Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return status value of a shell script when called from ruby?

Tags:

ruby

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 
like image 266
Fanatic23 Avatar asked Apr 29 '12 17:04

Fanatic23


People also ask

How do you call a shell script in Ruby?

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.

What is Retval in shell script?

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.


1 Answers

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
like image 79
Casper Avatar answered Sep 22 '22 17:09

Casper