0
0
Bash Scriptingscripting~5 mins

Network monitoring script in Bash Scripting

Choose your learning style9 modes available
Introduction

A network monitoring script helps you check if your internet or network devices are working well. It alerts you if something is wrong.

You want to check if your website server is reachable.
You need to monitor if a printer or other device on your network is online.
You want to log network uptime and downtime automatically.
You want to get notified if your internet connection drops.
You want to track network response times over time.
Syntax
Bash Scripting
#!/bin/bash
ping -c <count> <host>
if [ $? -eq 0 ]; then
  echo "Host is reachable"
else
  echo "Host is unreachable"
fi

ping sends small messages to check if a host is reachable.

-c sets how many messages to send.

Examples
Sends 3 ping messages to google.com to check if it is reachable.
Bash Scripting
ping -c 3 google.com
Checks if the router at 192.168.1.1 is online and prints a message.
Bash Scripting
if ping -c 1 192.168.1.1 > /dev/null 2>&1; then
  echo "Router is online"
else
  echo "Router is offline"
fi
Sample Program

This script pings Google's DNS server twice. It prints if the network is up or down based on the ping result.

Bash Scripting
#!/bin/bash

HOST="8.8.8.8"
COUNT=2

ping -c $COUNT $HOST > /dev/null 2>&1
if [ $? -eq 0 ]; then
  echo "Network is up: $HOST is reachable"
else
  echo "Network is down: $HOST is unreachable"
fi
OutputSuccess
Important Notes

Use chmod +x script.sh to make your script executable.

Redirect ping output to /dev/null to keep the script output clean.

Check the exit status $? to know if the ping succeeded (0 means success).

Summary

A network monitoring script uses ping to check device reachability.

It helps detect network problems early by alerting when devices are unreachable.

Simple scripts can be automated to run regularly for continuous monitoring.