Shell conditional test statement

1. Conditional test statement of Shell programming

1.test command

  • Test whether the expression is true (boolean value T/F), if it is true (T), return 0, otherwise return other values, it is not true
格式1:test 条件表达式
格式2[ 条件表达式 ]        #条件表达式左右需要有空格,否则报错

2. File testing

[ 操作符 文件或目录 ]

常用的测试操作符
-d:测试是否为目录
-e:测试目录或文件是否存在
-f:测试是否为文件
-r:测试当前用户是否有权限读取
-w:测试当前用户是否有权限写入
-x:测试当前用户是否有权限执行

Insert picture description here
Insert picture description here

With the use of

Insert picture description here

3. Integer value comparison

[ 整数1 操作符 整数2 ]

Common test operators

-eq:等于
-ne:不等于
-gt:大于
-lt:小于
-le:小于或等于
-ge:大于或等于

Insert picture description here

Insert picture description here

Insert picture description here

4. String comparison

格式1[ 字符串1 = 字符串2 ][ 字符串1 == 字符串2 ]
      [ 字符串1=  字符串2 ]

[ -z 字符串 ]       #检测是否为空,对于未定义或赋予空值的变量将视为空串
[ -n 字符串 ]       #检查是否有字符串存在
 =                 #字符串内容相同
!=                 #字符串内容不相同,!表示取反的意思

Insert picture description here

Insert picture description here

5. Logic test

格式1[ 表达式1 ] 操作符 [ 表达式2 ]...
格式2[ 命令1  操作符 命令2 ]

-a和&&      #都是逻辑与、且的意思必须两边同时满足。
-o和||      #都是逻辑或者的意思只需要有一边满足即可。
区别:
 -a和-o只能在同一个[]中使用,即只能在格式2使用
 &&||只能在两个[]之间使用,即只能在格式1使用
 &&||也可以在[[ ]]中使用,效果一样。
 

How to use && and || in the shell (supplement)

shell中&&||的使用方法
&&运算符:
 
command1  && command2
 
&&左边的命令(命令1)返回真(即返回0,成功被执行)后,&&右边的命令(命令2)才能够被执行;换句话说,“如果这个命令执行成功&&那么执行这个命令”。 

1 命令之间使用 && 连接,实现逻辑与的功能。
2 只有在 && 左边的命令返回真(命令返回值 $? == 0),&& 右边的命令才会被执行。
3 只要有一个命令返回假(命令返回值 $? == 1),后面的命令就不会被执行。
-------------------------------------------------------------------------------------
 
||运算符:
command1 || command2
 
||则与&&相反。如果||左边的命令(命令1)未执行成功,那么就执行||右边的命令(命令2);或者换句话说,“如果这个命令执行失败了||那么就执行这个命令。

1 命令之间使用 || 连接,实现逻辑或的功能。
2 只有在 || 左边的命令返回假(命令返回值 $? == 1),|| 右边的命令才会被执行。这和 c 语言中的逻辑或语法功能相同,即实现短路逻辑或操作。
3 只要有一个命令返回真(命令返回值 $? == 0),后面的命令就不会被执行。

Insert picture description here
Insert picture description here

Insert picture description here

Insert picture description here

Insert picture description here
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_44324367/article/details/111245936