Ruby Quicktips Logo

Ruby Quicktips

Random Ruby and Rails tips.
This blog is dedicated to deliver short, interesting and practical tidbits of the Ruby language and Ruby on Rails framework. Read more...

Your submissions are more than welcome!
May 26 ’11

Execute shell commands

There are a number of different ways to run shell commands from Ruby.

The exec command

Kernel#exec replaces the current process and runs the command:

exec('ls ~')
# Nothing after this command is executed

This might be a bit impractical, so have a look at the other options.

Backticks or %x shortcut

Place your command inside backticks (`) or execute it within %x() and it will return the output of this command:

`ls ~`
=> "Applications\nDesktop\nDocuments"
%x(ls ~)
=> "Applications\nDesktop\nDocuments"

The system command

Use Kernel#system and it will return true (command run successfully), false (unsuccessful) or nil (command execution failed):

system('ls ~')
=> true

For all of these methods, you can access the PID and exit status of the unix process via the $? variable:

$?.pid
=> 11988

$?.exitstatus
=> 0

There are more options and I recommend these resources for more details:

22 notes 0 comments

  1. atm09td reblogged this from toby-net and added:
    There are a number of different ways to run shell commands from Ruby. The exec command Kernel#exec replaces the current...
  2. toby-net reblogged this from rubyquicktips
  3. sanemat reblogged this from rubyquicktips
  4. rubyquicktips posted this

Comments

You can use HTML tags for formatting. Wrap code in <code> tags and multiple lines of code in <pre><code> tags.

blog comments powered by Disqus