Wednesday, December 14, 2011

Ruby %x, system(), `backtick`, and puppet Facter::Util::Resolution.exec differences

Below are three different ways of running a system command from ruby:
irb(main):014:0> %x(echo "sdfsd")
=> "sdfsd\n"
irb(main):015:0> system('echo "sdfsd"')
=> true
irb(main):016:0> `echo "sdfsd"`
=> "sdfsd\n"
system() gives you a shell, but doesn't save the output. Backticks and %x are equivalent: they give you a shell environment and return the stdout output.

In puppet if you're using Resolution.exec:
Facter::Util::Resolution.exec('echo "sdfsd"')
Things are not so obvious. Depending on the puppet version, you might get a shell environment and puppet is also doing some checking with 'which' that might result in a 'nil' return if your command is not a simple binary.


Anonymous said...

Actually %x() and the backtick are the same. Try %x(echo "sdfsh")

G said...

Thanks for the correction. My mistake was in thinking it needed a quoted string. Updated the post.