How can I pass a variable to a system() call in ruby?
Besides popen
you could also look at Shellwords.escape
:
puts Shellwords.escape("I'm quoting many different \"''' quotes")=> I\'m\ quoting\ many\ different\ \"\'\'\'\ quotes
This will take care of quoting special characters for you (bash compatible):
system("echo '#{Shellwords.escape(some_var)}' | ....")
http://www.ruby-doc.org/stdlib-1.9.3/libdoc/shellwords/rdoc/Shellwords.html
Oh, happy injection. You're looking forIO.popen
.
IO.popen('grep ba', 'r+') {|f| # don't forget 'r+' f.puts("foo\nbar\nbaz\n") # you can also use #write f.close_write f.read # get the data from the pipe}# => "bar\nbaz\n"
popen
and Shellwords.escape
are good solutions but system already have a built in escaping with the array syntax
system('argument', 'argument2', 'argument3')
for example
2.1.2 :002 > abc = "freeky\nbreak"# "freeky\nbreak" 2.1.2 :003 > system("echo #{abc}") #this is badfreeky# => true 2.1.2 :004 > system("echo",abc) # this is proper wayfreekybreak# => true