title: Using "watch" to run a function repeatedly in Bash?
body: <p>This is my first Bash script. I have a WiFi issue with my Debian machine. I'm not here to ask about the cause, but rather how to put a band-aid on the issue with Bash. My WiFi will drop out at a random time, usually every 12-15 minutes. I use SSH on this server, and do not want to have to run <code>ifdown wlan0</code> and <code>ifup wlan0</code> (which reconnects the WiFi) manually from the physical server. </p>
  
  <p>The function of this Bash script is to attempt to connect three times. If it fails three times, it will give up. Otherwise, every three seconds it will check whether or not my server is connected by attempting to ping Google. </p>
  
  <pre><code>#!/bin/bash
  
  ATTEMPTS=1
  
  function test_connection {
    ping -c 1 www.google.com
    local EXIT_CODE=$?
    if [ $EXIT_CODE -eq 0 ]
      then
        return true
      else
        return false
    fi
  }
  function reset_connection {
    ifdown wlan0
    ifup wlan0
    EXIT_CODE=$((EXIT_CODE+1))
  }
  function connection_test_loop {
    if [ $ATTEMPTS -ge  3 ]
      then
        echo CONNECTION FAILED TO INITIALIZE ... ATTEMPT $ATTEMPTS FAILED ... EXITING
        exit
    fi
    if ! [ test_connection ]
      then
        echo CONNECTION DROPPED ... ATTEMPTING TO RE-ESTABLISH CONNECTION ... ATTEMPT $ATTEMPTS
        reset_connection
    fi
  }
  
  test_connection
  if [ $? ]
    then
      echo CONNECTION PRE-ESTABLISHED
      watch -n 3 connection_test_loop
    else
      echo CONNECTION FAILED TO INITIALIZE ... ATTEMPTING TO RESET CONNECTION ... ATTEMPT $ATTEMPTS
      reset_connection
      if [ $? ]
        then
          echo CONNECTION ESTABLISHED
          watch -n 3 connection_test_loop
        else
          echo CONNECTION FAILED TO INITIALIZE ... ATTEMPT $ATTEMPTS FAILED ... EXITING
          exit
      fi
  fi
  </code></pre>
  
  <p>I've isolated the issue I'm having with this script. It lies in calling the <code>connection_test_loop</code> function with <code>watch</code>. I've been unable to find any information as to why this isn't performing as expected and running the function every three seconds.</p>