3

I have this:

 ping -q xxx.xxx.xxx.xxx & disown; pingpid=$!
 for run in {1..3}; do
 sleep 5
 stats+=$(kill -SIGQUIT $pingpid)
 done
 kill $pingpid

So basically I launch ping in background with -q option (to show just stats), get its PID and then execute a for loop in which I want to store the intermediary stats of ping on each kill -SIGQUIT $pingpid in a variable... that's 3 lines of stats, 5 seconds apart.

I can see the intermediary stats being printed to stdout but when I check the $stats variable, I find it empty. I also tried with stderr redirection to stdout but I still can't get the variable to have the stats stored in it.

one-liner
  • 791
  • 1
  • 9
  • 19
  • Good question... Looks like whatever prints as a result of the `kill -SIGQUIT` is not using a standard output stream. `>` and `2>` certainly perform no redirection. – arco444 Mar 06 '15 at 12:32

2 Answers2

2

The output that you're trying to capture is coming from the ping process (on it's standard error to be precise), not the kill process. You need to capture its output with a redirection when you launch it. Try this:

stats=""
{
        read pingpid
        for run in {1..3}; do
                sleep 5
                kill -quit $pingpid
                read line
                stats+="$line"$'\n'
        done
} < <(ping -q xx.xx.xx.xx 2>&1 >/dev/null & echo $!)

kill $pingpid
stats=${stats%$'\n'}  # Remove the extra newline
echo "$stats"

The ordering of the redirection in the ping command, 2>&1 >/dev/null, redirects standard out to /dev/null while standard error is redirected to the input of the loop.

ccarton
  • 3,556
  • 16
  • 17
1

What are you actually trying to accomplish here? It seems like you should actually be running ping with a timeout, or a limited number of packets (amounts to the same thing in the end).

for run in 1 2 3; do
    ping -c 5 -q 12.34.56.78 | tail -n 2
done

The regular output from ping is somewhat more verbose than the single line you get when you send it a SIGQUIT, so we need two lines of output. Perhaps you want to pipe to some simple Awk script to normalize the output to make it fit your needs, or perhaps transform it to a properly machine-readable format.

tripleee
  • 175,061
  • 34
  • 275
  • 318