6

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 2

13

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.

13

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
2
  • This works too.
    – John1024
    Jul 21, 2020 at 20:51
  • 3
    This only works in locales that use a period as the decimal separator (which seems to be OP's case). Setting LC_NUMERIC=C would take care of other locales.
    – TooTea
    Jul 22, 2020 at 9:07

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .