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


Posted: 7th October 2007
Tags: ,
Posted in Ruby on Rails
Comments: 5 Comments »

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 clockobj.co.uk]

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

  1. dom = clockobj.co.uk
  2. @whois = %x[whois #\{dom\}]

Comments below..

Advertisement

 




Comments

Note: You can leave a response, or trackback from your own site.

 
Comment:

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.

 
 
Comment:

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}`

 
 
Comment:

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

 
 
Comment:

# 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

 
 
Comment:

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

 
Add a comment: