如何在Ruby中转义终端的字符串?

我正在尝试启动mplayer。 我的文件名包含空格,这些应该被转义。 这是我正在使用的代码:

@player_pid = fork do exec "/usr/bin/mplayer #{song.file}" end 

其中#{song.file}包含类似"/home/example/music/01 - a song.mp3" #{song.file} "/home/example/music/01 - a song.mp3"的路径。 如何正确地转义此变量(以及标题可能包含的其他可能的奇怪字符),以便终端接受我的命令?

Shellwords应该适合你:)

 exec "/usr/bin/mplayer %s" % Shellwords.escape(song.file) 

在ruby 1.9.x中,看起来你必须先require

 require "shellwords" 

但是在ruby 2.0.x中,我没有必要明确要求它。

请永远不要使用exec的“单一命令行”forms,让您对所有常见的引用和注入问题持开放态度并毫无意义地启动shell。 从精细手册 :

exec(cmdname,arg1,…)

命令名和一个或多个参数(没有shell)

因此,不要使用引用和转义以及什么不是,只需使用无shell版本:

 exec '/usr/bin/mplayer', song.file 

并彻底绕过壳。 同样适用于system