[lug] Bash Scripting Ping

D. Stimits stimits at comcast.net
Sun Nov 8 11:27:21 MST 2020


> On 11/08/2020 11:21 AM Jed S. Baer <blug at jbaer.cotse.net> wrote:
> 
>  
> 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."

I'd like to know if there is a way to pipe the output of ping such that each line is equivalent to a loop iteration. Pseudo code:
   while (ping text line); do
      line | edit line; # e.g., substituting microseconds for date.
      print edit line if conditions are met; # e.g., a few lines of fail prior to print.
   done

I'm not actually concerned that this is ping so much as I am trying to figure out how a newline from a continuous command can be used to trigger a loop iteration. It has become something of a "brain teaser" for me. It is easy if the ping itself ends with a single ping. It is also easy if you run ping all day and only then process the results upon exit of ping. I am now just really curious how the newline delimited continuous output of ping can be used to trigger something else despite the continuous output itself not stopping.

> 
> 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
> _______________________________________________
> Web Page:  http://lug.boulder.co.us
> Mailing List: http://lists.lug.boulder.co.us/mailman/listinfo/lug
> Join us on IRC: irc.hackingsociety.org port=6667 channel=#hackingsociety


More information about the LUG mailing list