Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly capture the return value of a unix command?

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?

like image 986
Joel G Mathew Avatar asked Aug 14 '13 05:08

Joel G Mathew


People also ask

How do you find the return value of a command?

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.

How do you return a value from a Unix shell script?

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.

What is the return value of a shell script after successful execution?

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.

How do I return a value from a bash script?

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 $? .


1 Answers

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 $?} );
like image 191
mob Avatar answered Nov 07 '22 03:11

mob