On my Arch system, ping
results for a host that can and for a host that cannot be reached look like this:
$ ping -c1 8.8.8.8
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_seq=1 ttl=118 time=39.8 ms
--- 8.8.8.8 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 39.846/39.846/39.846/0.000 ms
and
$ ping -c 1 10.0.10.1
PING 10.0.10.1 (10.0.10.1) 56(84) bytes of data.
--- 10.0.10.1 ping statistics ---
1 packets transmitted, 0 received, 100% packet loss, time 0ms
Assuming your output is identical, and assuming that the failed connection's output is saved in $badPing
an the successful one's in $goodPing
, you can do:
$ awk -F= '/time=/{k=sub(/ms/,""); l=$NF}END{print k ? l : "no connection" }' <<< "$badPing"
no connection
$ awk -F= '/time=/{k=sub(/ms/,""); l=$NF}END{print k ? l : "no connection" }' <<< "$goodPing"
39.8
The command above uses =
as the field separator. Then, on every line that contains the string time=
, it replaces the first occurrence of the string ms
on that line (note that this assumes only one occurrence of ms
on the relevant line; if that isn't the case for you, use sub(/ms/,"",$NF)
instead) which leaves us with just the numerical value as the last field, and saves the number of replacements made in k
and the last field as l
.
Then, after we have processed the entire input, if k
is set, so if a replacement occurred, we print out the value of l
and if not, we print out no connection
.
Alternatively, you can set the value of l
at the beginning and then just print it:
$ awk -F= -v l="no connection" '/time=/ && sub(/ms/,""){l=$NF}END{print l}' <<< "$badPing"
no connection
$ awk -F= -v l="no connection" '/time=/ && sub(/ms/,""){l=$NF}END{print l}' <<< "$goodPing"
39.8
To make your original approach work, just add having a second field as a conditional and set a variable based on it. Then you can print the second field when it exist, and print no connection
at the end if the variable isn't set. Like this:
$ awk -F 'time=| ms' '($2){print $2;k=1}END{ if(!k) print "no connection"}' <<< "$goodPing"
39.8
$ awk -F 'time=| ms' '($2){print $2;k=1}END{ if(!k) print "no connection"}' <<< "$badPing"
no connection
fping
might be easier, if that's an optionping
output and ii) tell us your operating system so we know what tools and what versions of tools you have available.