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

时间:2022-02-01 22:27:51

I am attempting to start mplayer. My filename contains spaces and these should be escaped. This is the code I am using:

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

@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?

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

2 个解决方案

#1


30  

Shellwords should work for you :)

Shellwords应该适合你:)

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

In ruby 1.9.x, it looks like you have to require it first

在ruby 1.9.x中,看起来你必须先要求它

require "shellwords"

But in ruby 2.0.x, I didn't have to explicitly require it.

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

#2


15  

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:

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

exec(cmdname, arg1, ...)

exec(cmdname,arg1,...)

command name and one or more arguments (no shell)

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

So instead of mucking around with quoting and escaping and what not, just use the shell-less version:

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

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

and bypass the shell completely. Similarly for system.

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

#1


30  

Shellwords should work for you :)

Shellwords应该适合你:)

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

In ruby 1.9.x, it looks like you have to require it first

在ruby 1.9.x中,看起来你必须先要求它

require "shellwords"

But in ruby 2.0.x, I didn't have to explicitly require it.

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

#2


15  

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:

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

exec(cmdname, arg1, ...)

exec(cmdname,arg1,...)

command name and one or more arguments (no shell)

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

So instead of mucking around with quoting and escaping and what not, just use the shell-less version:

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

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

and bypass the shell completely. Similarly for system.

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