I am attempting to start mplayer. My filename contains spaces and these should be escaped. This is the code I am using:
@player_pid = fork do exec "/usr/bin/mplayer #{song.file}" end
where #{song.file}
contains a path like "/home/example/music/01 - a song.mp3"
. How can I escape this variable properly (and possible other weird characters that the title may contain) so the terminal will accept my command?
When using strings in Ruby, we sometimes need to put the quote we used to define the string inside the string itself. When we do, we can escape the quote character with a backslash \ symbol.
\ is a special character within a string used for escaping. "\" does now work because it is escaping the second " . To get a literal \ you need to escape it using \ .
Escape characters. Escape characters are used to remove the special meaning from a single character. A non-quoted backslash, \, is used as an escape character in Bash. It preserves the literal value of the next character that follows, with the exception of newline.
Escaping a string means to reduce ambiguity in quotes (and other characters) used in that string. For instance, when you're defining a string, you typically surround it in either double quotes or single quotes: "Hello World."
Shellwords should work for you :)
exec "/usr/bin/mplayer %s" % Shellwords.escape(song.file)
In ruby 1.9.x, it looks like you have to require
it first
require "shellwords"
But in ruby 2.0.x, I didn't have to explicitly require it.
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