Des*_*ume 23 linux shell command-line pipe
我需要从非 BASH 脚本(即 PHP 脚本)执行许多管道 shell 命令,如下所示:
command1 | command2 | command3
Run Code Online (Sandbox Code Playgroud)
所以,如果 command1以非零退出代码失败,则每个其他命令也会失败。到目前为止,我想出的是:
set -o pipefail && command1 | command2 | command3
Run Code Online (Sandbox Code Playgroud)
但即使它从终端运行良好,如果从脚本执行它也会产生这个:
sh: 1: set: 非法选项 -o pipefail
thk*_*ala 25
从 Bash 命令行,您需要调用子shell 以避免pipefail之后被设置:
$ (set -o pipefail && command1 | command2 | command3)
Run Code Online (Sandbox Code Playgroud)
这将限制pipefail选项对由括号创建的子shell的影响(...)。
一个真实的例子:
$ (set -o pipefail && false | true) && echo pipefail inactive || echo pipefail active
pipefail active
Run Code Online (Sandbox Code Playgroud)
如果您使用带有该-c选项的显式 shell 调用,则不需要带有bash或带有sh别名的子shell bash:
$ bash -c "set -o pipefail && false | true" && echo pipefail inactive || echo pipefail active
pipefail active
$ sh -c "set -o pipefail && false | true" && echo pipefail inactive || echo pipefail active
pipefail active
Run Code Online (Sandbox Code Playgroud)
由于您sh不接受该pipefail选项,我将不得不假设它是某个较旧的或修改过的版本bash- 或者它实际上完全是其他一些 shell。
rob*_*at2 10
不知道为什么上面没有提到它,但可以pipefail使用set +o pipefail.
set -o pipefail
command1 | command2 | command3
set +o pipefail
Run Code Online (Sandbox Code Playgroud)
如果您正在执行一个片段,并且不确定pipefail已经设置的片段,您可以按照之前的建议将其与子 shell 一起使用:
# explicitly execute with pipefail set
(set -o pipefail ; command1 | command2 | command3 )
# explicitly execute with pipefail unset
(set +o pipefail ; command1 | command2 | command3 )
Run Code Online (Sandbox Code Playgroud)