user2133606
user2133606

Reputation: 347

bash script to read/ping a list of ip addresses from a text file and then write the results to another file?

I have a text file with a lists of IP addresses called address.txt which contains the following

172.26.26.1   wlan01

172.26.27.65    wlan02

172.26.28.180    wlan03

I need to write a bash script that reads the only IP addresses, ping them and output to a another text file to something like this:

172.26.26.1 IS UP

172.26.27.65 IS DOWN

172.26.28.180 IS DOWN

I am fairly new to bash scripting so I am not sure where to start with this. Any help would be much appreciated.

Upvotes: 0

Views: 16776

Answers (1)

janos
janos

Reputation: 124656

In Linux this would work:

awk '{print $1}' < address.txt | while read ip; do ping -c1 $ip >/dev/null 2>&1 && echo $ip IS UP || echo $ip IS DOWN; done

I don't have a cygwin now to test, but it should work there too.

Explanation:

  • With awk we get the first column from the input file and pipe it into a loop
  • We send a single ping to $ip, and redirect standard output and standard error to /dev/null so it doesn't pollute our output
  • If ping is successful, the command after && is executed: echo $ip IS UP
  • If ping fails, the command after || is executed: echo $ip IS DOWN

Somewhat more readable, expanded format, to put in a script:

#!/bin/sh
awk '{print $1}' < address.txt | while read ip; do
    if ping -c1 $ip >/dev/null 2>&1; then
        echo $ip IS UP
    else
        echo $ip IS DOWN
    fi
done

Upvotes: 5

Related Questions