I'm having trouble getting the return value of a unix command into a perl variable.
Unix command:
#nc -z 8.8.8.8 441; echo $?
1
Perl command:
#perl -e 'my $pstate=`nc -z 8.8.8.8 441; echo $?`; print $pstate;'
0
So the perl command seems to get a return value of "no error"? How can I properly capture the return value of the *nix command?
Another instance:
#perl -e 'my $pstate=`ping -v 8.8.8.8 -c 1`; print $pstate;'
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
This returns the proper value. So what am I doing wrong in the first instance?
The return value of a command is stored in the $? variable. The return value is called exit status. This value can be used to determine whether a command completed successfully or unsuccessfully.
return command is used to exit from a shell function. It takes a parameter [N], if N is mentioned then it returns [N] and if N is not mentioned then it returns the status of the last command executed within the function or script. N can only be a numeric value.
Every command returns an exit status (sometimes referred to as a return status or exit code). A successful command returns a 0, while an unsuccessful one returns a non-zero value that usually can be interpreted as an error code.
When a bash function completes, its return value is the status of the last statement executed in the function, 0 for success and non-zero decimal number in the 1 - 255 range for failure. The return status can be specified by using the return keyword, and it is assigned to the variable $? .
Variables are interpolated inside backticks, so the $?
in
my $pstate=`nc -z 8.8.8.8 441; echo $?`
refers to Perl's $?
, not the shell's $?
. And what the shell sees is something like
nc -z 8.8.8.8 441 ; echo 0
To fix this, you can escape the shell command
my $pstate=`nc -z 8.8.8.8 441; echo \$?`;
or use the qx
operator with the single quote as a separator (this is the one exception to the "interpolation inside the qx
operator" rule)
my $pstate=qx'nc -z 8.8.8.8 441; echo $?';
or use readpipe
with a non-interpolated quote construction
my $pstate= readpipe( 'nc -z 8.8.8.8 441; echo $?' );
my $pstate= readpipe( q{nc -z 8.8.8.8 441; echo $?} );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With