if-then語句
if command
then
commands
commands
fi
if-then-else語句
if command
then
commands
else
commands
fi
嵌套if
if command1
then
commands
elif command2
then
more commands
fi
test命令
if [ condition ]
then
commands
fi
test 命令的數值比較功能
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
字符串比較
test命令的字符串比較功能
str1 = str2 檢查str1是否和str2相同
str1 !=str2 檢查str1是否和str2不同
str1 < str2 檢查str1是否比str2小
str1 > str2 檢查str1是否比str2大
-n str1 檢查str1的長度是否非0
-z str1 檢查str1的長度是否為0
例子:
#!/bin/bash
#string comparisons
val1=aaaaaaa
val2=aaa
if [ $val1 \> $val2 ]
#比較符號前需要加反斜杠,否則會被當做重定向處理
then
echo "$val1 is greater than $val2"
else
echo "$val1 is less than $val2"
fi
if [ -n "$val1" ]
#判斷字符串長度是否非零
if [ -z "$val2" ]
#判斷字符串長度是否為零
*文件比較
test命令的文件比較功能
-d file 檢查file是否存在並是一個目錄
-e file 檢查file是否存在
-f file 檢查file是否存在並是一個文件
-r file 檢查file是否存在並可讀
-s file 檢查file是否存在並非空
-w file 檢查file是否存在並可寫
-x file 檢查file是否存在並可執行
-O file 檢查file是否存在並屬於當前用戶所有
-G file 檢查file是否存在並且默認組與當前用戶相同
file1 -nt file2 檢查file1是否比file2新
file1 -ot file2 檢查file1是否比file2舊
復合條件測試
[ condition1 ] && [ condition2 ]
[ condition1 ] || [ condition2 ]
使用雙圓括號
雙圓括號允許將高級數學表達式放入比較中。
雙圓括號命令符號
val++ 后增
val-- 后減
++val 先增
--val 先減
! 邏輯求反
~ 位求反
** 冪運算
<< 左位移
>> 右位移
& 位布爾和
| 位布爾或
&& 邏輯和
|| 邏輯或
#雙圓括號中的大於小於號不需要轉義
使用雙方括號
[[ expression ]]
雙方括號提供了test命令另一個特性-模式匹配
在模式匹配中,可以定義一個正則表達式來匹配字符串值
case命令
case variable in
pattern1 | pattern2) command1;;
pattern3) command2;;
*) defalt commands;;
esac