arul's code
free code snippets

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 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 under ~/crons and add these lines as contents:

# Ping to the router
ping -c2 > /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`"

Chmod it to 755

  chmod 755 ~/crons/

Add cron entry to run this script every 12 hours.

  crontab -e

Add this line:

0  */12   *   *   *    sudo /home/pi/crons/ >> /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.

Share this

Last Updated: Posted on 05 Nov 2016