1, 幾個等效命令 test,/usr/bin/test,[],和/usr/bin/[
vim equi.sh
1 #!/bin/bash
2 echo
3
4 if test -z "$1"
5 then
6 echo "No command-line arguments."
7 else
8 echo "First command-line argument is $1."
9 fi
10
11 echo
12
13 if /usr/bin/test -z "$1" # 與內建的 test 結果相同
14 then
15 echo "No command-line arguments."
16 else
17 echo "First command-line argument is $1."
18 fi
19
20 echo
21
22 if [ -z "$1" ] # 與上邊代碼的作用相同
23 # if [ -z "$1" 應該工作,但是...
24 #+ Bash 相應一個缺少關閉中括號的錯誤消息.
25 then
26 echo "No command-line arguments."
27 else
28 echo "First command-line argument is $1."
29 fi
30
31 echo
效果:
First command-line argument is hhh.
First command-line argument is hhh.
First command-line argument is hhh.
First command-line argument is hhh.
2,算數測試使用(( ))
vim count.sh
1 #!/bin/bash
2 # 算數測試
3
4 # The (( ... )) construct evaluates and tests numerical expressions.
5 # (( ... ))結構計算並測試算數表達式的結果.
6 # 退出碼將與[ ... ]結構相反!
7
8 (( 0 ))
9 echo "Exit status of \"(( 0 ))\" is $?." # 1
10
11 (( 1 ))
12 echo "Exit status of \"(( 1 ))\" is $?." # 0
13
14 (( 5 > 4 )) # true
15 echo "Exit status of \"(( 5 > 4 ))\" is $?." # 0
16
17 (( 5 > 9 )) # false
18 echo "Exit status of \"(( 5 > 9 ))\" is $?." # 1
19
20 (( 5 - 5 )) # 0
21 echo "Exit status of \"(( 5 - 5 ))\" is $?." # 1
22
23 (( 5 / 4 )) # 除法也行
24 echo "Exit status of \"(( 5 / 4 ))\" is $?." # 0
25
26 (( 1 / 2 )) # 出發結果<1
27 echo "Exit status of \"(( 1 / 2 ))\" is $?." # 結果將爲 0
28 # 1
29
30 (( 1 / 0 )) 2>/dev/null # 除數爲 0 的錯誤
31 # ^^^^^^^^^^^
32 echo "Exit status of \"(( 1 / 0 ))\" is $?." # 1
33
34 # What effect does the "2>/dev/null" have?
35 # "2>/dev/null"的作用是什麼?
36 # 如果刪除"2>dev/null"將會發生什麼?
37 # Try removing it, then rerunning the script.
38 # 嘗試刪除它,然後再運行腳本.
39 exit 0
效果:
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.
3 test 死的鏈接文件
vim broken-link.sh
4,數字和字符串比較
vim numStrTest.sh
1 #!/bin/bash
2
3 a=4
4 b=5
5
6 # 這裏的變量 a 和 b 既可以當作整型也可以當作是字符串.
7 # 這裏在算術比較和字符串比較之間有些混淆,
8 #+ 因爲 Bash 變量並不是強類型的.
9
10 # Bash 允許對整型變量操作和比較
11 #+ 當然變量中只包含數字字符.
12 # 但是還是要考慮清楚再做.
13
14 echo
15
16 if [ "$a" -ne "$b" ]
17 then
18 echo "$a is not equal to $b"
19 echo "(arithmetic comparison)"
20 fi
21 echo
22
23 if [ "$a" != "$b" ]
24 then
25 echo "$a is not equal to $b."
26 echo "(string comparison)"
27 # "4" != "5"
28 # ASCII 52 != ASCII 53
29 fi
30 # 在這個特定的例子中,"-ne"和"!="都可以.
31 echo
32 exit 0