Reputation: 162
I want to write a bash script that monitors the status of my server.
Currently I have the following line to log the ping:
ping -c 1 google.com | grep -A 1 "bytes from" | xargs -L 1 -I '{}' date '+"%F %T" {}' >> ping.log
Unfortunately the grep filter also filters out error messages, but I only want to remove tthe first line and the summary.
"2020-12-04 15:46:00" 64 bytes from 216.58.208.110 (216.58.208.110): icmp_seq=1 ttl=37 time=16.2 ms
"2020-12-04 15:47:00" Request Timed Out.
Is there another way to supress only the ping summary, so that error messages are also added to my log?
Upvotes: 0
Views: 1337
Reputation: 69
I am sure there is something weird about ping and stderr, as I have been trying to suppress ALL messages (as I use the return code to do other processing). I do this, as ANY messages from a cron task cause root mail, which, although fine to catch problems, is not how I want to catch a ping failure.
I have had these results :
ping -q -c 3 ians.guess-fail.com 2>&1 >/tmp/ping.txt
ping: ians.guess-fail.com: Name or service not known
ping -q -c 3 ians.guess-fail.com 2>&1 >/dev/null
ping: ians.guess-fail.com: Name or service not known
ping -q -c 3 ians.guess-fail.com 2>/dev/null >/tmp/ping.txt
# No output/messages produced!!!
I have no idea why... But I will use that last example.
Upvotes: 1
Reputation: 12887
Try using awk (in this case GNU awk) and so:
ping -c 1 www.google.co.uk | awk '/^---/ { exit } NR > 1 && !/^$/ { print strftime("%F %T")" "$0 }'
Take the ping output and print only the second line, lines that are not blank and then exit once we get to the start of the summary (starts with ---). For all other lines, print the line prefixed with the date, built with awk's strftime function.
Upvotes: 1