Bash Script to Ping Multiple Hosts with Output
for host in host1 host2; do ping -c 1 -W 1 $host && echo "$host is reachable" || echo "$host is unreachable"; done to ping multiple hosts and show their status.Examples
How to Think About It
Algorithm
Code
#!/bin/bash hosts="google.com github.com invalid.host" for host in $hosts; do if ping -c 1 -W 1 $host > /dev/null 2>&1; then echo "$host is reachable" else echo "$host is unreachable" fi done
Dry Run
Let's trace pinging 'google.com' and 'invalid.host' through the script
Set hosts variable
hosts="google.com invalid.host"
Start loop with host=google.com
ping -c 1 -W 1 google.com runs and succeeds
Print result for google.com
Output: google.com is reachable
Next loop with host=invalid.host
ping -c 1 -W 1 invalid.host runs and fails
Print result for invalid.host
Output: invalid.host is unreachable
| Host | Ping Result | Output |
|---|---|---|
| google.com | Success | google.com is reachable |
| invalid.host | Fail | invalid.host is unreachable |
Why This Works
Step 1: Loop over hosts
The script uses a for loop to go through each host in the list one by one.
Step 2: Ping each host once
It runs ping -c 1 -W 1 to send one ping and wait 1 second for a reply, checking if the host is reachable.
Step 3: Check ping success
If ping returns success, the script prints the host is reachable; otherwise, it prints unreachable.
Alternative Approaches
#!/bin/bash while read -r host; do if ping -c 1 -W 1 "$host" > /dev/null 2>&1; then echo "$host is reachable" else echo "$host is unreachable" fi done < hosts.txt
#!/bin/bash hosts="google.com github.com invalid.host" for host in $hosts; do (ping -c 1 -W 1 $host > /dev/null 2>&1 && echo "$host is reachable" || echo "$host is unreachable") & done wait
fping -c1 -t300 google.com github.com invalid.host
Complexity: O(n) time, O(1) space
Time Complexity
The script pings each host once, so time grows linearly with the number of hosts.
Space Complexity
The script uses constant extra memory regardless of the number of hosts.
Which Approach is Fastest?
Parallel pinging runs faster but is more complex; sequential pinging is simpler and easier to understand.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Sequential ping loop | O(n) | O(1) | Simple scripts with few hosts |
| Parallel ping with background jobs | O(1) to O(n) depending on system | O(n) | Speeding up many hosts |
| fping tool | O(n) | O(1) | Efficient multi-host pinging with external tool |
-W 1 with ping to limit wait time and speed up the script.