Shell:变量数值计算(下)

Shell:变量数值计算(下)

罗小黑
2021-04-03 / 0 评论 / 258 阅读 / 正在检测是否收录...
广告
温馨提示:
本文最后更新于2021年04月06日,已超过1283天没有更新,若内容或图片失效,请留言反馈。

bc 命令用法

如果没有安装bc,用下面命令进行安装
centos systemctl intall -y bc
Unbunt apt-get install -y bc

root@cs:/server/scripts# echo 3+5|bc
8
root@cs:/server/scripts# echo 3-5|bc
-2
root@cs:/server/scripts# echo 3.6-5.2|bc
-1.6
root@cs:/server/scripts# echo 3.6*5.2|bc
18.7
root@cs:/server/scripts# echo "scale=2;355/113"|bc
3.14
root@cs:/server/scripts# echo "scale=6;355/113"|bc
3.141592

计算1-10的结果

root@cs:/server/scripts# echo `seq -s "+" 10`=`seq -s "+" 10|bc`
1+2+3+4+5+6+7+8+9+10=55
root@cs:/server/scripts# echo `seq -s "+" 10`=$((`seq -s "+" 10`))
1+2+3+4+5+6+7+8+9+10=55
root@cs:/server/scripts# echo `seq -s '+' 10`=$(echo $[`seq -s "+" 10`])
1+2+3+4+5+6+7+8+9+10=55

awk实现计算

root@cs:/server/scripts# echo "5.3 6.9"|awk '{print ($1+$2)}'
12.2
root@cs:/server/scripts# echo "5.3 6.9"|awk '{print ($1-$2)}'
-1.6
root@cs:/server/scripts# echo "5.3 6.9"|awk '{print ($1*$2)}'
36.57
root@cs:/server/scripts# echo "5.3 6.9"|awk '{print ($1/$2)}'
0.768116

$[]实现运算

root@cs:/server/scripts# i=8
root@cs:/server/scripts# i=$[i+6]
root@cs:/server/scripts# echo $i
14
root@cs:/server/scripts# echo $[i-5]
9
root@cs:/server/scripts# echo $[i*5]
70
root@cs:/server/scripts# echo $[i**5]
537824
root@cs:/server/scripts# echo $[i/5]
2
root@cs:/server/scripts# echo $[i%5]
4

基于Shell 变量输入read 命令的运算实践

root@cs:/server/scripts# cat test3.sh
#!/bin.bash
read -p "please input two:" a b
echo "a+b=$(($a+$b))"
echo "a-b=$(($a-$b))"
echo "a*b=$(($a*$b))"
echo "a/b=$(($a/$b))"
echo "a**b=$(($a**$b))"
echo "a%b=$(($a%$b))"
echo "a++:$((a++))"
echo "a=$a"
echo "++a:$((++a))"
echo "a=$a"
echo "b--:$((--b))"
echo "b=$b"
echo "--b:$((--b))"
echo "b=$b"

执行结果

root@cs:/server/scripts# sh test3.sh
please input two:2 2
a+b=4
a-b=0
a*b=4
a/b=1
a**b=4
a%b=0
a++:2
a=3
++a:4
a=4
b--:1
b=1
--b:0
b=0

完善的代码

root@cs:/server/scripts# cat test3.sh
#!/bin.bash

read -t 15 -p "please input two:" a b
[ ${#a} -le 0 ]&&{
 echo "the first num is null"
exit 1
}
[ ${#b} -le 0 ]&&{
echo "the first num is null"
exit 1
}
expr $a + 1 &>/dev/null
REVTAL_A=$?
expr $b + 1 &>/dev/null
REVTAL_B=$?
if [ $REVTAL_A -ne 0 -o $REVTAL_B -ne 0 ];then
    echo "one of the num is not num,pls input again."
    exit 1
fi

echo "a+b=$(($a+$b))"
echo "a-b=$(($a-$b))"
echo "a*b=$(($a*$b))"
echo "a/b=$(($a/$b))"
echo "a**b=$(($a**$b))"
echo "a%b=$(($a%$b))"
echo "a++:$((a++))"
echo "a=$a"
echo "++a:$((++a))"
echo "a=$a"
echo "b--:$((--b))"
echo "b=$b"
echo "--b:$((--b))"
echo "b=$b"

运算结果

root@cs:/server/scripts# sh test3.sh
please input two:12 12
a+b=24
a-b=0
a*b=144
a/b=1
a**b=8916100448256
a%b=0
a++:12
a=13
++a:14
a=14
b--:11
b=11
--b:10
b=10

用传参方式进行运算

0

打赏


评论 (0)

取消