Forum: Ruby shell exit code

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Yuguri A. (Guest)
on 2009-04-12 12:48
Hello Group,

Is there any way to retrieve an exit code of shell commands when called
from ruby?

ruby code :

exec("ls") if fork.nil?
Process.wait

shell :

# ls
# echo $? <-- get this value in ruby
Alex Eiras (Guest)
on 2009-04-12 15:09
(Received via mailing list)
>
> shell :
>
> # ls
> # echo $? <-- get this value in ruby
> --
>

As of Ruby 1.9, you indeed have the $? global variable, which references
the
exit status of the last child process to terminate. In your example,
exec
will replace the subprocess by running the given command, thus $? will
contain its exit status.

irb(main):001:0> exec('ls') if fork.nil?; Process.wait; puts $?
tmp
pid 5552 exit 0

irb(main):002:0> exec('cat /etc/sudoers') if fork.nil?; Process.wait;
puts
$?
cat: /etc/sudoers: Permission denied
pid 5556 exit 1

Hope it helps
Cheers

Alex
Yuguri A. (Guest)
on 2009-04-12 15:32
Hello Alex,

Thank you for your advise. This really helped!

Regards,
Yuguri

Alex Eiras wrote:
>>
>> shell :
>>
>> # ls
>> # echo $? <-- get this value in ruby
>> --
>>
>
> As of Ruby 1.9, you indeed have the $? global variable, which references
> the
> exit status of the last child process to terminate. In your example,
> exec
> will replace the subprocess by running the given command, thus $? will
> contain its exit status.
>
> irb(main):001:0> exec('ls') if fork.nil?; Process.wait; puts $?
> tmp
> pid 5552 exit 0
>
> irb(main):002:0> exec('cat /etc/sudoers') if fork.nil?; Process.wait;
> puts
> $?
> cat: /etc/sudoers: Permission denied
> pid 5556 exit 1
>
> Hope it helps
> Cheers
>
> Alex
This topic is locked and can not be replied to.