使用重定向捕获Perl系统命令的返回码

时间:2014-08-14 07:01:59

标签: perl

我正在尝试捕获system调用的返回码。为简单起见,请考虑一个您知道返回代码1的命令,例如以下bash脚本t.sh

#! /bin/bash
exit 1

然后考虑:

use warnings;
use strict;
use feature qw(say);

my $res=system("t.sh");
say ($?>>8);

$res=system("t.sh &>/dev/null");
say ($?>>8);

打印

1
0

为什么第二个system调用(带有错误重定向的调用)给我一个零返回码?

1 个答案:

答案 0 :(得分:1)

我无法使用Bash v4.1.2复制您的问题:

$ perl -wE 'system( q{/bin/bash -c "true &> /dev/null"} ); say $? >> 8'
0
$ perl -wE 'system( q{/bin/bash -c "false &> /dev/null"} ); say $? >> 8'
1

但是,&>重定向运算符不可移植且should generally be avoided。我不确定,但似乎它在早期版本中可能无法正常工作。 *

以下语法在语义上等效且更具可移植性:

>file 2>&1

(请注意&中的2>&1

改为使用它。


*根据Advanced Bash Scripting Guide,"此运算符现已正常运行,从Bash 4开始,最终版本。"

相关问题