Bash 條件判斷與流程控制相關語句詳解
阿新 • • 發佈:2022-04-29
介紹 if case 等語句。
條件判斷語句
字串判斷
str1 = str2 當兩個字串有相同內容、長度時為真
str1 != str2 當字串 str1 和 str2 不等時為真
-n str1 當字串的長度大於 0 時為真(串非空)
-z str1 當字串的長度為 0 時為真(空串)
str1 當字串 str1 為非空時為真
數值的判斷
int1 -eq int2 兩數相等為真
int1 -ne int2 兩數不等為真
int1 -gt int2 int1 大於 int2 為真
int1 -ge int2 int1 大於等於 int2 為真
int1 -lt int2 int1 小於 int2 為真
int1 -le int2 int1 小於等於 int2 為真
檔案相關的判斷語句
-r file 使用者可讀為真
-w file 使用者可寫為真
-x file 使用者可執行為真
-f file 檔案為普通檔案為真
-d file 檔案為目錄為真
-c file 檔案為字元特殊檔案為真
-b file 檔案為塊特殊檔案為真
-s file 檔案大小非 0 時為真
-t file 當檔案描述符(預設為 1 )指定的裝置為終端時為真
邏輯判斷
-a 與
-o 或
! 非
if
基本結構
if [ 條件判斷 ]; then
do something here
elif [ 條件判斷 ]; then
do another thing here
else
do something else here
fi
或者
if [ 條件判斷 ]
then
Command
else
Command
fi
舉例如下
# 獲取作業系統型別 SYSTEM=`uname -s` # [] 內兩邊必須有空格 # if 與 then 在同一行,判斷語句後加上 ; if [ $SYSTEM = "Linux" ];then echo "Linux" else echo "OS is not Linuix" fi # 寫在一行 if [ $SYSTEM = "Linux" ];then echo "Linux"; else echo "OS is not Linuix"; fi
也可以寫成
SYSTEM=`uname -s`
if [ $SYSTEM = "Linux" ]
then
echo "Linux"
else
echo "OS is not Linuix"
fi
case
基本結構
case $1 in
模式1 )
命令序列1
;;
模式2 )
命令序列2
;;
* )
預設執行的命令序列
;;
esac
for
for (( i = 0; i < 10; i++ )); do
#statements
done
for in
for arg in "$@"
do
echo $arg
done
while
while [[ condition ]]; do
#statements
done
until
until [[ condition ]]; do
#statements
done