Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Shell test command


May 22, 2021 Linux


Table of contents


Shell test command

The test command in the shell is used to check that a condition is true and that it can be tested in three areas: numeric, character, and file.


Numerical testing

Parameters Description
-eq Equal to true
-ne Not equal to true
-gt Greater than is true
-ge If it is greater than or equal to true
-lt Less than is true
-le Less than or equal to true

Example demonstration:

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

Output:

两个数相等!

String testing

Parameters Description
= Equal to true
!= It's true if you're not equal
-z string A string length of zero is true
-n string If the string length is not zero, it is true

Example demonstration:

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

Output:

两个字符串相等!

File test

Parameters Description
-e File name True if the file exists
-r file name True if the file exists and is readable
-w file name True if the file exists and can be written
-x file name True if the file exists and can be executed
-s file name True if the file exists and has at least one character
-d File name True if the file exists and is a directory
-f File name True if the file exists and is normal
-c File name True if the file exists and is character-specific
-b File name True if the file exists and is a special block file

Example demonstration:

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

Output:

文件已存在!

In addition, shell also provides with ( -a), or (-o), non- ( ! T hree logical operators are used to connect test conditions with the priority:!" H ighest, "-a" second, "-o" lowest. For example:

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

Output:

有一个文件存在!