这与宣传的一样:
# example 1
#!/bin/bash
grep -ir 'hello world' .
Run Code Online (Sandbox Code Playgroud)
这不是:
# example 2
#!/bin/bash
argumentString="-ir 'hello world'"
grep $argumentString .
Run Code Online (Sandbox Code Playgroud)
尽管'hello world'在第二个例子中被引号括起来,但grep解释'hello为一个参数和world'另一个参数,这意味着,在这种情况下,'hello将是搜索模式world'并将成为搜索路径.
同样,这仅在从argumentString变量扩展参数时发生.grep 'hello world'在第一个示例中正确解释为单个参数.
谁能解释为什么会这样?有没有一种正确的方法来扩展一个字符串变量,它将保留每个字符的语法,以便shell命令正确解释它?
这是我的问题.在bash 3中:
$ test='One "This is two" Three'
$ set -- $test
$ echo $2
"This
Run Code Online (Sandbox Code Playgroud)
如何获得的bash了解行情,并返回$ 2作为This is two和不"This?不幸的是,我不能改变test这个例子中调用的变量的构造.
我有一个字符串:
Str='This string has "a substring"'
Run Code Online (Sandbox Code Playgroud)
字符串有逗号,所以如果我打印字符串,我会看到:
echo "${Str}"
This string has "a substring".
Run Code Online (Sandbox Code Playgroud)
如果我输入命令:
$ Tmp=( ${Str} )
$ echo "${Tmp[3]}"
"a
$ echo "${Tmp[4]}"
Substring"
Run Code Online (Sandbox Code Playgroud)
我想打印:有a Substring
什么建议吗?我可以更改逗号,但必须将其从 Str 打印到 Tmp