&&运算符
格式
command1 && command2
&&左边的命令(命令1)返回真(即返回0,成功被执行)后,&&右边的命令(命令2)才能够被执行;换句话说,“如果这个命令执行成功&&那么执行这个命令”。
命令之间使用 && 连接,实现逻辑与的功能。
只有在 && 左边的命令返回真(命令返回值 $? == 0),&& 右边的命令才会被执行。
只要有一个命令返回假(命令返回值 $? == 1),后面的命令就不会被执行。
例子:
[root@ol01 htlin]# [[ -e "/tmp/htlin/htlin.txt" ]] && echo "file exits" file exits
如果存在文件/tmp/htlin/htlin.txt,则输出“file exits”
[root@ol01 htlin]# [[ ! -e "/tmp/htlin/htlin.txt" ]] && echo "file not exits" file not exits
反之不存在文件/tmp/htlin/htlin.txt,则输出“file not exits”
||运算符
格式
command1 || command2
||则与&&相反。如果||左边的命令(command1)未执行成功,那么就执行||右边的命令(command2);或者换句话说,“如果这个命令执行失败了||那么就执行这个命令。
命令之间使用 || 连接,实现逻辑或的功能。
只有在 || 左边的命令返回假(命令返回值 $? == 1),|| 右边的命令才会被执行。这和 c 语言中的逻辑或语法功能相同,即实现短路逻辑或操作。
只要有一个命令返回真(命令返回值 $? == 0),后面的命令就不会被执行。
例子:
[root@ol01 htlin]# [[ -e "/tmp/htlin/htlin.txt" ]] || echo "file not exits" file not exits
延伸
1:怎么将&&和||一起使用呢?
[root@ol01 htlin]# [[ -e "/tmp/htlin/htlin.txt" ]] || echo "file not exits" && echo "do something" file not exits do something