在bash中,当参数传递给他们作为一个变量,为什么shell命令忽略参数报价? [英] In bash, why do shell commands ignore quotes in arguments when the arguments are passed to them as a variable?

查看:167
本文介绍了在bash中,当参数传递给他们作为一个变量,为什么shell命令忽略参数报价?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这像宣传的那样:

# example 1
#!/bin/bash
grep -ir 'hello world' .

这不:

# example 2
#!/bin/bash
argumentString="-ir 'hello world'"
grep $argumentString .

尽管世界你好被在第二个例子引号括起来,用grep间$ P $点'你好作为一个参数和全球作为另一个,这意味着,在这种情况下,'你好必应搜索图案和全球将搜索路径。

Despite 'hello world' being enclosed by quotes in the second example, grep interprets 'hello as one argument 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的正确间$ P $点世界你好作为第一个例子中的一个参数。

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

谁能解释这是为什么?是否有扩大的字符串变量,将preserve每个字符的语法正确的方式,使得它通过shell命令正确PTED间$ P $?

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?

推荐答案

在字符串被扩大,它被分成词,但它不重新评估,以寻找特殊字符,如引号或美元符号或...这是壳已永远的行为方式,因为Bourne Shell中早在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.

庆典,使用数组来保存参数:

In bash, use an array to hold the arguments:

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

或者,如果勇敢/有勇无谋,使用评估

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

在另一方面,自由裁量权往往是勇敢的一个重要组成部分,并与评估工作是一个地方,自由裁量权比勇敢更好。如果你不完全是评估'D(如果有一个在尚未经过严格验证的命令字符串任何用户输入)字符串的控制,那么你打开自己潜在的严重问题。

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.

注意扩展为猛砸序列中壳牌描述的扩张在GNU Bash的手册。请特别注意章节3.5.3壳牌参数扩展,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.

这篇关于在bash中,当参数传递给他们作为一个变量,为什么shell命令忽略参数报价?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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