Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Shell 程式設計

Ubuntu Shell 條件測試完整整理:test、[] 與流程控制

基本語法

test 測試條件 測試內容
[ 測試條件 測試內容 ]      # 使用更為廣泛,[] 兩側務必留空格

test 本身不輸出結果,需要用 echo $? 查看返回值:0 代表條件成立,非 0 代表不成立。

test -e test.txt && echo Yes || echo No

1. 測試檔案類型

test -e 檔名    檔案是否存在
test -f 檔名    是否為普通檔案
test -d 檔名    是否為目錄
test -b 檔名    是否為區塊裝置
test -c 檔名    是否為字元裝置

2. 測試檔案權限

test -r 檔名    是否可讀
test -w 檔名    是否可寫
test -x 檔名    是否可執行
test -s 檔名    是否為非空白(有內容)

3. 兩個檔案比較

[ file1 -nt file2 ]   file1 是否比 file2 新
[ file1 -ot file2 ]   file1 是否比 file2 舊
[ file1 -ef file2 ]   兩者是否為同一檔案(硬連結/軟連結指向同 inode)

4. 數值比較

[ n1 -eq n2 ]   相等
[ n1 -ne n2 ]   不等
[ n1 -gt n2 ]   大於
[ n1 -lt n2 ]   小於
[ n1 -ge n2 ]   大於等於
[ n1 -le n2 ]   小於等於

實務上更直覺的寫法是 (( )) 搭配 ==:

aa=123; bb=123
[ $aa -eq $bb ] && echo Yes || echo no

5. 判斷字串

[ -z 字串 ]              是否為空
[ 字串1 == 字串2 ]        是否相等
[ 字串1 != 字串2 ]        是否不等
aa=abc
[ "$aa" == "abc" ] && echo Yes || echo No

變數一律加引號是好習慣,可避免變數為空時語法出錯。

6. 多重條件

-a   邏輯 AND     [ -z $file -a -e $file ]
-o   邏輯 OR
!    邏輯 NOT

7. 綜合範例:判斷檔案類型與權限

#!/bin/bash
echo -e "你的檔案是否存在?檔案權限是什麼?\n\n"
read -p "please input filename:" -t 30 filename

test -z $filename && echo "please input filename!!" && exit 1
test ! -e $filename && echo "檔案不存在!" && exit 2

test -f $filename && filetype=普通檔案
test -d $filename && filetype=目錄

test -r $filename && perm="read"
test -w $filename && perm="$perm write"
test -x $filename && perm="$perm executable"

echo -e "the filename is : $filename \n"
echo -e "filetype is : $filetype \n"
echo -e "permision is : $perm \n"

這支腳本先用 -z 攔下空輸入,再用 -e 確認檔案存在,最後分別用 -f/-d 判定類型、用 -r/-w/-x 拼出權限清單,是很值得反覆練習的範式。

多指令順序執行

;     cmd1 ; cmd2 ; cmd3        依序執行,彼此無關(如 cd ; ls ; date)
&&    cmd1 && cmd2            cmd1 成功才執行 cmd2
||    cmd1 || cmd2            cmd1 失敗才執行 cmd2

類似 test 的應用:

ls && echo "Yes" || echo "No"
ls skdjfkdj && echo "Yes" || echo "No"
ls aa && echo "存在" || echo "不存在!"

管線符

命令1 | 命令2     # 命令1 的輸出作為命令2 的輸入

前提是命令1 必須有輸出,否則管線沒有意義。

Copyright © Linux教程網 All Rights Reserved