如何在Perl中安全地传递带有空格的文件名到外部命令? [英] How can I safely pass a filename with spaces to an external command in Perl?
问题描述
我想能够正确地逃避它们(即不使用我头顶部的随机正则表达式)。是否有一个CPAN模块正确转义字符串以用于bash命令?我知道我过去已经解决了这个问题,但是这次我找不到任何东西。
你在寻找 quotemeta ?
返回EXPR的值所有非word字符都反斜杠。
更新:由于hobbs在评论中指出, quotemeta
不是为了这个目的而且更多地考虑一下,嵌入的 nul
可能会有问题。另一方面, String :: ShellQuote 遇到嵌入的 null
s。
最安全的方法是完全避免shell。使用系统的列表形式可以走很长的路(我发现几个月前我感到沮丧的是, cmd.exe
可能仍然涉及到Windows),我建议这样。
如果您需要命令的输出,那么您最好(安全地)自己打开一个管道,如 hobbs'answer
I have a Perl script that processes a bunch of file names, and uses those file names inside backticks. But the file names contain spaces, apostrophes and other funky characters.
I want to be able to escape them properly (i.e. not using a random regex off the top of my head). Is there a CPAN module that correctly escapes strings for use in bash commands? I know I've solved this problem in the past, but I can't find anything on it this time. There seems to be surprisingly little information on it.
Are you looking for quotemeta?
Returns the value of EXPR with all non-"word" characters backslashed.
Update: As hobbs points out in the comments, quotemeta
is not intended for this purpose and upon thinking a little more about it, might have problems with embedded nul
s. On the other hand String::ShellQuote croaks upon encountering embedded null
s.
The safest way is to avoid the shell entirely. Using the list form of 'system' can go a long way towards that (I found out to my dismay a few months ago that cmd.exe
might still get involved on Windows), I would recommend that.
If you need the output of the command, you are best off (safety-wise) opening a pipe yourself as shown in hobbs' answer
这篇关于如何在Perl中安全地传递带有空格的文件名到外部命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!