I expected these values to match. They did not match when the shell script exited due to some error condition (and thus returned a non-zero value). Shell $? returned 1, ruby $? returned 256.
>> %x[ ls kkr]
ls: kkr: No such file or directory
=> ""
>> puts $?
256
=> nil
>> exit
Hadoop:~ Madcap$ ls kkr
ls: kkr: No such file or directory
Hadoop:~ Madcap$ echo $?
1
First, note that when Ruby calls out to a shell, it typically calls /bin/sh , not Bash. Some Bash syntax is not supported by /bin/sh on all systems. This is like many other languages, including Bash, PHP, and Perl. Returns the result (i.e. standard output) of the shell command.
The retval command will set the global return value to the numeric value given. retval value. This can be used to pass a value back from a script. The value is initialized to zero whenever a script is executed, so that zero is the default return value.
In Ruby $?
is a Process::Status
instance. Printing $?
is equivalent to calling $?.to_s
, which is equivalent to $?.to_i.to_s
(from the documentation).
to_i
is not the same as exitstatus
.
From the documentation:
Posix systems record information on processes using a 16-bit integer. The lower bits record the process status (stopped, exited, signaled) and the upper bits possibly contain additional information (for example the program's return code in the case of exited processes).
$?.to_i
will display this whole 16-bit integer, but what you want is just the exit code, so for this you need to call exitstatus
:
$?.exitstatus
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