Latest web development tutorials

Shell test command

Shell The test command is used to check whether a condition is satisfied, it can be tested numeric, character, and file three aspects.


Numerical test

parameter Explanation
-eq Equal to True
-ne It is not equal to True
-gt Greater than True
-ge Greater than or equal True
-lt Less than True
-le True or less

Examples Demo:

num1=100
num2=100
if test $[num1] -eq $[num2]
then
    echo '两个数相等!'
else
    echo '两个数不相等!'
fi

Output:

两个数相等!

String Test

parameter Explanation
= Equal to True
! = Not equal True
-z string True zero-length string
-n string Length of the string is not zero True

Examples Demo:

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

Output:

两个字符串相等!

File test

parameter Explanation
-e filename True if file exists
-r filename If the file exists and is readable True
-w filename If the file exists and is writable True
-x filename If the file exists and is executable True
-s filename If the file exists and that at least one character True
-d filename If the file exists and is a directory True
-f filename If the file exists and is a regular file True
-c filename If the file exists and is a character special file True
-b filename If the file exists and is a block special file True

Examples Demo:

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

Output:

文件已存在!

In addition, Shell also provides a (-a), or (-o), three non-logical operators for connecting the test conditions, the priority (!): "!" Highest, "- a" time the, "- o" minimum. E.g:

cd /bin
if test -e ./notFile -o -e ./bash
then
    echo '有一个文件存在!'
else
    echo '两个文件都不存在'
fi

Output:

有一个文件存在!