if
- 變量賦值,等號之間不能有空格
- 條件判斷是中括號要留有空格
#語法結構
#如果if條件判斷中有多條命令,則根據最後一條命令的執行結果進行評估
if command;then
command
elif command;then
command
else
command
fi
#!/bin/bash
x=5
if [ $x = 5 ];then
echo "x equals 5"
else
echo "x not equals 5"
fi
退出狀態
每個命令執行完成後,會向操作系統發送一個值,表示退出狀態,可以使用以下方法,查看該值
#0表示執行成功,其他值表示失敗
echo $?
test
語法結構
(一)
test expression
(二)
[ expression ]
文件判斷
-d file 文件存在,並且是一個目錄文件
-e file file文件存在
-f file file問價存在,並是一個普通文件
-r file 問價存在,並且可讀
-w file 文件存在,並且可寫
-x file 文件存在,並且可執行
#!/bin/sh
file="/usr/study/test/test.t"
if [ -e $file ];then
if [ -f $file ] ;then
echo "$file is a regular file"
fi
if [ -d $file ];then
echo "$file if a directory"
fi
if [ -r $file ];then
echo "$file is a readable"
fi
if [ -w $file ];then
echo "$file is a writeable"
fi
if [ -x $file ];then
echo "$file is a executable"
fi
else
echo "$file does not exit"
exit 1
fi
exit
#exit命令接受單獨的可選參數,來作爲腳本的退出狀態
字符串表達式
">"和"<"在使用是必須使用引號引起來,或者使用反斜槓進行轉義
"="和"=="在判斷字符串相等是作用相同
-n string 表示字符串長度大於0
-z string 表示字符串長度等於0
#!/bin/bash
result=xul
if [ -z $result ];then
echo "there is no answer"
exit 1
fi
if [ "$result" = "xul" ];then
echo "result is xul"
fi
if [ "$result" != "test" ];then
echo "result is not test"
fi
if [ "$result" \> "yyy" ];then
echo "result > yyy"
fi
if [ "$result" \< "yyy" ];then
echo "result < yyy"
fi
整數表達式
-eq 連個整數相等
-ne 兩個整數不相等
-le 小於等於
-lt 小於
-ge 大於等於
-gt 大於
#!/bin/bash
i=4
if [ -z "$i" ];then
echo "i is empty"
exit 1
fi
if [ $i -eq 0 ];then
echo "i is 0"
else
if [ $i -le 0 ];then
echo "i <= 0"
fi
if [ $i -ge 0 ];then
echo "i >= 0"
fi
if [ $i -ne 0 ];then
echo "i != 0"
fi
if [ $((i%2)) -eq 0 ];then
echo "i is even"
fi
fi
exit
增強版test
[[ espression ]]
1.增加了對正則表達式的支持
2.==操作符支持模式匹配
(())
算數測試,使用變量是不需要擴展操作,該表達式可以根據變量名直接查找變量
#!/bin/bash
i=5
if [[ "$i" =~ ^-?[0-9]+$ ]];then
if [ $i -eq 0 ];then
echo "$i is 0"
else
if [ $i -lt 0 ];then
echo "$i < 0"
else
echo "$i > o"
fi
if [ $((i%2)) == 0 ];then
echo "$i is even"
else
echo "$i is not even"
fi
fi
else
echo "$i is not a integer"
fi
邏輯表達式
&& || !
#!/bin/bash
i=50
max=100
min=1
if [[ "$i" =~ ^-?[0-9]+$ ]];then
if [[ i -ge min && i -le max ]];then
echo "$i is within $min to $max"
else
echo "$i is out of range"
fi
else
echo "$i is not a integer"
fi
控制運算符
command1&&command2
//只有command1執行成功後才執行command2
command1||command2
//只有command1執行失敗後才執行command2
mkdir test && cd test