Raspberry Pi/Rasbian Linux - Bash script to check and maintain the WIFI network connection

Posted by Blake on 2/19/2015
)

Here is a simple script that you can run and schedule via scheduled cron job that will check the status of your network adapter and attempt to force restart it if it's not connected. This is handy if you're using the Raspberry Pi as a headless utility device that may have a weak WIFI connection that drops from time to time. I currently run this script via a cronjob every 5 minutes and write the output to a log file (I like writing both successes and failures so I can see that the job is running consistently).

The one note in my script that might require a change depending on your setup is that the wireless adapter you're using is named "wlan0" (which will probably be the case in most common setups). Here is the contents of my bash script:

isup

#!/bin/bash

ip=$(hostname -I)

if ifconfig wlan0 | grep -q "inet addr:" ; then
   echo [$(date)] ${ip}-  Network up
else
   echo [$(date)] ${ip}-  ERROR - Network DOWN
   sudo ifup --force wlan0
fi
Here is my entry for the cron job started via "sudo crontab -e":
# Every 5 minutes it will make a network log on whether the network is up
*/5 * * * * sudo /home/pi/Utilities/isup >> /home/pi/net-log.txt