Fernando Retimo
Fernando Retimo

Reputation: 1073

Bash Syntax error in conditional expression

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!

Upvotes: 1

Views: 2680

Answers (2)

joeytwiddle
joeytwiddle

Reputation: 31285

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

Upvotes: 1

Wilf
Wilf

Reputation: 743

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

Upvotes: 1

Related Questions