1.直接命令:命令執行成功返回 0 不存在返回 125 內部錯誤返回 5,總之只要不是 0 就失敗,then 中的代碼不會執行
1 if command1 2 then 3 do somenthing 4 elif command2 5 then 6 do again 7 fi
2.test 命令,條件不成立 test 命令退出返回非零的退出狀態碼
1 if test condition 2 then 3 do something 4 fi
3. 方括號
3.1 數值比較
option | 描述 |
-eq | 兩個數值是否相等 |
-ge | >= |
-gt | > |
-le | <= |
-lt | < |
-ne | != |
當然也可以直接 [ $var1 > $var2 ] 這種形式,但是 > 會被解釋成重定向輸入 $var2 文件,所以需要轉義 [ $var1 \> $var2 ] 那還不如 [ $var1 -gt $var2 ] 來得好是吧
3.2 字符串比較
option | description |
str1 = str2 | 兩個字符串是否相同 |
str1 != str2 | 兩個字符串是否不同 |
str1 > str2 | 1字符串的ASCII是否大於2的 |
str1 < str2 | ASCII 值比較 |
-n str1 | str1 字符串長度是否為0 |
-z str1 | str1 是否為空 ‘’ |
注意 > < 符號需要轉義
3.3 文件比較
option | 描述 |
-d file | 是否是目錄 |
-e file | exist 是否存在 |
-f file | file 是否是文件 |
-s file | 文件是否為空 |
-r | 是否可讀 |
-w | 是否可寫 |
-x | 是否可執行 |
-0 | |
-G | |
file1 -nt file2 | f1 是否比 f2 新 |
file1 -ot file2 | f1 是否比 f2 舊 |
1 xxx@ubuntu:~/data$ ls -l 2 total 20 3 -rw-rw-r-- 1 xxx root 5 Jun 22 08:24 1.log 4 -rw-r--r-- 1 xxx xxx 0 Jun 7 06:16 2.log 5 drwxrwxr-x 2 xxx xxx 4096 Jun 21 06:46 dirx 6 drwxrwxr-x 3 xxx xxx 4096 Jun 13 19:56 package 7 -rw-rw-r-- 1 xxx xxx 59 Jun 6 20:06 sortx 8 -rwxrwxr-x 1 xxx xxx 167 Jun 21 05:28 test.sh 9 xxx @ubuntu:~/data$ file=$(pwd)/1.log 10 xxx @ubuntu:~/data$ echo $file 11 /home/xxx/data/1.log 12 xxx @ubuntu:~/data$ if [ -e $file ];then 13 > if [ -d $file ];then 14 > echo "it's directory" 15 > elif [ -f $file ];then 16 > echo "it's file" 17 > fi 18 > fi 19 it's file 20 xxx@ubuntu:~/data$ 21 xxx@ubuntu:~/data$ if [ 3 -eq '3' ];then 22 > echo 'eq yes' 23 > else 24 > echo 'no' 25 > fi 26 eq yes 27 xxx@ubuntu:~/data$ if [ 3 -eq 2 ];then echo 'eq yes'; else echo 'no'; fi 28 no 29 xxx@ubuntu:~/data$ if [ 3 -ne 2 ];then echo 'eq yes'; else echo 'no'; fi 30 eq yes 31 xxx@ubuntu:~/data$ if [ 3 -lt 2 ];then echo 'eq yes'; else echo 'no'; fi 32 no 33 xxx@ubuntu:~/data$ if [ 3 -gt 2 ];then echo 'eq yes'; else echo 'no'; fi 34 eq yes 35 xxx@ubuntu:~/data$ if [ 3 -gt 3 ];then echo 'eq yes'; else echo 'no'; fi 36 no 37 xxx@ubuntu:~/data$ if [ 3 -ge 3 ];then echo 'eq yes'; else echo 'no'; fi 38 eq yes 39 xxx@ubuntu:~/data$ if [ 3 -le 3 ];then echo 'eq yes'; else echo 'no'; fi 40 eq yes