Jak
Jak

Reputation: 67

How to do arithmetic inside a bash while loop?

I am starting a script and know that this while loop is incorrect syntax but I am curious if there is any way to do this type of conditional statement in bash?

#Network Bandwidth Utilization

line=$(ifstat | head -n 7)
echo $line

interface=$(echo line | cut -f 1 -d ' ')
RXPktsRate=$(echo line | cut -f 2 -d ' ')
TXPktsRate=$(echo line | cut -f 3 -d ' ')
RXDataRate=$(echo line | cut -f 4 -d ' ')
TXDataRate=$(echo line | cut -f 5 -d ' ')

echo $interface $RXPktsRate $TXDataRate

while [ (( $SECONDS % 5 )) == 0 ] && [ $SECONDS <= 900 ];do
    echo hi
done

Upvotes: 3

Views: 3132

Answers (2)

Sam
Sam

Reputation: 859

For arithmetic tests in bash you generally don't want to use the [ test-builtin but rely on the more sophisticated arithmetic evaluation within double parentheses, i.e.

while ((SECONDS % 5 == 0 && SECONDS <= 900)); do
    echo hi
done

SECONDS % 5 == 0 could also be written as !(SECONDS % 5), as within double parentheses, similarly as in C, a zero value evaluates to "false", while any non-zero integer value evaluates to "true".

Note that variables do not need to be prefixed with the dollar symbol within double parentheses.

Also note that only integer arithmetic is built in in bash. If you want to do floating point arithmetic you can still achieve this with the help of some other scripting tool such as the bc calculator language.

Upvotes: 9

Soveu
Soveu

Reputation: 19

Well, your script is pretty close to being correct. You can perform arithmetic operations by placing integer expressions using the following format $((expr)), for example echo $(( 5 % 3 )) outputs 2.

And instead of <= operand you can use -le (le stands for Less or Equal), which does the same and works without any additional magic.

while [ $(( $SECONDS % 5 )) == 0 ] && [ $SECONDS -le 900 ];do
    echo hi
done

Upvotes: 0

Related Questions