if [[ `ping -c $count "$HNAME"` ]]
This runs ping
in a command substitution (using the old backtick syntax, instead of the saner $(...)
). The resulting output is put on the command line, and then [[ .. ]]
, tests to see if the output is empty. (That is, regular output. Command substitution doesn't capture error output, which would still be sent to the script's error output.)
If ping
outputs anything, the test succeeds. E.g. on my system:
$ ping -c1 1.2.3.4 2>/dev/null
PING 1.2.3.4 (1.2.3.4) 56(84) bytes of data.
--- 1.2.3.4 ping statistics ---
1 packets transmitted, 0 received, 100% packet loss, time 0ms
Since 1.2.3.4
is a valid IP address, ping
tries to contact it. With an invalid IP address or a nonexisting hostname, it would only print an error, and the standard output would be empty.
A better way to test if a host is up would be to test the exit status of ping
, and redirect its output away:
host=1.2.3.4
if ping -c1 "$host" >/dev/null 2>&1; then
echo "'$host' is up"
else
echo "'$host' does not respond (or invalid IP address/hostname)"
fi
Note that the quoting in the echo
commands is off:
echo ""$HNAME" seems to be down."
This has an empty quoted string ""
, then an unquoted parameter expansion $HNAME
, and then the quoted string " seems to be down."
. For various reasons, it's better to quote all paremeter expansions, so use "$var blahblah"
, or "\"$var\" blahblah"
if you want to put quotes around the variable in the output.
See:
news-15.net seems to be down. Pity.
– Siva Aug 16 '18 at 11:50ping "$HNAME"
? – RudiC Aug 16 '18 at 11:53ping -c $count "$HNAME" > /dev/null 2>&1
echo "ping exit code is $?" # return 1
It print 1 with nonexistent ip... But in the if statement it prints out "$HNAME up " – artemmiet Aug 16 '18 at 13:44