user14795102
user14795102

Reputation: 17

How do I save greater number in variable in Bash shell script?

I have a bash shell app that count rx and tx packets. These packets every second has change then save it inside SUM variable. My goal is to save greater number in new variable. How can I do that?

SUM=$(expr $TKBPS + $RKBPS)

now=$(( $SUM))

if [ $now -gt $SUM ] ; then
    max=$(( $now ))
fi

  
echo "SUM is: $SUM"
echo "MAX is: $max"

Upvotes: 0

Views: 72

Answers (2)

Talel BELHAJSALEM
Talel BELHAJSALEM

Reputation: 4294

#!/bin/bash

# Example of a previously calculated SUM that gives MAX number 5
max=5

SUM=$(($A + $B))

# Update max only if new sum is greater than it
[ $SUM -gt $max ] && max=$SUM

echo $max

Example:

$ A=5 B=9 bash program
14

$ A=1 B=1 bash program
5

Upvotes: 0

dan
dan

Reputation: 5221

The bug in your code is: if [ $now -gt $max ] (max, not SUM).

You can write it better like this:

sum=$((TKBPS+RKBPS))

max=$((sum>max?sum:max))
# ((sum>max)) && max=$sum # or like this

echo "sum is $sum"
echo "max is $max"

Upvotes: 2

Related Questions