Wednesday 2 August 2023

How to check ping able IP address in total using a bash script?

Create a bash script as following:-

#!/bin/bash
# Array of IP addresses to ping
ip_addresses=(
192.168.1.1
192.168.1.2
192.168.1.3
)
# Variables to count successful and unsuccessful pings
ping_success=0
ping_fail=0
# Function to perform the ping and update the counters
ping_ips() {
for ip in "${ip_addresses[@]}"; do
ping -c 1 "$ip" > /dev/null 2>&1
if [ $? -eq 0 ]; then
echo "Ping to $ip succeeded"
((ping_success++))
else
echo "Ping to $ip failed"
((ping_fail++))
fi
done
}
# Call the function
ping_ips
# Print the results
echo "Total IPs: ${#ip_addresses[@]}"
echo "Ping Success: $ping_success"
echo "Ping Fail: $ping_fail"

No comments:

Post a Comment