bash calculation ( $(...) 與 $((...)) )

最後更新: 2019-06-19

 


Floating Point

 

Convert floating point to integer

[方法1]

FLOAT=34.56
INT=${FLOAT/.*}
echo $INT            # 34

[方法2]

f=34.56
i=${f%.*}
echo $i              # 34

bash handles only integer maths but you can use 'bc' command as of:

echo "11 > 1.1" | bc

1        # 1 是 True

echo "11 > 11" | bc

0

using in script

A=50
B=5.6

if [[ $(echo "$A > $B" | bc ) -eq 1 ]];
then
        echo "A big than B"
fi

 


$(...) 與 $((...))

 

Single Parenthesis

(...)           # 在 subshell 內執行 "()" 內的 CLI. 它不可以配會  =, ".." 使用

r=(ls MyFolder)      # 錯誤
echo "now: (date)"   # 錯誤

$(...)         # 相當於 ``. (command substitution) 它在可以與合 ".." 及 = 使用

---

Double Parenthesis

((…))           # 計數

# Logical AND

(( 0 && 1 )); echo $?       # 1
(( 1 && 1 )); echo $?       # 1

# 只修改值不返回運算結果

((a=2+3)); echo "a=$a"      # a=5

$((...))        # 與 expr 同義

a=$((2+3)); echo "a=$a"     # a=5

(( ... )) 支援

  • ==
  • !=
  • >
  • <
  • >=
  • <=

* It without spawning external processes

有趣的測試:

# 當 Result 係 0 時會返回 FALSE

(( 0 )); echo $?                # Result: 1

(( 1 )); echo $?                # Result: 0

# Division result < 1, Rounded off to 0

a=$(( 1 / 2 )); echo $?; echo $a         #

(( 1 / 2 )); echo $?                            # 1 <= 因為 result 為 0, 所以 $0 會是 1

Example

<1>

test=$((5-3))
echo $test          # 2

<2> i++

myvar=10
((myvar++))         # var=$((var+1))
echo $myvar         # 11

<3>: $(()) 直接獲得運算的 result

result=$((30*3/4));           # result=22

P.S.

$(...) is a command substitution (not just a subshell), but $((...)) is an arithmetic expansion.

Command substitution allows the output of a command to replace the command name.

$(ls MyFolder)       # MyFolder 內有 file 名叫 top

執行後相當於行了 top

方法2: 交給 bc 處理

echo "30*3/4" | bc

方法3: 增量(Increment)

(( ... ))  # Double-Parentheses

carries out arithmetic operations on variables

((var++))
((var=var+1))
((var+=1))
((++var))

var=$((var+1))

 


 

Creative Commons license icon Creative Commons license icon