Getting Started with Shell Scripting-9

Shell test command

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

Numerical test

parameter illustrate
-eq equal to true
-born not equal to true
-gt greater than true
-give true if greater than or equal to
-lt true if less than
-the true if less than or equal to

Case:

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

输出结果:两个数相等!

 The [] in the code performs basic arithmetic operations , such as:

#!/bin/bash
a=5
b=6
result=$[a+b] # 注意等号两边不能有空格
echo "result 为: $result"

结果为:result 为: 11

String test

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

Case:

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

Case:

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

输出结果:文件已存在!

In addition, Shell also provides and (-a) , or (-o) , not (!) three logical operators used to connect test conditions , the priority is: "!" highest, "-a" times In other words, "-o" is the lowest . E.g:

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

输出结果:至少有一个文件存在!

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325473702&siteId=291194637