【问题标题】:Shell script producing the escaping character (\) with escaped double qoutes使用转义双引号生成转义字符 (\) 的 Shell 脚本
【发布时间】: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


【解决方案1】:

在传递给terraform 命令之前,您还需要转义封闭的双括号({})。为避免手动转义字符,您可以将其留给bash 中的printf() 函数,它可以执行所需的转义序列。

使用带有-v 的命令将完成的转义应用于新变量并将其传递给terraform 命令

printf -v esc_instance_types "%q" "${instance_types_array}"

现在esc_instances_types 在打印为时会有一个值

printf "%s\n" "${esc_instances_types}"
\{\"0\"=\"t2.small\"\}

您现在可以将此变量传递给您需要的命令。请参阅printf() - Format Strings 了解更多信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-21
    • 1970-01-01
    • 2022-10-25
    • 1970-01-01
    • 2020-11-26
    • 1970-01-01
    • 2013-01-06
    相关资源
    最近更新 更多