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?
Shellwords should work for you :)
In ruby 1.9.x, it looks like you have to
require
it firstBut in ruby 2.0.x, I didn't have to explicitly require it.
Please never use the "single command line" form of
exec
, that leaves you open to all the usual quoting and injection issues and pointlessly launches a shell. From the fine manual:So instead of mucking around with quoting and escaping and what not, just use the shell-less version:
and bypass the shell completely. Similarly for
system
.