Bash script to reconnect Wi-Fi connection in Raspberry Pi

Published on 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.

Ubuntu_ Can't connect to Starbu...
Ubuntu_ Can't connect to Starbucks wifi

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.

Steps

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.

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.

Table of Contents

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.

Published on November 05, 2016

← Previous Post Various MySQL commands

Parsing Web Server Logs Next Post →