1. 程式人生 > >CentOS 7 Shell指令碼程式設計第八講 Bash Shell 簡單數值運算

CentOS 7 Shell指令碼程式設計第八講 Bash Shell 簡單數值運算

開發十年,就只剩下這套架構體系了! >>>   

Bash Shell 可以進行一些簡單數值運算。例如簡單整數+-*/和整數指數運算。

#注意對比輸出結果
[root@promote ~]# echo $((1+11111111111111111111111111111111111111111111111111111111))
-3835065282685275704
[root@promote ~]# echo $((1+111111111111111))
111111111111112
[root@promote ~]# echo $((1+1111111111111111))
1111111111111112
[root@promote ~]# echo $((1+11111111111111111))
11111111111111112
[root@promote ~]# echo $((1+111111111111111111))
111111111111111112
[root@promote ~]# echo $((1+1111111111111111111))
1111111111111111112
[root@promote ~]# echo $((1+11111111111111111111))
-7335632962598440504
[root@promote ~]# echo $((1+111111111111111111111))
430646668853801416
[root@promote ~]# echo $((2**3))
8
[root@promote ~]# echo $((1-7777777777777777))
-7777777777777776
[root@promote ~]# echo $(((50*70)/2))
1750
[root@promote ~]# a=8
[root@promote ~]# echo $((a=a+1))
9
[root@promote ~]# echo $((a/3))
3
[root@promote ~]# echo $((a**3))
729
[root@promote ~]# echo $a
9
[root@promote ~]# echo $((8==7))
0
[root@promote ~]# echo $((8>7))
1
[root@promote ~]# echo $((8<7))
0
[root@promote ~]# echo $((8<=7))
0
[root@promote ~]# echo $((8>=7))
1
[root@promote ~]# echo $((1/2))
0
[root@promote ~]# echo $((1/3))
0

複雜運算可以嘗試使用命令列直譯器bc。

#
[root@promote ~]# yum install bc

let 命令基本等同於(())。複雜運算推薦使用awk。

[root@promote ~]# echo "302 125" | awk '{print ($1-2)/$2}'
2.4
[root@promote ~]# echo "302 100" | awk '{print ($1-2)/$2}'
3
[root@promote ~]# echo "302 100" | awk '{print $1+$2}'
402
[root@promote ~]# echo "302 100" | awk '{print $1-$2}'
202
[root@promote ~]# echo "302 100" | awk '{print $1*$2}'
30200
[root@promote ~]# echo "302 100" | awk '{print $1/$2}'
3.02
[root@promote ~]# echo "302 100" | awk '{print $1**$2}'
100159995352569794157337122264449633359340789387852910740121009667012307693563577085101962837571466472836569051169628003691266451752717050890980506496841970147265639778330507058712176709486840856688987753267362751648557469738863812361843311653158912
[root@promote ~]#