【问题标题】:why is bash adding single quotes to escaped double quotes for command为什么bash在命令的转义双引号中添加单引号
【发布时间】:2015-02-11 05:52:41
【问题描述】:

我在 EC2 AWS-AMI Linux 上执行作为脚本一部分的命令时遇到问题。

作为命令的一部分,我必须将一些变量传递给 CLI,包括 --subnet-ids "subnet-c123456" "subnet-b123456" "subnet-a123456" 这样的引号,因此我将代码块创建为

#!/bin/sh
set -x
......
MySubnetA="subnet-a123456"
MySubnetB="subnet-b123456"
MySubnetC="subnet-c123456"
$(aws --profile myProfile --region myRegion rds create-db-subnet-group --db-subnet-group-name ${!1} --db-subnet-group-description ${!1} --subnet-ids \"${MySubnetA}\" \"${MySubnetB}\" \"${MySubnetC}\"  --tags Key=Name,Value=${!1})

当我运行脚本时,输出显示的命令在转义的双引号周围带有单引号,这会导致 CLI 失败。

++ aws --profile myProfile --region us-west-1 rds create-db-subnet-group --db-subnet-group-name myDBgroup --db-subnet-group-description myDBgroup --subnet-ids '"subnet-a123456"' '"subnet-b123456"' '"subnet-c123456"' --tags Key=Name,Value=myDBgroup

如何传递命令,使双引号不包含在单引号中。

更新

根据下面的评论,如果我回显命令字符串,然后在终端中复制/粘贴运行,则命令按预期执行。但是当在脚本中运行时它会失败。 bash 脚本是否会在命令中添加额外的字符导致它失败?

谢谢 艺术

【问题讨论】:

    标签: bash escaping aws-cli


    【解决方案1】:

    单引号是使用 xtrace 的产物,实际上并不是参数的一部分。它们只是表明双引号实际上是参数的一部分,而不仅仅是表明参数是一个单词。

    【讨论】:

    • 感谢@Ignacio,我注意到如果我回显命令然后复制/粘贴运行,命令会按预期执行,但是在运行脚本时会失败。 bash 是否可以在执行过程中添加一些额外的报价或承租人?
    • 你知道那是什么意思,对吧?你不需要双引号。因为 shell 在传递参数之前会剥离它们。
    【解决方案2】:

    aws 命令中的变量无需使用转义引号,将其用作:

    $(aws --profile myProfile --region myRegion rds create-db-subnet-group --db-subnet-group-name ${!1} --db-subnet-group-description ${!1} --subnet-ids ${MySubnetA} ${MySubnetB} ${MySubnetC} --tags Key=Name,Value=${!1})

    或者引用它们而不转义:

    $(aws --profile myProfile --region myRegion rds create-db-subnet-group --db-subnet-group-name ${!1} --db-subnet-group-description ${!1} --subnet-ids "$MySubnetA" "$MySubnetB" "$MySubnetC" --tags Key=Name,Value=${!1})

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多