linux - bash: && 运算符行为

标签 linux bash

我正在练习 bash 脚本,对 && 运算符有疑问

根据 O'reily bash cookbook 如果 && 运算符之前的命令失败,它之前的命令应该停止执行

看下面代码

-bash-4.2$ pwd
/home/postgres
-bash-4.2$ mkdir testdir
-bash-4.2$ dir=testdir1
-bash-4.2$ cd $dir1 && rm -rf *
-bash-4.2$ echo $?
0
-bash-4.2$ ls

我希望 rm -rf 命令失败,因为命令 cd testdir1 失败,但 rm -rf 执行并清理。行为更像是“;”运营商。

谁能解释一下我错过了什么

最佳答案

问题与退出代码有关。

如果第一个命令成功,&& 运算符将执行第二个命令。

考虑以下几点:

gmc@linux-ihon:/tmp> rm -rf nonexistant
gmc@linux-ihon:/tmp> echo $?     # Note that there is no error message and the exit status is 0 (success).
0
gmc@linux-ihon:/tmp> rm -r nonexistant
rm: cannot remove 'nonexistant': No such file or directory
gmc@linux-ihon:/tmp> echo $?     # Note that there was an error message and the exit status is 1 (unsuccessful)
1
gmc@linux-ihon:/tmp> 

现在考虑以下几点:

gmc@linux-ihon:/tmp> rm -rf nonexistant && echo "rm success"
rm success
gmc@linux-ihon:/tmp> rm -r nonexistant && echo "rm success"
rm: cannot remove 'nonexistant': No such file or directory
gmc@linux-ihon:/tmp> 

在这种情况下,因为不存在的目录的rm -rf被认为是成功的,所以执行下一个命令。 而同一目录的rm -r 则认为失败,所以不执行下一条命令。

我不确定为什么 rm -f 在目录不存在时返回成功,一种观点认为如果目录不存在,那么你已经达到了 rm 命令的预期结果,因此成功!如果没有 -f 选项,则您明确要求 rm 删除某些内容,如果不存在请告诉我!

顺便说一句。您发布的代码中可能有错误。

您将“坏”目录分配给变量 dir dir=testdir1。但是你cd $dir1,这相当于没有参数的cd(因为变量dir1不存在)。因此,它将 cd 回到您的主目录(返回值:成功)。从那里运行 rm -rf * 可能不是最好的主意。

关于linux - bash: && 运算符行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56127954/

相关文章:

bash - 如何在 shell 脚本中使用向上箭头键获取上一个命令

linux - Sles10 zypper 无法添加存储库

linux - 为什么我的 crontab 不工作?

c - Accept() 超时或错误?

linux - 使用 grep 计算大量日志文件中某个标签的所有出现次数

linux - xargs 错误 : File name too long

linux - 如何在 OSX 或 LINUX 上执行没有完整目录的 execv()?

linux - Bash 获取等待进程的退出代码

linux - rpmbuild 设置错误的文件所有权说 root :root (wrong owner/group build:users)

c++ - 时间术语