1. Arithmetic expansion
$(( expression ))
範例:
#!/bin/sh
var1=1
echo Before arithmetic expansion \$var1 = $var1
var1=$(( var1 + 1 ))
echo After arithmetic expansion \$var1 = $var1
結果:
Before arithmetic expansion $var1 = 1
After arithmetic expansion $var1 = 2
說明:
因為 var1 不是宣告成整數型態,因此用 $(( )) 讓 bash 知道是要做算術運算
2. 使用 declare -i 將變數宣告為整數型態
範例:
#!/bin/sh
declare -i var2=1
echo Before arithmetic evaluation \$var2 = $var2
var2=var2+1
echo After arithmetic evaluation \$var2 = $var2
結果:
Before arithmetic evaluation $var2 = 1
After arithmetic evaluation $var2 = 2
因為 var2 是被宣告成整數型態,因此可以直接做算術運算
3. 使用 Conditional Constructs
(( expression ))
範例:
#!/bin/sh
var3=1
echo Before arithmetic expression \$var3 = $var3
(( var3 += 1 ))
echo After arithmetic expression \$var3 = $var3
var4=1
echo Before arithmetic expression \$var4 = $var4
(( var4=var4+1 ))
echo After arithmetic expression \$var4 = $var4
Before arithmetic expression $var3 = 1
After arithmetic expression $var3 = 2
Before arithmetic expression $var4 = 1
After arithmetic expression $var4 = 2
說明:
原本 (( expression )) 的用法應該是將 expression 的運算結果做為條件式判斷的依據,因為 expression 運算的結果如果非0,則 (( expression )) 會回傳 0,不然則回傳 1,但是利用了如 +=, -=, ++, -- 等運算子會修改變數的特性來達到同上面一樣的效果,或是用 = 將運算結果設定給變數。
範例:
#!/bin/sh
(( 1 + 1 ))
echo $?
(( 1 - 1 ))
echo $?
var4=(( 1 + 1 ))
結果:
0
1
./arithmetic.sh: line 30: syntax error near unexpected token `('
./arithmetic.sh: line 30: `var4=(( 1 + 1 ))'
好站連結
1. http://linux.vbird.org/linux_basic/0340bashshell-scripts.php#ex_cal
好站連結
1. http://linux.vbird.org/linux_basic/0340bashshell-scripts.php#ex_cal
沒有留言:
張貼留言