对shell中的与(&&)和或(||)的理解

来源:转载

先说明一下:

如果第一个命令执行成功,与操作符 (&&)才会执行第二个命令

如果第一个命令执行失败,或操作符 (||)才会执行第二个命令

可以分析一下下面的命令的输出:

#!/bin/sh

echo "1" && echo "2" || echo "3" && echo "4" || echo "5" || echo "6" && echo "7" && echo "8" || echo "9"

下面是输出:

[email protected]:~/test/shell$ ./sh5.sh

1

2

4

7

8

分析:

echo "1"  执行成功,所以执行echo "2"

echo "2" 执行成功,不执行 echo "3"

既然没有执行echo "3",可以看做不存在 “ " || echo "3" ”,echo "2"后紧接“ && echo "4" ”

echo "4" 执行成功,不执行echo "5"

既然没有执行echo "5",可以看做不存在 “ " || echo "5" ”,echo "4"后紧接“ || echo "6" ”

echo "4" 执行成功,不执行echo "6"

既然没有执行echo "6",可以看做不存在 “ " || echo "6" ”,echo "4"后紧接“ && echo "7" ”

echo "7" 执行成功,执行echo "8"

echo "8" 执行成功,不执行echo "9"

所以最终变成了:

echo "1" && echo "2" && echo "4" && echo "7" && echo "8"

 改变一下,比如当前目录没存在目录p,不存在文件7

#!/bin/sh

cd p && echo "2" || echo "3" && echo "4" || echo "5" || echo "6" && ls "7" && echo "8" || echo "9"

 

下面是输出:

[email protected]:~/test/shell$ ./sh6.sh

./sh6.sh: line 4: cd: p: No such file or directory

3

4

ls: cannot access 7: No such file or directory

9

 

如果想改变执行逻辑,可以加优先操作符()

(Command_x1 &&Command_x2) || (Command_x3 && Command_x4)

在上面的伪代码中,如果Command_x1执行失败,Command_x2不会执行,但是Command_x3会继续执行, Command_x4会依赖于 Command_x3的退出状态。 

(Command_x1 &&Command_x2)

它的执行成功与否: 如果Command_x1执行成功,执行Command_x2 ,如果Command_x2执行成功,那么整个()执行成功,如果Command_x2执行失败,整个()执行失败。如果Command_x2不执行,整个()的执行成功与否取决于Command_x1。

  

可以分析一下下面的例子:

例一

#!/bin/sh

cd p && (echo "1" || echo "2") || (echo "3" && echo "5") && (ls 7 || echo "8" || (echo "9" && echo "0"))

下面是输出:

./sh8.sh: line 3: cd: p: No such file or directory

3

5

ls: cannot access 7: No such file or directory

8

 

例二

#!/bin/sh

cd p && (echo "1" || echo "2") || (echo "3" && cd p) && (ls 7 || echo "8" || (echo "9" && echo "0"))

下面是输出:

./sh7.sh: line 3: cd: p: No such file or directory

3

./sh7.sh: line 3: cd: p: No such file or directory

 

例三:

#!/bin/bash

if ls ./iii

then

echo "1"

elif echo "2" && ls ./i

then

echo "3"

else

echo "4"

fi

下面是输出:

[email protected]:~/test/shell$ ./sh8.sh

ls: cannot access ./iii: No such file or directory

2

ls: cannot access ./i: No such file or directory

4

 


分享给朋友:
您可能感兴趣的文章:
随机阅读: