Home > front end >  How do I save greater number in variable in Bash shell script?
How do I save greater number in variable in Bash shell script?

Time:03-14

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"

CodePudding user response:

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"

CodePudding user response:

#!/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
  • Related