Bash script to reconnect Wi-Fi connection in Raspberry Pi

Published November 05, 2016

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 directory

Create a directory called crons under the home directory and cd to it.

mkdir ~/crons
cd ~/crons

Create bash script

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 crontab entry for every 12 hours

Add cron entry to run this script every 12 hours.

crontab -e

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.

Related Posts

If you have any questions, please contact me at arulbOsutkNiqlzziyties@gNqmaizl.bkcom. You can also post questions in our Facebook group. Thank you.

Disclaimer: Our website is supported by our users. We sometimes earn affiliate links when you click through the affiliate links on our website.

Last Updated: November 05, 2016.     This post was originally written on November 05, 2016.

← Previous Post
Various MySQL commands

Next Post →
Parsing Web Server Logs