TransWikia.com

How do you read STDOUT into variables in bash?

Unix & Linux Asked on November 14, 2021

I read the bandwidth usage by ifstat, which prints the download and upload into STDOUT every second.

ifstat -i wlp7s0
      wlp7s0      
 KB/s in  KB/s out
 1390.13     81.20
 1039.14     74.05
 1810.63    102.08
  865.60    183.15
 1272.91    274.19
 1174.00    400.04

How can I run ifstat in a bash script and read the values into variables for an if statement to run a command if the values are smaller than an amount?

For example,

if [ $in -lt 100 ] && [ $out -lt 100 ]
then
   echo Network is slow.
else
   echo Network is fast.
fi

How can I read the output of ifstat into $in and $out variables to check the if statement every second?

2 Answers

John1024 is right about floating point numbers, but we can just truncate the numbers. With plain bash:

n=0
LC_NUMERIC=C  ifstat -i $interface  
| while read -r in out; do
  ((++n < 2)) && continue # skip the header
  if (( ${in%.*} < 100 && ${out%.*} < 100 )); then
    echo Network is slow.
  else
    echo Network is fast.
  fi
done

Answered by glenn jackman on November 14, 2021

Since the network speeds are not integers, we need to supplement with other tools such as awk to process the numbers. Try:

ifstat -ni wlp7s0 | awk 'NR>2{if ($1+0<100 && $2+0<100) print "Network is slow."; else print "Network is fast."}'

Or, for those who like their commands spread over multiple lines:

ifstat -ni wlp7s0 | awk '
    NR>2{
        if ($1+0<100 && $2+0<100)
            print "Network is slow."
        else
            print "Network is fast."
    }'

How it works

The -n option is added to ifstat to suppress the periodic repeat of the header lines.

NR>2{...} tells awk to process the commands in curly braces only if the line number, NR, is greater than two. This has the effect of skipping over the header lines.

if ($1+0<100 && $2+0<100) tests whether both the first field, $, and the second field, $2, are less than 100. If they are, then print "Network is slow." is executed. If not, then print "Network is fast." is executed.

Answered by John1024 on November 14, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP