Bash shell 環境可以執行基本的算術運算利用一些指令如 let、(()),以及[]。expr 和 bc 這兩個工具在執行進階操作時也很有用。
let 指令可以被用于直接執行基本操作,在使用 let 時,用變量名就行了,不用帶 $ 字首。例如:
#!/bin/bash
no1=4;
no2=5;
let result=no1+no2
echo $result
遞增操作:let no1++
遞減操作:let no1--
簡寫:let no+=6
let no-=6
[] 操作符也可像 let 指令那樣:result=$[ no1 + no2],在[]裡面使用 $ 字首是合法的,例如:
result=$[ $no1 + 5]
當用的是(())操作符,就用 $變量名 這種格式。如:result=$(( no1 + 50))
expr 也可用于基本操作:
result=`expr 3 + 4`
result=$(expr $no1 + 5)
前面這些方法都不支援浮點數,隻能在整數上操作。
bc,精确電腦,是一個進階同居用于算術操作。它有很多選項。我們可以執行浮點操作,并使用進階函數,例如:
echo "4 * 0.56" | bc
2.24
no=54;
result=`echo "$no * 1.5" | bc`
echo $result
81.0
Additional parameters can be passed to bc with prefixes to the operation with
semicolon as delimiters through stdin.
Decimal places scale with bc: In the following example the scale=2
parameter sets the number of decimal places to 2. Hence, the output
of bc will contain a number with two decimal places:
echo "scale=2;3/8" | bc
0.37
Base conversion with bc: We can convert from one base number system to
another one. Let us convert from decimal to binary, and binary to octal:
#!/bin/bash
Desc: Number conversion
no=100
echo "obase=2;$no" | bc
1100100
no=1100100
echo "obase=10;ibase=2;$no" | bc
100
Calculating squares and square roots can be done as follows:
echo "sqrt(100)" | bc #Square root
echo "10^10" | bc #Square