Ruby “execute shell command” examples

Ruby exec FAQ: How do I execute a shell command from a Ruby script?

It's very easy to execute an external shell command from a Ruby script. Off the top of my head there are at least two ways to do this. First, you can use the traditional backtick operators. Second, you can use the %x syntax. I'll demonstrate both examples here.

Use the backtick operator

First, I'll use the backtick operator to execute a shell command. Here's how you can run a simple command, like the ls command, using Ruby and the backtick operator:

puts `ls`

or, if you prefer longer output:

puts `ls -al`

(Note that the characters around the ls command there are the backtick characters, typically on the same key on your keyboard as the tilde (~) character.)

Oh, and if you're interested in using variables when you execute your system commands, it's easy to use them, like this:

# define your variable
dir='/tmp'

# execute your shell command
puts `ls #{dir}`

It's that easy.

Use the %x function

You can also use Ruby's %x command, like this:

puts %x{ls -al}

Frankly, I don't know the difference between these two options, and I always use the backtick approach just because I can remember it much more easily. (I just looked this up in a Ruby book, and there is no explanation there either.)

Two things to remember

There are at least two things to remember when running systems commands like this:

  1. The output from the command expression you run will be the standard output of that command.
  2. Newline characters will not be stripped from the output, so you'll probably want to strip those off.

There's also that whole security thing in regards to running system commands like this, but that's a topic for a longer tutorial...

Add new comment

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.