-2

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!

Shieryn
  • 234
  • 2
  • 15

2 Answers2

1

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.
ikegami
  • 367,544
  • 15
  • 269
  • 518
-1

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.

Shieryn
  • 234
  • 2
  • 15
  • Nit: `echo` can exit with a code other than 0. [Example](https://pastebin.com/cdc92cJa) – ikegami May 01 '20 at 20:28
  • Why did you leave the echo out from the question? – jordanm May 01 '20 at 20:28
  • 5
    In other words, please don't say the code you posted does something when it's doesn't, and please only post code that exhibits the behaviour you describe. – ikegami May 01 '20 at 20:30
  • So ... do you actually have an extra `echo $?` in your real code (not shown in Q)? If this is the case I suggest to update the question with a clear added **Note** about it. Or, are you just posting an observation? Either way, this isn't an "answer" and I suggest you remove it. As for the [`$?` variable](https://www.gnu.org/software/bash/manual/bash.html#Special-Parameters), it's always set by the shell for the last executed command, loosely speaking. See for instance [this post](https://stackoverflow.com/questions/6834487/what-is-the-dollar-question-mark-variable-in-shell-scripting). – zdim May 02 '20 at 01:05