How can I pass a variable to a system() call in ruby?
command-line, command-line-interface, ruby, unix
Solution
Oh, happy injection. You're looking for `IO.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"
Problem
Let's say I have a bunch of text in a variable, `some_var`, that could be pretty much anything. ``` some_var = "Hello, I'm a \"fancy\" variable | with a pipe, double- and single-quotes (terminated and unterminated), and more." ``` Let's also say that, in a CLI Ruby application, I want to allow the user to pipe that text into any Unix command. I've allowed them to input something like `some_var | espeak -a 200 -v en-us`, where the command to the right of the pipe is any unix CLI tool installed on their system. Let's also say that I already took care of separating the variable choice and the pipe out of their input, so I know for 100% certainty exactly what command is after the pipe. (In this case, I want to pipe the contents of the variable to `espeak -a 200 -v en-us`.) How would I do this? I don't think I can use the backtick method, or the `%x[]` literal. I've tried doing the following... ``` system("echo '#{some_var}' | espeak -a 200 -v en-us") ``` ...but any special characters screw things up, and I can't remove the special characters. What should I do?