How to get the perl exit value from bash script

427 views Asked by At

I'm trying to run perl script through bash, and get the perl's exit value.

perl_script.pl

print "test1";
sub a{
  my @array = ("a","b");
  if ($#array ne -1){
   return 1;
  }
  else {return 0;}
}
my $result=a(arg1,arg2);
exit $result;

bash.sh

VARIABLE_1=$("perl_script.pl" arg1 arg2)
RESULT=$? 

The '$?' variable keeps returning 0, no matter the exit value is. Do you know another way to retrieve the perl exit value from bash?

Thanks in advance!

2

There are 2 answers

0
ikegami On

bash's $? will be set to the value passed to exit[1].

$ perl -e'exit 3'

$ echo $?
3

$ perl -e'exit 4'

$ echo $?
4

$ perl perl_script.pl
test1
$ echo $?
1

  1. If the program dies from an exception, the exit code will be set to a non-zero value. If the program neither dies nor calls exit, the exit code will by set to zero.
4
Shieryn On

I noticed the root cause of this problem. It is a simple issue but tricky. So I would like to share it here.

bash.sh

VARIABLE_1=$("perl_script.pl" arg1 arg2)
echo $?
RESULT=$? 

The echo process has accessed the $?, so the RESULT variables would save the exit value of the echo operation which always turns 0 (successful operation)

The fix

VARIABLE_1=$("perl_script.pl" arg1 arg2)
RESULT=$? 
echo $RESULT

As the conclusion, the $? has one-time use only right after the script executed.