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

xor*_*zor 22 ruby escaping command-line-interface

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

@player_pid = fork do
   exec "/usr/bin/mplayer #{song.file}"
end
Run Code Online (Sandbox Code Playgroud)

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

Tha*_*you 39

Shellwords应该适合你:)

exec "/usr/bin/mplayer %s" % Shellwords.escape(song.file)
Run Code Online (Sandbox Code Playgroud)

在红宝石1.9.x中,看起来你必须先做require

require "shellwords"
Run Code Online (Sandbox Code Playgroud)

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


mu *_*ort 15

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

exec(cmdname,arg1,...)

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

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

exec '/usr/bin/mplayer', song.file
Run Code Online (Sandbox Code Playgroud)

并彻底绕过壳.同样的system.