【shell 指令碼】算術測試需要使用(( ))

楊奇龍發表於2011-03-16
#!/bin/bash
  # 算術測試.
  # (( ... ))結構可以用來計算並測試算術表示式的結果.
  # 退出狀態將會與[ ... ]結構完全相反!
  (( 0 ))
  echo "Exit status of \"(( 0 ))\" is $?."         # 1
  (( 1 ))
  echo "Exit status of \"(( 1 ))\" is $?."         # 0
  (( 5 > 4 ))                                      # 真
  echo "Exit status of \"(( 5 > 4 ))\" is $?."     # 0
  (( 5 > 9 ))                                      # 假
  echo "Exit status of \"(( 5 > 9 ))\" is $?."     # 1
  (( 5 - 5 ))                                      # 0
  echo "Exit status of \"(( 5 - 5 ))\" is $?."     # 1
  (( 5 / 4 ))                                      # 除法也可以.
  echo "Exit status of \"(( 5 / 4 ))\" is $?."     # 0
  (( 1 / 2 ))                                      # 除法的計算結果 < 1.
  echo "Exit status of \"(( 1 / 2 ))\" is $?."     # 擷取之後的結果為 0.
                                                   # 1
  (( 1 / 0 )) 2>/dev/null                          # 除數為0, 非法計算.
 #           ^^^^^^^^^^^
  echo "Exit status of \"(( 1 / 0 ))\" is $?."     # 1
  # "2>/dev/null"起了什麼作用?
  # 如果這句被刪除會怎樣?
  # 嘗試刪除這句, 然後在執行這個指令碼.
 exit 0
======================
root@client.example.com ~/yang # ./calucate.sh
Exit status of "(( 0 ))" is 1.
Exit status of "(( 1 ))" is 0.
Exit status of "(( 5 > 4 ))" is 0.
Exit status of "(( 5 > 9 ))" is 1.
Exit status of "(( 5 - 5 ))" is 1.
Exit status of "(( 5 / 4 ))" is 0.
Exit status of "(( 1 / 2 ))" is 1.
Exit status of "(( 1 / 0 ))" is 1.
root@client.example.com ~/yang #

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/22664653/viewspace-689625/,如需轉載,請註明出處,否則將追究法律責任。

相關文章