Shell scripting tutorial [7] - Shell test command
Directory : https://blog.csdn.net/shn111/article/details/131590488
Reference tutorial : https://www.runoob.com/linux/linux-shell.html
Online editor : https://www.runoob.com/try/runcode.php?filename=helloworld&type=bash
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
numerical test
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 |
Example:
num1=100
num2=100
if test $[num1] -eq $[num2]
then
echo '两个数相等!'
else
echo '两个数不相等!'
fi
# 两个数相等!
[]
Perform basic arithmetic operations in code
a=5
b=6
result=$[a+b] # 注意等号两边不能有空格
echo "result 为: $result"
# result 为: 11
string test
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 |
Example (tested in the online editor at the beginning of this article):
cd /bin
if test -e ./bash
then
echo '文件已存在!'
else
echo '文件不存在!'
fi
# 文件已存在!
In addition, the shell also provides and (-a) or (-o) not (!) Three logical operators are used to connect test conditions, and their priorities are: highest, second, !
and -a
lowest -o
. For example:
cd /bin
if test -e ./notFile -o -e ./bash
then
echo '至少有一个文件存在!'
else
echo '两个文件都不存在'
fi
# 至少有一个文件存在!