First, all the below assumes that your ping
command has output formatted such that your original awk works as-is. If that assumption isn't true (and not all ping
commands do work with that, f/e, one I'm trying to test with puts the value in $10
instead of $9
), the below examples (except for the pure-bash one that doesn't use awk at all) aren't expected to work either.
A better implementation of the checkOnline
function could look like:
# caution: this awk code doesn't work for all versions of ping
awkTTL() { ping 8.8.8.8 -c 1 | awk -F '[ :=]' '/ttl/ {print $9}'; }
checkOnline() {
if [[ $(awkTTL) -ge 2 ]]; then
echo "online"
else
echo "offline"
fi
}
Using a command substitution (the $( ... )
syntax) means we're putting the output of running awkTTL
into the [[
argument list, instead of the string 'awkTTL'
. Because the string 'awkTTL'
isn't a number, attempts to compare it against a number fail.
By the way, you could also just do the whole thing in awk, and not need bash to read or compare awk's output at all:
# note that this still assumes ttl is in $9, per the OP's original code
checkOnline() {
awk -F '[ :=]' '
BEGIN { ttl=0 }
/ttl/ && $9 ~ /^[[:digit:]]+$/ { ttl=$9 }
END { if (ttl >= 2) { print "online" } else { print "offline" } }
' < <(ping 8.8.8.8 -c1)
}
...or, to do the whole thing in bash, without any need for awk:
checkOnline() {
local line highestTTL=0
while IFS= read -r line; do
if [[ $line =~ [[:space:]]ttl=([[:digit:]]+)([[:space:]]|$) ]]; then
highestTTL=${BASH_REMATCH[1]}
fi
done < <(ping 8.8.8.8 -c 1)
if (( highestTTL >= 2 )); then
echo "online"
else
echo "offline"
fi
}