5

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 
2
  • What version of Ruby? In 1.9.2-p180, $?.exitstatus returns the same value as $? in the shell for me. And in 1.8.7-p334, and 1.9.3-p0. What OS? Commented Apr 29, 2012 at 17:50
  • Yeah, I get #<Process::Status: pid 23365 exit 1>. Commented Apr 29, 2012 at 17:53

2 Answers 2

16

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
Sign up to request clarification or add additional context in comments.

1 Comment

What do you mean by call exitstatus how can I do that? I get pid 27305 exit 1 as output I just want that 1 other that parsing what is the best way?
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.