# Shell exit code

**URL:** <https://www.ruby-forum.com/t/shell-exit-code/165325>\
**Category:** Ruby\
**Created:** [April 12, 2009, 10:48am UTC](https://www.ruby-forum.com/t/shell-exit-code/165325 "2009-04-12T10:48:56Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![yuguri](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/y/a88e57/32.png) [@yuguri](https://www.ruby-forum.com/u/yuguri)\
**Post date:** [April 12, 2009, 10:48am UTC](https://www.ruby-forum.com/t/shell-exit-code/165325/1 "2009-04-12T10:48:56Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![yuguri](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/y/a88e57/32.png) [@yuguri](https://www.ruby-forum.com/u/yuguri)\
**Post date:** [April 12, 2009, 1:09pm UTC](https://www.ruby-forum.com/t/shell-exit-code/165325/2 "2009-04-12T13:09:09Z")

</div>

> 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

---

<div class="post-metadata">

**Author:** ![yuguri](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/y/a88e57/32.png) [@yuguri](https://www.ruby-forum.com/u/yuguri)\
**Post date:** [April 12, 2009, 1:32pm UTC](https://www.ruby-forum.com/t/shell-exit-code/165325/3 "2009-04-12T13:32:55Z")

</div>

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
