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:
- To restart the Raspberry Pi upon sensing no Internet.
- To restart the Wi-Fi of the Raspberry Pi upon sensing no Internet.
Choose one and let's explore both of them!
- 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
main() {
ping -c4 192.168.1.1 > /dev/null
if [ $? != 0 ]; then
sudo /sbin/shutdown -r now
fi
}
main
# 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 usingreboot-when-no-wifi.sh
.
*/5 * * * * /usr/bin/sudo -H $HOME/Projects/restartpi/reboot-when-no-wifi.sh >> /dev/null 2>&1
- Done!