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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With