Shell計算功能

Shell計算功能

  • 使用$((計算式))
#!/bin/bash
echo -n "Enter number : "
read n

sd=0

# store number of digit
nd=0
on=$n # store $n so that we can use it later

# use while loop to caclulate the number of digit
while [ $n -gt 0 ]
do
sd=$(( $n % 10 )) # get Remainder
n=$(( $n / 10 ))
nd=$(( $nd + 1)) # calculate all digit in a number till n is not zero
done
echo  "Numnber of digit in a $on is $nd"

  • 使用"計算式|bc"
(
while [ $ != 'x' ]
do
echo "Welcome to calculator (x to quit)"
echo "Enter the first operand: "
read value1
echo "Enter an operator (+, -, *, /): "
read operator
echo "Enter the second operand: "
read value2
if [ " $ operator " = " + " ] ; then
answer=$(echo "scale=2;value1+value2" |bc);
elif [ " $ operator " = " - " ] ; then
answer=$(echo " scale=2;value1-value2" |bc);
elif [ " $ operator " = " / " ] ; then
answer=$(echo "scale=2;value1/value2" |bc);
elif [ " $ operator " = " * " ] ; then
answer=$(echo "scale=2;value1*value2" |bc);
elif [ " $ operator " = " % " ] ; then
answer=$(echo "scale=2;value1%value2" |bc);
fi
echo "Answer: $value1 $operator $value2 = $answer";
done
)

使用範例:
#!/bin/bash
export memSize=`/usr/bin/free -m | grep Mem | awk '{print $2}'`
export realUsed=`/usr/bin/free -m | grep + | awk '{print $4}'`
echo $realUsed :: $memSize

echo $(($realUsed*100/$memSize))
echo "$realUsed*100/$memSize"| bc
執行結果:
[appmanager@PTW-ES-SCHD-01 bin]$ ./mrtg-memory-real.sh 
4595 :: 5579
82
82

這個網誌中的熱門文章

Bash判斷參數是否存在

使用 minikube 輕鬆上手 kubernetes