Skip to content

Instantly share code, notes, and snippets.

@lauslim12
Created August 19, 2022 14:16
Show Gist options
  • Save lauslim12/34f8970de003914d3ee4ca31ba745881 to your computer and use it in GitHub Desktop.
Save lauslim12/34f8970de003914d3ee4ca31ba745881 to your computer and use it in GitHub Desktop.
Yeah, we know Raspberry Pi sometimes loses its connection to Wi-Fi and you have to dirty your hands.

Restart Pi

Yeah, we know that sometimes Raspberry Pi loves to lose its internet connection. Once that is done, you have to unplug and replug it again, which is a real pain.

This helps to mitigate that issue. There are two scripts:

  1. To restart the Raspberry Pi upon sensing no Internet.
  2. To restart the Wi-Fi of the Raspberry Pi upon sensing no Internet.

Choose one and let's explore both of them!

Usage

  • Create a folder where you can place the script.
mkdir -p $HOME/Projects/restartpi
  • Make two files.
touch reboot-when-no-wifi.sh restart-wifi.sh
  • Write scripts like the following:

reboot-when-no-wifi.sh

# reboot-when-no-wifi.sh
main() {
    ping -c4 192.168.1.1 > /dev/null

    if [ $? != 0 ]; then
        sudo /sbin/shutdown -r now
    fi
}

main

restart-wifi.sh

# restart-wifi.sh
main() {
    ping -c4 192.168.1.1 > /dev/null

    if [ $? != 0 ]; then
        echo "No network connection, restarting 'wlan0'..."
        /sbin/ifdown 'wlan0'
        sleep 5
        /sbin/ifup --force 'wlan0'
    fi
}

main
  • Change permissions.
sudo chmod 775 $HOME/Projects/restartpi/reboot-when-no-wifi.sh
sudo chmod 755 $HOME/Projects/restartpi/restart-wifi.sh
  • Make a cronjob (crontab -e) which would run every five minutes. Don't run both scripts at once! Choose one. In this case, I am using reboot-when-no-wifi.sh.
*/5 * * * * /usr/bin/sudo -H $HOME/Projects/restartpi/reboot-when-no-wifi.sh >> /dev/null 2>&1
  • Done!

Credits

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment