在backticked命令的bash PIPESTATUS? [英] bash pipestatus in backticked command?

查看:170
本文介绍了在backticked命令的bash PIPESTATUS?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在bash,如果我执行了几个命令的反引号里面的管道连接到一起,我怎么能找到的第一个命令的退出状态?

in bash, if I execute a couple of commands piped together inside of backticks, how can I find out the exit status of the first command?

即。在这种情况下,我想获得的1。我可以,如果我不使用反引号,但似乎不工作时,我想保存输出通过PIPESTATUS [0]得到:

i.e. in this case, I am trying to get the "1". which I can get via PIPESTATUS[0] if I am not using backticks, but which doesn't seem to work when I want to saving the output:

## PIPESTATUS[0] works to give me the exit status of 'false':
$ false | true;
$ echo $? ${PIPESTATUS[0]} ${PIPESTATUS[1]};
0 1 0

## doesn't work:
$ a=`false | true`;
$ echo $? ${PIPESTATUS[0]} ${PIPESTATUS[1]};
0 0

更一般地,我试图做到:节省一些程序的输出给一个变量的最后一行,但能够告诉我们,如果计划失败:

More generally, I am trying to accomplish: save the last line of the output of some program to a variable, but be able to tell if the program failed:

$ myvar=` ./someprogram | tail -1 `;
$ if [ "what do i put here" ]; then echo "program failed!"; fi

理想我也想明白是怎么回事,得到的答复是没有什么。

Ideally I'd also like to understand what is going on, not just what the answer is.

感谢。

推荐答案

尝试设置 pipefail 选项。它返回失败管道的最后一个命令。一个例子是:

Try to set pipefail option. It returns the last command of the pipeline that failed. One example:

首先,我将其禁用:

set +o pipefail

创建一个 perl的脚本( script.pl )来测试管道:

#!/usr/bin/env perl

use warnings;
use strict;

if ( @ARGV ) { 
    die "Line1\nLine2\nLine3\n";
}
else {
    print "Line1\nLine2\nLine3\n";
}

在命令行中运行:

myvar=`perl script.pl | tail -1`
echo $? "$myvar"

这收益率:

0 Line3

这似乎是正确的,让我们看到 pipefail 已启用:

set -o pipefail

和运行命令:

myvar=`perl script.pl fail 2>&1 | tail -1`
echo $? "$myvar"

这收益率:

255 Line3

这篇关于在backticked命令的bash PIPESTATUS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆