【发布时间】:2018-12-17 00:50:44
【问题描述】:
短版: 为什么 shell 脚本会在其生成的字符串中生成嵌入(但不可见)的转义字符 ()?
详细版本:
我有一个脚本,它生成一个 Terraform 命令并执行它。命令生成涉及使用变量替换计算值,如下所示:
...
AWS_VM_NUMBER=1
types="{"
array_limit=$((AWS_VM_NUMBER - 1))
for ((i = 0; i <= $array_limit; i++));
do
var=AWS_INSTANCE_TYPE_${i+1}
types=${types}"\"$i\"=\"${!var}\","
done
instance_types_array=${types%,}"}"
echo $instance_types_array ## prints {"0"="t2.small"} which is the correct fromat
...
# Now, executing a terraform command like this (please ignore the other variables as they exist else where in the code)
terraform apply -var \'access_key=$AWS_ACCESS_KEY\' \
-var \'secret_key=$AWS_SECRET_KEY\' \
-var \'instance_count=$AWS_VM_NUMBER\' \
-var \'region=$AWS_REGION\' \
-var \'instance_types=$instance_types_array\'
执行 terraform 命令时,出现以下错误:
标志 -var 的无效值 "'instance_types={\"0\"=\"t2.small\"}'":无法解析变量的值 ("{\"0\"=\"t2.small \"}'") 作为有效的 HCL:在 1:21:非法字符
如果我将命令放在变量中并回显它,它会在不带反斜杠的情况下打印。但是,如果我复制它并在终端中手动执行它,我会得到同样的错误。只有当我删除双引号并手动输入它们时它才会起作用!
【问题讨论】:
-
是的,谢谢 :)
标签: bash shell escaping terraform