为什么 shell 忽略通过变量传递给它的参数中的引用字符? [英] Why does shell ignore quoting characters in arguments passed to it through variables?

查看:21
本文介绍了为什么 shell 忽略通过变量传递给它的参数中的引用字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这些如宣传的那样工作:

These work as advertised:

grep -ir 'hello world' .
grep -ir hello world .

这些没有:

argumentString1="-ir 'hello world'"
argumentString2="-ir hello\ world"
grep $argumentString1 .
grep $argumentString2 .

尽管 'hello world' 在第二个示例中被引号括起来,grep 仍将 'hello(和 hello)解释为一个参数和 world'(和 world)作为另一个,这意味着,在这种情况下,'hello 将是搜索模式,而 world' 将是搜索路径.

Despite 'hello world' being enclosed by quotes in the second example, grep interprets 'hello (and hello) as one argument and world' (and world) as another, which means that, in this case, 'hello will be the search pattern and world' will be the search path.

同样,这仅在从 argumentString 变量扩展参数时发生.在第一个示例中,grep 正确地将 'hello world'(和 hello world)解释为单个参数.

Again, this only happens when the arguments are expanded from the argumentString variables. grep properly interprets 'hello world' (and hello world) as a single argument in the first example.

谁能解释一下这是为什么?是否有适当的方法来扩展字符串变量,以保留每个字符的语法,以便 shell 命令正确解释它?

Can anyone explain why this is? Is there a proper way to expand a string variable that will preserve the syntax of each character such that it is correctly interpreted by shell commands?

推荐答案

为什么

当字符串被扩展时,它被拆分为单词,但不会重新评估以找到特殊字符,例如引号或美元符号或......这是外壳始终"表现的方式,因为伯恩壳早在 1978 年左右.

Why

When the string is expanded, it is split into words, but it is not re-evaluated to find special characters such as quotes or dollar signs or ... This is the way the shell has 'always' behaved, since the Bourne shell back in 1978 or thereabouts.

bash 中,使用一个数组来保存参数:

In bash, use an array to hold the arguments:

argumentArray=(-ir 'hello world')
grep "${argumentArray[@]}" .

或者,如果勇敢/愚蠢,使用eval:

Or, if brave/foolhardy, use eval:

argumentString="-ir 'hello world'"
eval "grep $argumentString ."

另一方面,谨慎往往是勇气中更好的部分,与 eval 合作是谨慎胜于勇敢的地方.如果您不能完全控制 eval 的字符串(如果命令字符串中的任何用户输入未经严格验证),那么您将面临潜在的严重问题.

On the other hand, discretion is often the better part of valour, and working with eval is a place where discretion is better than bravery. If you are not completely in control of the string that is eval'd (if there's any user input in the command string that has not been rigorously validated), then you are opening yourself to potentially serious problems.

请注意,Shell 中描述了 Bash 的扩展顺序GNU Bash 手册中的扩展.特别注意 3.5.3 Shell 参数扩展、3.5.7 分词和 3.5.9 引用删除.

Note that the sequence of expansions for Bash is described in Shell Expansions in the GNU Bash manual. Note in particular sections 3.5.3 Shell Parameter Expansion, 3.5.7 Word Splitting, and 3.5.9 Quote Removal.

这篇关于为什么 shell 忽略通过变量传递给它的参数中的引用字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆