Bash script to reconnect Wi-Fi connection in Raspberry Pi
This is a simple bash script that monitors the Raspberry Pi for wireless connectivity. If the Raspberry Pi has lost its Wi-Fi connection, this script will attempt to reconnect.
This script assumes that the local address of your wireless router is 192.168.1.1. If your router has a different IP address, please replace that in this script.
Create a directory called crons under the home directory and
cd to it.
mkdir ~/crons cd ~/crons
Create script wifi_connect.sh under
~/crons and add these lines as contents:
# Ping to the router ping -c2 192.168.1.1 > /dev/null # If the return code from ping ($?) is not 0 (meaning there was an error) if [ $? != 0 ]; then # Restart the wireless interface ifdown --force wlan0 sleep 5 ifup wlan0 echo "wlan0 reconnected at `date`" fi
Chmod it to 755
chmod 755 ~/crons/wifi_reconnect.sh
Add cron entry to run this script every 12 hours.
Add this line:
0 */12 * * * sudo /home/pi/crons/wifi_reconnect.sh >> /tmp/wifi_reconnect.log
Save and exit by presing Ctrl+X, if you're using Nano editor.
That's all! Every 12 hours, this script will check if your wireless interface wl0 is connected to the router. If it is not connected, it will restart wlan0.
I have been using this script since 2012 and it has always worked great. Hopefully, it should work generically across all Raspberry Pi computer versions.
Created on 05 November 2016
Affiliate Disclosure: Some of the links to products on this blog are affiliate links. It simply means, at no additional cost to you, we’ll earn a commission if you click through and buy any product.