Shell test 命令
每一種合理完整的編程語言都可以測試一個條件,然后根據測試的結果進行操作。Bash有test命令、各種括號和圓括號操作符以及if/then構造。
與test命令相關的命令和符號:
- If/then條件判斷。
- 內置的[]中括號和[[]雙中括號,[[]]比[]更靈活和強大,可以說是增強版。
- (())和let,一般用於算術表達式和計算比較。
[root@localhost shell]# type test
test is a shell builtin
[root@localhost shell]# type [
[ is a shell builtin
[root@localhost shell]# type [[
[[ is a shell keyword
[root@localhost shell]# type let
let is a shell builtin
If/then可以測試任何命令,而不僅僅是括號內的條件
#!/bin/bash if cmp a.txt b.txt &> /dev/null then echo 'Files a and b are identical.' else echo 'Files a and b are diff.' fi
if/then測試條件格式一:
if [ condition-true ] then command 1 command 2 ... else # Or elif ... # Adds default code block executing if original condition tests false. command 3 command 4 ... Fi
if/then測試條件格式二:
if [ condition1 ] then command1 command2 command3 elif [ condition2 ] # Same as else if then command4 command5 else default-command fi
使用(())進行算術測試
#!/bin/bash var1=7 var2=10 if (( var1 > var2 )) # not $var1 $var2, but is ok. then echo "var1 is greater than var2" else echo "var1 is less than var2" fi exit 0
數值比較
比較 |
描述 |
n1 -eq n2 |
檢查n1是否與n2相等 |
n1 -ge n2 |
檢查n1是否大於或等於n2 |
n1 -gt n2 |
檢查n1是否等於n2 |
n1 -le n2 |
檢查n1是否小於或大於n2 |
n1 -lt n2 |
檢查n1是否小於n2 |
n1 -ne n2 |
檢查n1是否不等於n2 |
#!/bin/bash num1=6 num2=9 if [ $num1 -ne $num2 ] then echo "$num1 is not equal to $num2" fi
字符串比較
參數 |
說明 |
Str1 = str2 |
檢查str1是否和str2相同 |
Str1 != str2 |
檢查str1是否和str2不同 |
-z str1 |
檢查str1是否為零 |
-n str1 |
檢查str1是否非零 |
Str1 > str2 |
檢查str1是否大於syr2 |
Str1 < str2 |
檢查str1是否小於str2 |
文件比較
比較 |
說明 |
-e file |
檢查file是否存在 |
-r file |
檢查file是否存在並可讀 |
-w file |
檢查file是否存在並可寫 |
-x file |
檢查file是否存在並可執行 |
-s file |
檢查file是否存在並非空 |
-d file |
檢查file是否存在並是一個目錄 |
-f file |
檢查file是否存在並是一個文件 |
-c file |
檢查file是否字符型特殊文件 |
-b file |
檢查file是否塊設備文件 |
#!/bin/bash device1="/dev/sda1" if [ -b "$device1" ] then echo "$device1 is a block device." fi device2='/dev/tty0' if [ -c "$device2" ] then echo "$device2 is a character device." fi