使用反引号作为变量时查找匹配的“”时出现意外的 EOF

使用反引号作为变量时查找匹配的“”时出现意外的 EOF

下面的代码正在运行:

[ec2-user@ip restore]$ echo $snap_name
manual-test-2024-01-11-11-26-19
[ec2-user@ip restore]$  aws rds describe-db-cluster-snapshots --db-cluster-identifier creditpoc3 --query 'DBClusterSnapshots[].{DBClusterSnapshotIdentifier:DBClusterSnapshotIdentifier,Status:Status} | [?DBClusterSnapshotIdentifier == `'"$snap_name"'`']'' | grep creating
[ec2-user@ip-10-0-39-226 restore]$

但是当尝试将输出作为变量获取时,会出现错误:

[ec2-user@ip restore]$ snap_count=`aws rds describe-db-cluster-snapshots --db-cluster-identifier creditpoc3 --query 'DBClusterSnapshots[].{DBClusterSnapshotIdentifier:DBClusterSnapshotIdentifier,Status:Status} | [?DBClusterSnapshotIdentifier == `'"$snap_name"'`']'' | grep creating`
-bash: command substitution: line 1: unexpected EOF while looking for matching `''
-bash: command substitution: line 2: syntax error: unexpected end of file
-bash: command substitution: line 1: unexpected EOF while looking for matching `''
-bash: command substitution: line 2: syntax error: unexpected end of file
[ec2-user@ip restore]$

请在这里建议。

答案1

问题是您正在使用旧式的“反引号”表示法进行命令替换。他们的用途是灰心,除其他原因外,因为它们不能轻易嵌套。

如果您认为您的命令替换仅将您的命令扩展到查询条件的开始反引号(即仅该部分),则可以理解您收到的错误消息

aws rds describe-db-cluster-snapshots --db-cluster-identifier creditpoc3 --query 'DBClusterSnapshots[].{DBClusterSnapshotIdentifier:DBClusterSnapshotIdentifier,Status:Status} | [?DBClusterSnapshotIdentifier == 

然后 shell 尝试连接snap_count来自的变量

  • 该命令调用的结果 - shell 无法解析它,因为您有一个不平衡的左单引号(这是两条错误消息中第一条的原因)
  • 其解释'"$snap_name"'结果是文字字符串,"$snap_name"因为从 shell 的角度来看,它被放在单引号中,然后
  • 其他命令替换由您想要的查询条件的结束反引号开始。这将是命令的输出']'' | grep creating,该命令再次具有不平衡的单引号,并且是两条错误消息中的第二条的原因。

正如 @ilkkachu 所指出的,结果是$snap_count分配了分配的唯一有效部分,即文字 string "$snap_name"

使用推荐的$( ... )- 符号实际的命令替换(即代替反引号),这不会导致与条件` ... `中查询语法可能需要的冲突?DBClusterSnapshotIdentifier

相关内容