I am creating a bash script to get cpu%, pps & incoming kbps
#!/bin/bash
INTERVAL="0.5" # update interval in seconds
IFS="enp0s3"
while true
do
# Read /proc/stat file (for first datapoint)
read cpu user nice system idle iowait irq softirq steal guest< /proc/stat
# compute active and total utilizations
cpu_active_prev=$((user+system+nice+softirq+steal))
cpu_total_prev=$((user+system+nice+softirq+steal+idle+iowait))
sleep $INTERVAL
# Read /proc/stat file (for second datapoint)
read cpu user nice system idle iowait irq softirq steal guest< /proc/stat
# compute active and total utilizations
cpu_active_cur=$((user+system+nice+softirq+steal))
cpu_total_cur=$((user+system+nice+softirq+steal+idle+iowait))
# compute CPU utilization (%)
cpu_util=$((100*( cpu_active_cur-cpu_active_prev ) / (cpu_total_cur-cpu_total_prev) ))
echo "CPU: $cpu_util"
R4=$(cat /sys/class/net/$IFS/statistics/rx_bytes)
sleep $INTERVAL
R5=$(cat /sys/class/net/$IFS/statistics/rx_bytes)
R8BPS=$(expr $R5 - $R4)
RKBPS=$(expr $R8BPS / 125)
echo "IN: $RKBPS"
R1=$(cat /sys/class/net/$IFS/statistics/rx_packets)
T1=$(cat /sys/class/net/$IFS/statistics/tx_packets)
sleep $INTERVAL
R2=$(cat /sys/class/net/$IFS/statistics/rx_packets)
T2=$(cat /sys/class/net/$IFS/statistics/tx_packets)
RBPS=$(expr $R2 - $R1)
echo "PPS : $RBPS"
done
I am getting a syntax error:
line 11: u 2: syntax error in expression (error token is "2")
Can someone please help me to fix this?
IFS
variable (ifs
, for example). TheIFS
variable is special, and the shell uses it to split any string resulting from unquoted expansions into words. Withthe value of$IFS
as you have in the script, the string0.02
would be split into the two words.
and2
(since$IFS
contains0
). – Kusalananda Aug 29 '22 at 10:14IFS
. Also remember to paste your code into https://shellcheck.net/ to check for errors – Chris Davies Sep 02 '22 at 10:54