Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Bash中单引号与双引号的混淆_Bash_Quoting - Fatal编程技术网

Bash中单引号与双引号的混淆

Bash中单引号与双引号的混淆,bash,quoting,Bash,Quoting,在bash中,我知道单引号和双引号的作用,但随着嵌套的深入,我会迷失方向 例如,它们之间的区别是什么 export VAR=$(echo "${VAL}-venv" | awk '{print tolower($0)}') 及 或者就这件事来说 $(somecmd "${ROLE_NAME}" | someothercmd) "$(somecmd "${ROLE_NAME}" | someothercmd)" 及 防止外壳扩展$0。Awk可以看到$0 awk "{print tolower

在bash中,我知道单引号和双引号的作用,但随着嵌套的深入,我会迷失方向

例如,它们之间的区别是什么

export VAR=$(echo "${VAL}-venv" | awk '{print tolower($0)}')

或者就这件事来说

$(somecmd "${ROLE_NAME}" | someothercmd)
"$(somecmd "${ROLE_NAME}" | someothercmd)"

防止外壳扩展
$0
。Awk可以看到
$0

awk "{print tolower($0)}"
使shell扩展到当前脚本或shell的名称,类似于交互式会话中的
-bash
。Awk可以看到

print tolower(-bash)
因为它不知道任何名为
bash
的变量,所以它将其初始化为0

$(somecmd "${ROLE_NAME}" | someothercmd)
返回的输出

somecmd "${ROLE_NAME}" | someothercmd
输出经过分词和全局扩展

"$(somecmd "${ROLE_NAME}" | someothercmd)"
做同样的事情,但是分词和全局扩展不会发生

但是,如果命令替换位于赋值的右侧,则默认情况下禁止全局搜索和分词:

var=$(somecmd "${ROLE_NAME}" | someothercmd)
相当于

var="$(somecmd "${ROLE_NAME}" | someothercmd)"
不过,引用一下也没什么坏处

请注意,“默认情况下被抑制”语句仅适用于整个右侧;在它里面,你仍然需要引用。这在处理数组时很重要:观察

$ myfunc () { echo 1 2 3; }                  # Generates three words
$ arr=($(myfunc))                            # Unquoted within ()
$ declare -p arr
declare -a arr='([0]="1" [1]="2" [2]="3")'   # Three array elements
$ arr=("$(myfunc)")                          # Quoted within ()
$ declare -p arr
declare -a arr='([0]="1 2 3")'               # One array element

最后,“右侧的自动引号仅适用于扩展,即,
var=$1
(无需引号)或
var=$(命令)
(无需在
$()
;可能在
命令本身中需要。当右侧包含空格时,它不适用:
var=abc
不将
abc
分配给var。它尝试将环境变量
var
设置为值
a
,然后在第二次检查中使用参数
c
运行命令
b
例如,我的实际使用导致了不同的行为。我的形式是
--role$(aws iam get role--role name“${role\u name}”| jq--raw output.role.Arn')
,工作正常,但
--role“$(aws iam get role--role name“${role\u name}”| jq--raw output.role.Arn'))"
会产生各种各样的错误。@raxacoricofallapatorius,这取决于
jq
的输入以及
--role
期望什么样的选项–在不知道细节的情况下很难说。但是,在这两种情况下,对外部引号内的所有内容的处理不都是一样的吗?添加外部引号应该正好在前面在整个过程的最后进行ent拆分和全局展开。在这种情况下,所涉及的值是相同的(没有特殊字符的空格)。@raxaco我必须看到确切的字符串才能分辨出来。
var="$(somecmd "${ROLE_NAME}" | someothercmd)"
$ myfunc () { echo 1 2 3; }                  # Generates three words
$ arr=($(myfunc))                            # Unquoted within ()
$ declare -p arr
declare -a arr='([0]="1" [1]="2" [2]="3")'   # Three array elements
$ arr=("$(myfunc)")                          # Quoted within ()
$ declare -p arr
declare -a arr='([0]="1 2 3")'               # One array element