標籤:des style color io 使用 ar 檔案 sp on
比較和判斷是程式流程式控制制的要素,此文總結一下shell的比較和判斷語句,方便尋找使用。
1. 重要的比較操作符
大於: -gt
小於: -lt
大於或等於: -ge
小於或等於: -le
等於: -eq
不等於: -ne
舉例:
if [ $var -eq 0] # 如果$var等於0時
if [ $var -ne 0 -a $var -gt 2 ] #邏輯與 -a
if [ $var -ne 0 -o $var -gt 2 ] #邏輯或 -o
2. 檔案相關的判斷測試
[ -f $file_var ] : 如果$file_var是存在的檔案路徑或檔案名稱,則返回真;
[ -x $var ] : 如果$var具有檔案可執行許可權,則返回真;
[ -d $var ] : 如果$var是目錄,則返回真;
[ -e $var ] : 如果$var是存在的檔案,則返回真;
[ -c $var ] : 如果$var是存在的字元裝置檔案,則返回真;
附上英文:
-a file exists.
-b file exists and is a block special file.
-c file exists and is a character special file.
-d file exists and is a directory.
-e file exists (just the same as -a).
-f file exists and is a regular file.
-g file exists and has its setgid(2) bit set.
-G file exists and has the same group ID as this process.
-k file exists and has its sticky bit set.
-L file exists and is a symbolic link.
-n string length is not zero.
-o Named option is set on.
-O file exists and is owned by the user ID of this process.
-p file exists and is a first in, first out (FIFO) special file or named pipe.
-r file exists and is readable by the current process.
-s file exists and has a size greater than zero.
-S file exists and is a socket.
-t file descriptor number fildes is open and associated with a terminal device.
-u file exists and has its setuid(2) bit set.
-w file exists and is writable by the current process.
-x file exists and is executable by the current process.
-z string length is zero.
舉例:
fpath="etc/passwd"
if [ -e $fpath ]; then
echo "file exists";
else
echo "not exist";
fi
3. 字串比較
[[ $str1 = $str2 ]] : 當str1等於str2時,返回真;
[[ $str1 == $str2 ]] : 這是判斷字串是否相等的另一種寫法;
[[ $str1 != $str2 ]] : 當str1不等於str2時,返回真;
[[ $str1 > $str2 ]] : 當str1大於str2時,返回真;
[[ $str1 < $str2 ]] : 當str1小於str2時,返回真;
[[ -z $str1 ]] : 當str1包含的是Null 字元串,返回真;
[[ -n $str1 ]] : 當str1包含的是非Null 字元串,返回真;
shell的比較和判斷