Reputation: 3428
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
Upvotes: 5
Views: 6099
Reputation: 34308
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
Upvotes: 16
Reputation: 1000
Please see http://pubs.opengroup.org/onlinepubs/9699919799/functions/exit.html:
The value of status may be 0, EXIT_SUCCESS, EXIT_FAILURE, [CX] or any other value, though only the least significant 8 bits (that is, status & 0377) shall be available to a waiting parent process.
The unix exit status only has 8 bit. 256 overflows so I guess the behavior in that case is simply undefined. For example this happens on Mac OS 10.7.3 with Ruby 1.9.3:
irb(main):008:0> `sh -c 'exit 0'`; $?
=> #<Process::Status: pid 64430 exit 0>
irb(main):009:0> `sh -c 'exit 1'`; $?
=> #<Process::Status: pid 64431 exit 1>
irb(main):010:0> `sh -c 'exit 2'`; $?
=> #<Process::Status: pid 64432 exit 2>
irb(main):011:0> `sh -c 'exit 255'`; $?
=> #<Process::Status: pid 64433 exit 255>
irb(main):012:0> `sh -c 'exit 256'`; $?
=> #<Process::Status: pid 64434 exit 0>
Which is consistent with what my shell indicates
$ sh -c 'exit 256'; echo $?
0
$ sh -c 'exit 257'; echo $?
1
I'd propose you fix the shell-script (if possible) to return only values < 256.
Upvotes: 0