0

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?

8
  • 2
    "&>" should be "2>". You are running the command in background, and gets the 0 exit code Commented Aug 14, 2014 at 7:08
  • 1
    Thanks, but I am trying to redirect both standard output and standard error.. See gnu.org/software/bash/manual/html_node/Redirections.html. According to that page, the syntax should be &> ? Commented Aug 14, 2014 at 7:13
  • 2
    Then use $res = system("t.sh > /dev/null 2>1") Commented Aug 14, 2014 at 7:15
  • Thanks @Miller, this works! (It would be nice to know why &> is not working though, since it is given in the manual) Commented Aug 14, 2014 at 7:19
  • @HåkonHægland &> is a relatively new Bash feature (introduced in v4.x). Check your version with bash --version; &> works properly on my system with v4.1.2. &> is semantically equivalent to >word 2>&1, so you could do system('t.sh > /dev/null 2>&1');. Note the & in 2>&1; if you leave this off, you will create a file named 1 in the current directory. Commented Aug 14, 2014 at 14:30

1 Answer 1

1

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."

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.