title: Bash script to bring up and down an interface on loop
body: <p>I use Ubuntu server as NAT router. WAN interface is <code>eth1</code> and LAN interface is <code>eth0</code>. I use ucarp virtual ip on LAN side for failover. I am writing a script which will bring down LAN interface <code>eth0</code> if WAN link or default gateway goes down (If LAN interface goes down, then ucarp can release the NAT gateway ip to another router on the network). Also if the WAN ip gets pinged then LAN interface should come up and should remain up until WAN ip can be pinged. </p>
  
  <p><strong>Bash Script:</strong></p>
  
  <pre><code>#!/bin/bash
  t1=$(ifconfig | grep -o eth0)
  t2="eth0"
  #RMT_IP = "8.8.8.8"
  SLEEP_TIME="10"
  
  ping -c 2 8.8.8.8 &gt; /dev/null
     PING_1=$?
  
  if [ $PING_1 = 1 ]; then
      if [ "$t1" != "$t2" ]; then
          ifconfig eth0 up
          echo "Iface brought up"
      else
          echo "Iface is already up"
      fi
  else
      if [ "$t1" = "$t2" ]; then
          ifconfig eth0 down
          echo "Iface brought down"
      else
          echo "iface already down"
      fi
  fi
  
  sleep $SLEEP_TIME
  </code></pre>
  
  <p>The script does not work for me. What I want is, if a WAN ip can be pinged then the LAN interface <code>eth0</code> should remain up. If the WAN ip cannot be pinged, then the interface should be brought down. The script should run on loop every 10 seconds. If the WAN ip cannot be pinged for extended period of time then <code>eth0</code> should remain down only and if the WAN ip gets pinged after some time then <code>eth0</code> should be brought up. I also plan to run the script on boot up as an upstart job. </p>
  
  <p><strong>EDIT 1:</strong> 
  My final script:</p>
  
  <pre><code>#!/bin/bash
  
  timeout=5         # delay between checks
  pingip='8.8.8.8'   # what to ping
  iface="eth0"
  LOG_FILE="/var/log/syslog"
  isdown=0            # indicate whether the interface is up or down
                     # start assuming interface is up
  
  while true; do
      LOG_TIME=`date +%b' '%d' '%T`
      if ping -q -c 2 "$pingip" &gt;&gt; /dev/null ; then      # ping is good - bring iface up
          if [ "$isdown" -ne 0 ] ; then
              ifup $iface &amp;&amp; isdown=0
              printf "$LOG_TIME $0: Interface brought up: %s\n" "$iface" | tee -a $LOG_FILE
          fi
      else                                 # ping is bad - bring iface down
          beep -f 4000
          if [ "$isdown" -ne 1 ] ;  then
              ifdown $iface &amp;&amp; isdown=1
              printf "$LOG_TIME $0: Interface brought down: %s\n" "$iface" | tee -a $LOG_FILE
          fi
      fi
      sleep "$timeout"
  done
  </code></pre>