bashshellexpr

bash script expr - arithmetic syntax error


I have made a bash script to monitor my network traffic every 10 sec using ifconfig. It must be ifconfig else I would have used a different tool.

My issue is because my counter is so high number I have to use expr to do the calculation, however expr is causing me some issues.

#!/bin/bash
#run for how many seconds

savefile=/root/eth0.csv
timer=10

echo "EPOCH,Interface,TX,RX,ChangeTx,ChangeRX" >> $savefile

END=8640
x=$END
while [ $x -gt 0 ]; do

ETH0RX=`ifconfig | grep eth0 -A8 | grep "RX bytes" | tr -s ' ' | cut -d':' -f2 | cut -d ' ' -f1`
ETH0TX=`ifconfig | grep eth0 -A8 | grep "RX bytes" | tr -s ' ' | cut -d':' -f3 | cut -d ' ' -f1`

#ETH0 RX
ETH0RXcurrentvalue=$ETH0RX
ETH0RXchange=$(expr $ETH0RXcurrentvalue - $ETH0RXpreviousvalue)
ETH0RXpreviousvalue=$ETH0RXcurrentvalue

#ETH0 TX
ETH0TXcurrentvalue=$ETH0TX
ETH0TXchange=$(expr $ETH0TXcurrentvalue - $ETH0TXpreviousvalue)
ETH0TXpreviousvalue=$ETH0TXcurrentvalue

epoch=`date +%s`

echo $epoch,ETH0,$ETH0TX,$ETH0RX,$(($ETH0RXchange*8)),$(($ETH0TXchange*8)) >> $savefile

sleep $timer

x=$(($x-1))
done;

My error is line 33: arithmetic syntax error (which is done; ). The script works fine if there is no expr, however due to big numbers I need to use expr (I cannot use bc).


Solution

  • I have fixed the issue,

    As I'm trying to do an

    expr

    and then later on the script I do another calculation the

    expr

    continuously giving error because of the other line where the calculation was via echo.

    so I fixed using the code below.

    ETH0RXcurrentvalue=$ETH0RX
    ETH0RXchange=$(expr "$ETH0RXcurrentvalue" - "$ETH0RXpreviousvalue")
    ETH0RXpreviousvalue=$ETH0RXcurrentvalue
    ETH0RXchange1=$(expr "$ETH0RXchange" \* "8")
    echo $ETH0RXchange1
    echo $ETH0TXchange1
    
    
    echo $epoch,ETH0,$ETH0TX,$ETH0RX,$ETH0RXchange1,$ETH0TXchange1 >> $savefile