• tel: 0845 475 2487 (UK)

Tip: Running command line / shell commands in Ruby using %x

Developed by Jon

I thought I would post a very quick tip on how to execute a command line / shell command with Ruby. There are several ways to run command lines / shell commands in Ruby as discussed by Jay Fields however by far the most useful of these is the %x command, as follows:

  1. @whois = %x[whois www.gotripod.com]

And what is important and not mentioned by Jay is the fact that you can pass parameters into %x[] as follows:

  1. dom = www.gotripod.com
  2. @whois = %x[whois #\{dom\}]

Bookmark and Share

5 Comments

Ikai

November 1, 2007

Hey there, Thought I’d let you know there are a few different ways – I didn’t know about %x, but it is very similar to the backtick (`). Example: `dig yahoo.com` `dig #{domain}` Double quote rules apply. Of course, I might start adopting the %x[] format for readability – unless you are using an IDE or VIM (my choice) with syntax highlighting, backticks are hard to spot.

Jon

November 1, 2007

Thanks for the comment, indeed this also works in exactly the same way. Interesting enough the syntax highlighting in RadRails doesn’t like %x[] so if you are using this, you may prefer the back tick approach i.e. @whois = `whois #{dom}`

steve

December 25, 2007

I’m kind of a newbe, but do these operations wait for the command line/shell command to complete, ie as if you were calling the function from a shell or command line and the whois operation was complete, to return to the ruby app and execute the next line of code? Maybe this is obvious, but I haven’t seen said details specified. Thanks either way for the %x[], very helpfull

gaw.in

June 5, 2008

# Steve: you could start a thread and retrieve the result later.

dom = ‘clockobj.co.uk’
t = Thread.new { `whois #{dom}` }
puts “Proceed with your code…”
puts t.value

margaret

July 10, 2008

I prove the three options but i’m get the follow error: Errno::ECONNREFUSED in … What i am doing bad?? i prove exec command too and the server shut down after execute the command.

Tanks

Leave a comment