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!

2
  • What is the error which you are getting ? Commented Jun 28, 2014 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). Commented Jun 28, 2014 at 20:56

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

for ip in $(cat ips.txt) is, by the way, generally deprecated as a way to loop over contents of a file. See mywiki.wooledge.org/DontReadLinesWithFor
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.