如何在Bash-shell脚本中的变量中保存更大的数字



我有一个bash-shell应用程序,可以计算rx和tx数据包。这些数据包每秒都有更改,然后将其保存在SUM变量中。我的目标是在新变量中保存更多的数字。我该怎么做?

SUM=$(expr $TKBPS + $RKBPS)
now=$(( $SUM))
if [ $now -gt $SUM ] ; then
max=$(( $now ))
fi

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

代码中的错误是:if [ $now -gt $max ](max,而不是SUM(。

你可以这样写得更好:

sum=$((TKBPS+RKBPS))
max=$((sum>max?sum:max))
# ((sum>max)) && max=$sum # or like this
echo "sum is $sum"
echo "max is $max"
#!/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

示例:

$ A=5 B=9 bash program
14
$ A=1 B=1 bash program
5

最新更新