Bash Script If Ping Fails Then Automatically Reboot Server

In this article I will show simile bash script if ping fails then reboot Linux server. You can easily modify this script for example if ping fails then send notification to email, or if ping successful then do something.

Create a File

SSH login into your Linux server as root, and create new text file using touch command.

# touch

Make a File Executable

Now we need make a new created bash script file executable.

Just run:

# chmod +x

Script If Ping Fails Then …

This script will ping target host 3 times, every 10 min. If responses count equal 0 will write date and time in inetmonit.log log file, then execute system reboot command: shutdown -r 0.

Open file with text editor and paste script text:


# Set target host IP or hostname

count=$(ping -c 3 $TARGET_HOST | grep from* | wc -l)

if [ $count -eq 0 ]; then
    echo "$(date)" "Target host" $TARGET_HOST "unreachable, Rebooting!" >>/var/log/inetmonit.log
    /sbin/shutdown -r 0

    echo "$(date) ===-> OK! " >>/var/log/inetmonit.log

Edit TARGET_HOST if you need.

Save and close file.

Cron Job Setup

Now we need setup cron job for executing our monitoring script every 10 min and ping. To schedule jobs edit crontab file with command:

# crontab -e

Paste this text:

*/10 * * * * /path_to/

Then edit path to your script location.

If you want to change the checks interval, change 10 min to your value. For check every 5 min:

*/5 * * * *

Save and close text editor.

That’s it! Now this script will check your internet connection every 10 min. and automatically reboot host if connection lost.

inetmonit in GitHub.

Discuss article in ArsTech Forum


If you like what you are reading, please:

Buy me a coffeeBuy me a coffee


Start the discussion at