2.5 Ways to Execute a Shell Command

I always get confused by the difference between %x{}, backticks, and system "command", so I wrote down what the difference was. %x{} is actually the exact same thing as backticks, but it’s useful because you can nest backticks inside it.

system "command" echoes to STDOUT, and returns true if the command succeeded.

irb > system "echo ABC"
 => true 

Backticks and %x{ } do not echo to STDOUT, and return the result of running the command.

irb > `echo ABC`
 => "ABC\n" 
irb > %x{echo ABC}
 => "ABC\n"
irb > %x{echo `which ruby`}
 => "/Users/gabe/.rvm/rubies/ruby-1.9.2-p290/bin/ruby\n"

Pair with one of our expert developers to level up your skills with Coaching by thoughtbot. Save time learning best practices and techniques for reducing technical debt in Ember, Ruby, Haskell, and Go in 1-on-1 sessions tailored to your goals.