1

I'm trying to make a simple bash script that will iterate through a text file containing IP addresses, ping them one time, and see if they are alive or not.

This is my work so far:

#!/bin/bash

for ip in $(cat ips.txt); do
if [[ "1" ==  "$(ping -c 1 $ip | grep 'packets transmitted' | cut -d ' ' -f 4)"]]
echo $ip
fi
done

Any Suggestions? Thanks!

Fernando Retimo
  • 1,003
  • 3
  • 13
  • 25
  • What is the error which you are getting ? – ak0053792 Jun 28 '14 at 20:55
  • 4
    You need a space before the final `]]`. And you're missing the `then` after that (and if the `then` is on the same line, you'll need a `;` before it). – ooga Jun 28 '14 at 20:56

2 Answers2

1

This seems to work:

#!/bin/bash
for ip in $(cat ips.txt); do
if [ "1" ==  "$(ping -c 1 $ip | grep 'packets transmitted' | cut -d ' ' -f 4)" ]; then
    echo $ip
fi
done

You needed the ; then after the if [ ... ] statement (same thing goes for elif, not else), and a space between the last bracket of the statement and the statement's contents. Also this appears to work fine with just single brackets, and this may be more portable (see here).

Works on Bash 4.2.47

Community
  • 1
  • 1
Wilf
  • 713
  • 1
  • 11
  • 26
  • 1
    `for ip in $(cat ips.txt)` is, by the way, generally deprecated as a way to loop over contents of a file. See http://mywiki.wooledge.org/DontReadLinesWithFor – Charles Duffy Jun 28 '14 at 23:38
1

Yes. You can use a newline instead of ; if you like, but you always need the then keyword.

if [ "1" ==  "$(ping -c 1 $ip | grep 'packets transmitted' | cut -d ' ' -f 4)" ]
then echo $ip
fi

# or

if [ "1" ==  "$(ping -c 1 $ip | grep 'packets transmitted' | cut -d ' ' -f 4)" ]
then
    echo $ip
fi
joeytwiddle
  • 29,306
  • 13
  • 121
  • 110