34

shell中是否有一些类似的选项dash对应于pipefailin bash

或者,如果管道中的命令之一失败(但不会退出它),则获得非零状态的任何其他方式set -e

为了更清楚,这里是我想要实现的一个例子:

在示例调试 makefile 中,我的规则如下所示:

set -o pipefail; gcc -Wall $$f.c -o $$f 2>&1 | tee err; if [ $$? -ne 0 ]; then vim -o $$f.c err; ./$$f; fi;

基本上它运行时会打开错误文件和源文件,并在没有错误时运行程序。节省了我一些打字时间。上面的代码片段运行良好,bash但我较新的 Ubunty 系统使用dash的似乎不支持pipefail选项。

如果以下命令组的第一部分失败,我基本上想要一个 FAILURE 状态:

gcc -Wall $$f.c -o $$f 2>&1 | tee err

这样我就可以将其用于if声明。

有没有其他方法可以实现它?

谢谢!

4

2 回答 2

3

Q. 的示例问题需要:

如果... 命令组的第一部分失败,我基本上想要一个 FAILURE 状态:

安装moreutils并尝试util,它返回管道中第一个命令mispipe的退出状态:

sudo apt install moreutils

然后:

if mispipe "gcc -Wall $$f.c -o $$f 2>&1" "tee err" ; then \
     ./$$f 
else 
     vim -o $$f.c err 
fi

虽然 'mispipe' 在这里完成了这项工作,但它并不是bashshell 的pipefail; 来自man mispipe

   Note that some shells, notably bash, do offer a
   pipefail option, however, that option does not
   behave the same since it makes a failure of any
   command in the pipeline be returned, not just the
   exit status of the first.
于 2019-02-11T02:24:23.420 回答
3

我遇到了同样的问题,并且我正在使用的 docker 映像上的 dash shell (/bin/sh) 中的 bash 选项set -o pipefail和两者都失败了。${PIPESTATUS[0]}我宁愿不修改图像或安装另一个包,但好消息是使用命名管道对我来说非常有效 =)

mkfifo named_pipe
tee err < named_pipe &
gcc -Wall $$f.c -o $$f > named_pipe 2>&1
echo $?

请参阅此答案以了解我在哪里找到信息:https ://stackoverflow.com/a/1221844/431296

于 2020-04-27T23:55:10.910 回答