[lug] Bash Scripting Ping

Jed S. Baer blug at jbaer.cotse.net
Sun Nov 8 11:21:13 MST 2020


On Sun, 8 Nov 2020 10:53:09 -0700 (MST)
D. Stimits wrote:

> I am curious about something in bash scripting which does not seem to be
> particularly easy. I wanted to script "ping -O -D address" such that each
> line gets processed by some logic if the ping fails. Redirecting ping to
> a variable does not work because it only "returns" when the ping exits
> (each line is not an exit). Even if I were to fork and exec, the forked
> process would itself have the same problem.
> 
> Is there some simple/clever way to process each line of a ping in bash
> without killing off the ping itself? My goal was to send it through some
> database and statistics type processing as success/failure lines occur.

I'm not sure of quite what you want. Is it necessary to process this in
real time? And you say "...if ping fails", but then "... as success/failure
lines occur."

The super simple thing is a bash read loop. But you won't know the exit
status until the ping finishes.

$ ping -c 3 -D -O n.n.n.n | while read LINE;
> do
> echo $LINE
> done

Bash read will do token separation using IFS, so you could do
  | while read FIELD1 FIELD2 etc

Offhand, if the exit status of ping must be known before processing, then
redirect ping output to a file, check status, then you can still do a bash
read loop to process the file. If needed, the bash mktemp command will
generate a unique tmp filename for your ping output.

-- 
All operating systems suck, but Linux just sucks less
 - Linus Torvalds


More information about the LUG mailing list