[英]Capture return code of Perl system command with redirection
I am trying to capture the return code of a system
call. 我正在尝试捕获system
调用的返回码。 To make it simple, consider a command that you know returns code 1, for example the following bash script t.sh
: 为简单t.sh
,请考虑一个您知道返回代码1的命令,例如以下bash脚本t.sh
:
#! /bin/bash
exit 1
Then consider: 然后考虑:
use warnings;
use strict;
use feature qw(say);
my $res=system("t.sh");
say ($?>>8);
$res=system("t.sh &>/dev/null");
say ($?>>8);
which prints 哪个打印
1
0
Why does the second system
call (the one with error redirection) give me a zero return code? 为什么第二个system
调用(带有错误重定向的那个)给我零返回码?
I can't duplicate your issue with Bash v4.1.2: 我无法使用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
However, the &>
redirection operator is not portable and should generally be avoided . 但是, &>
重定向操作符不是可移植的, 通常应避免使用 。 I'm not sure, but it seems like it may not have worked properly in earlier releases. 我不确定,但似乎在早期版本中可能无法正常工作。 * *
The following syntax is semantically equivalent and much more portable: 以下语法在语义上是等效的,并且更具可移植性:
>file 2>&1
(note the &
in 2>&1
) (请注意&
在2>&1
)
Use it instead. 改用它。
* According to the Advanced Bash Scripting Guide , "This operator is now functional, as of Bash 4, final release." *根据《 高级Bash脚本指南》的规定 ,“此操作符从Bash 4(最终版本)开始起作用。”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.