今天寫了個小shell腳本,順便整理一下shell中的運算符
1 算數運算符(加減乘數取餘賦值)
原生bash不支持簡單的數學運算,但是可以通過其他命令來實現,expr 最常用
a=10
b=20
var=`expr $a + $b`
var1=`expr $a \* $b`
a=$b 將把變量 b 的值賦給 a
兩點注意:
表達式和運算符之間要有空格,例如 2+2 是不對的,必須寫成 2 + 2,這與我們熟悉的大多數編程語言不一樣。
完整的表達式要被 ` ` 包含,注意這個字符不是常用的單引號,在 Esc 鍵下邊。
2 關係運算符(大於小於等於)
b=20
then
fi
3點注意:
乘號(*)前邊必須加反斜槓(\)才能實現乘法運算;
if...then...fi 是條件語句
條件表達式要放在方括號之間,並且要有空格,例如 [$a==$b] 是錯誤的,必須寫成 [ $a == $b ]。
3 布爾運算符(與或非)
a=10b=20
[ ! false ] 返回 true
[ $a -lt 20 -o $b -gt 100 ] 返回 true
[ $a -lt 20 -a $b -gt 100 ] 返回 false
4 字符串運算符(檢測字符串是否相等爲空等)
a="abc"b="efg"
= 檢測兩個字符串是否相等,相等返回 true。 [ $a = $b ] 返回 false。
!= 檢測兩個字符串是否相等,不相等返回 true。 [ $a != $b ] 返回 true。
-z 檢測字符串長度是否爲0,爲0返回 true。 [ -z $a ] 返回 false。
-n 檢測字符串長度是否爲0,不爲0返回 true。 [ -z $a ] 返回 true。
str 檢測字符串是否爲空,不爲空返回 true。 [ $a ] 返回 true。
5 文件測試運算符(檢測unix文件屬性以及是否存在是否爲空等)
#文件“/var/www/tutorialspoint/unix/test.sh”,它的大小爲100字節,具有 rwx 權限file="/var/www/tutorialspoint/unix/test.sh"
-b file 檢測文件是否是塊設備文件,如果是,則返回 true。 [ -b $file ] 返回 false。
-c file 檢測文件是否是字符設備文件,如果是,則返回 true。 [ -b $file ] 返回 false。
-d file 檢測文件是否是目錄,如果是,則返回 true。 [ -d $file ] 返回 false。
-f file 檢測文件是否是普通文件(既不是目錄,也不是設備文件),如果是,則返回 true。 [ -f $file ] 返回 true。
-g file 檢測文件是否設置了 SGID 位,如果是,則返回 true。 [ -g $file ] 返回 false。
-k file 檢測文件是否設置了粘着位(Sticky Bit),如果是,則返回 true。 [ -k $file ] 返回 false。
-p file 檢測文件是否是具名管道,如果是,則返回 true。 [ -p $file ] 返回 false。
-u file 檢測文件是否設置了 SUID 位,如果是,則返回 true。 [ -u $file ] 返回 false。
-r file 檢測文件是否可讀,如果是,則返回 true。 [ -r $file ] 返回 true。
-w file 檢測文件是否可寫,如果是,則返回 true。 [ -w $file ] 返回 true。
-x file 檢測文件是否可執行,如果是,則返回 true。 [ -x $file ] 返回 true。
-s file 檢測文件是否爲空(文件大小是否大於0),不爲空返回 true。 [ -s $file ] 返回 true。
-e file 檢測文件(包括目錄)是否存在,如果是,則返回 true。 [ -e $file ] 返回 true。
更清晰一些的說明:
-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