linux - && :; in bash scripts 的目的是什么

标签 linux bash shell

我遇到了一个在函数中运行以下命令的 bash 脚本

set -e
rm -rf some_dir/* && :;

在这种情况下 && :; 的目的是什么?

编辑:

我知道它是 && true 的同义词,但现在我不明白为什么它会绕过 set -e

尝试一下,我看到运行以下命令

#!/bin/bash -e

# false
echo false alone return 1 and fail with -e

false || true
echo "false || true return $?"

false || :;
echo "false || :; return $?"

false && true
echo "false && true return $?"

false && :;
echo "false && :; return $?"

false && :
echo "false && : return $?"

输出

false alone return 1 and fail with -e
false || true return 0
false || :; return 0
false && true return 1
false && :; return 1
false && : return 1

最佳答案

它抑制 set -e 效果的原因可以在手册页中找到:

-e      Exit immediately if a simple command (see SHELL GRAMMAR above) exits with a non-zero status.
        The shell does not exit if the command that fails is part of the  command  list  immediately
        following  a while or until keyword, part of the test in an if statement, part of a && or ||
        list, or if the command's return value is being inverted via !.  A trap on ERR, if  set,  is
        executed before the shell exits.

为了强调:如果失败的命令是…… && 或 || 的一部分,则 shell 不会退出列表

请注意,这里有一些微妙之处。一个常见的错误是编写类似 foo() { ...; 的代码。 rm 路径; #cleanup 的目的是始终成功。我的意思是,代码的作者甚至没有真正考虑 foo 的退出状态,而是隐含地期望 is 成功并且不关心 rm< 的退出状态,忘记 foo 返回 rm 的退出状态。代码可能会被重写 rm path || : 确保 foo 总是成功返回,或者 rm path && : 返回 rm 的状态,但如果 errexit 已启用。坦率地说,它太微妙了,我相信还有一个不使用 set -e 的原因。此外,可以提出一个论点,即除非您显式退出脚本或从函数返回,否则您永远不应依赖代码的退出状态。

关于linux - && :; in bash scripts 的目的是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50249696/

相关文章:

C: GTK+ 3.0 (3.20) - 从 GNU/Linux (Arch Linux) 到 Windows 的交叉编译

bash - 无法分隔分号分隔线awk

python - 采购 Anaconda 激活脚本与将 Anaconda bin 目录添加到 PATH

用于用户提示的 Linux 函数

bash - 是否值得切换到 zsh 以供临时使用?

Mysql-Linux : Insert a record in a table at a specific date and time

linux - shell 脚本 (AIX) : Extracting OS and browser information from user agent string

linux - Linux中进程的网络使用情况

shell - 如何通过管道输出需要文件参数的命令

python - 对如何在 python shell 中对 16 位二进制数执行按位运算感到困惑