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
##Example demonstration:

num1="php" num2="php" if test num1=num2 then echo '两个字符串相等!' else echo '两个字符串不相等!' fi

Output result:

两个字符串相等!


File test

Parameter illustrate -e filename True if the file exists -r filename True if the file exists and is readable -w filename True if the file exists and is writable -x filename True if the file exists and is executable -s filename True if the file exists and has at least one character -d filename True if the file exists and is a directory -f filename True if the file exists and is a normal file -c filename True if the file exists and is a character special file -b filename True if the file exists and is a block special file
Example demonstration:

cd /bin if test -e ./bash then echo '文件已存在!' else echo '文件不存在!' fi

Output 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 '两个文件都不存在' fi

Output result:

有一个文件存在!