Shell test command
The test command in Shell is used to check whether a certain condition is true. It can test values, characters and files.
Numerical Test
Parameter | illustrate |
---|---|
-eq | True if equal |
-ne | True if not equal |
-gt | True if greater than |
-ge | True if greater than or equal to |
-lt | True if less than |
-le | If less than or equal to, it is true |
Example demonstration:
num1=100 num2=100 if test $[num1] -eq $[num2] then echo '两个数相等!' else echo '两个数不相等!' fi
Output result:
两个数相等!
String test
Parameter | illustrate |
---|---|
= | True if equal |
!= | True if not equal |
-z string | True if the length of the string is zero |
-n string | True if the length of the string is not zero |
num1="php" num2="php" if test num1=num2 then echo '两个字符串相等!' else echo '两个字符串不相等!' fiOutput result:
两个字符串相等!
File test
illustrate | |
---|---|
True if the file exists | |
True if the file exists and is readable | |
True if the file exists and is writable | |
True if the file exists and is executable | |
True if the file exists and has at least one character | |
True if the file exists and is a directory | |
True if the file exists and is a normal file | |
True if the file exists and is a character special file | |
True if the file exists and is a block special file |
cd /bin if test -e ./bash then echo '文件已存在!' else echo '文件不存在!' fiOutput result:
文件已存在!In addition, the Shell also Three logical operators are provided: AND (-a), OR (-o), and NOT (!) to connect test conditions. Their priorities are: "!" is the highest, "-a" is the second, and "- o"lowest. For example:
cd /bin if test -e ./notFile -o -e ./bash then echo '有一个文件存在!' else echo '两个文件都不存在' fiOutput result:
有一个文件存在!