相关疑难解决方法(0)

为什么shell忽略通过变量传递给它的参数中的引号?

这与宣传的一样:

# 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命令正确解释它?

variables syntax bash quoting expansion

33
推荐指数
3
解决办法
6094
查看次数

将字符串转换为参数时,Bash不解析引号

这是我的问题.在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这个例子中调用的变量的构造.

string bash arguments spaces quoting

11
推荐指数
2
解决办法
2981
查看次数

使用 bash 将字符串转换为数组,尊重用于分组的引号

我有一个字符串:

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

bash

3
推荐指数
1
解决办法
1661
查看次数

标签 统计

bash ×3

quoting ×2

arguments ×1

expansion ×1

spaces ×1

string ×1

syntax ×1

variables ×1