[Linux] Shell test command

overview

The test command in the Shell is used to check whether a certain condition is true, and it can perform three tests of value, character and file

test常用于 if ,作为判断条件,if test等价于 if [ ], therefore, the contents of test and [] can be directly interchanged! Both support

The syntax of [] can be found in the examples in Summarizing the usage of various brackets in the shell () (()), [], [[]], {}), or [] and [[]] of [Linux] shell if the difference

Of course, test can also be executed separately. If the hello.sh file exists in the current directory, the return value will be 0:

[root@linuxforliuhj test]# test -f hello.sh 
[root@linuxforliuhj test]# echo $?          
0

The above command is equivalent to the following syntax:

[root@linuxforliuhj test]# [ -f hello.sh ]
[root@linuxforliuhj test]# echo $?          
0

So [] is a built-in command with a return value, not a symbol

Numeric tests (arithmetic operators)

parameter illustrate
-eq true if equal to
- is true if not equal
-gt true if greater than
-ge True if greater than or equal to
-lt true if less than
- the true if less than or equal to

test常用于 if ,作为判断条件, the example is as follows:

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

if test is equivalent to if [ ], if we transform the above example, the execution result is the same:

num1=100
num2=100
if [ $[num1] -eq $[num2] ]
then
    echo '两个数相等!'   # 打印结果
else
    echo '两个数不相等!'
fi

string test (string operators)

parameter illustrate
= true if equal to
!= 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:

num1="ru1noob"
num2="runoob"
if test $num1 = $num2
then
    echo '两个字符串相等!'
else
    echo '两个字符串不相等!'    # 执行打印
fi

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
cd /bin
if test -e ./bash
then
    echo '文件已存在!'
else
    echo '文件不存在!'
fi

Logical Operators

In addition, Shell also provides three logical operators with ( -a ), or ( -o ), and not ( ! ) to connect test conditions. The priority is: ! is the highest, followed by -a, and -o lowest. For example:

For example, to determine whether at least one of the two files exists:

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

reference

Shell test command

Guess you like

Origin blog.csdn.net/m0_45406092/article/details/129286128