return status value of a shell script when called from ruby?
ruby
Solution
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
Problem
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 ```