I am trying to capture the return code of a system
call. To make it simple, consider a command that you know returns code 1, for example the following bash script 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?
I can't duplicate your issue with 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
)
Use it instead.
* According to the Advanced Bash Scripting Guide , "This operator is now functional, as of Bash 4, final release."
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.