I'm trying to write a bash script that (once added to cronjobs) will do the following:
1. Checks if wi-fi is up by doing a ping to google.com => if ok exit. If not increment a env. variable.
2. (at second run) if env. variable is 1 (e.g. the ping test failed at previous run) reset the usb interface (with an external script that works fine) and increment the env. variable again (set it to 2) and exit
3. (at third run) if env. variable is 2 then reset the network interface again (otherwise wi-fi will still not work) and set env. variable to 0 (back to step 1)
I realize that this might not be the optimum way, but I'm very new to bash scripting. So what I did so far:
Code: Select all
#!/bin/bash
if [ -n $TESTVAR ]
then
if [ "$TESTVAR" == "0" ]
then
ping -c 3 www.google.com > /dev/null 2>&1
date '+%Y-%m-%d %H:%M:%S all ok' >> /var/log/checkconnection.log
if [ $? -ne 0 ] ; then
date '+%Y-%m-%d %H:%M:%S Connection Unavailable' >> /var/log/checkconnection.log
/etc/init.d/networking restart
export TESTVAR=$((TESTVAR+1))
fi
exit
fi
if [ "$TESTVAR" == "1" ]
then
./usbreset /dev/bus/usb/001/005
export TESTVAR==$((TESTVAR+1))
date '+%Y-%m-%d %H:%M:%S USB reset' >> /var/log/checkconnection.log
exit
fi
if [ "$TESTVAR" == "2" ]
then
ping -c 3 www.google.com > /dev/null 2>&1
if [ $? -ne 0 ] ; then
date '+%Y-%m-%d %H:%M:%S Connection Unavailable after usb reset' >> /var/log/checkconnection.log
/etc/init.d/networking restart
export TESTVAR=0
fi
exit
fi
fi
My first problem is that the line:
export TESTVAR=$((TESTVAR+1))
does not seem to increment the env. variable
I managed to make it execute, and I even checked with echo that indeed it does:
export TESTVAR=1
but still:
root@raspberrypi:/home/pi# echo "$TESTVAR"
0
From what I read about variables they are not always set for the same "environments" (not sure how else to say it), but I'm thinking there must be a way to have true global variables that can be set and read from anywere.