Groovy 转义引号的脚本问题
Groovy script issue with escaping quotes
我运行正在使用 groovy(在 bash 中有效)执行此 shell 命令:
aws --profile profileName --region us-east-1 dynamodb update-item --table-name tableName --key '{"group_name": {"S": "group_1"}}' --attribute-updates '{"attr1": {"Value": {"S": "STOP"},"Action": "PUT"}}'
这会将 DynamoDB 中的项目值更新为 STOP
。在我的 groovy 脚本中,我 运行 像这样执行此命令:
String command = "aws --profile profileName --region us-east-1 dynamodb update-item --table-name tableName --key '{\"group_name\": {\"S\": \"group_1\"}}' --attribute-updates '{\"attr1\": {\"Value\": {\"S\": \"STOP\"},\"Action\": \"PUT\"}}'"
println(command.execute().text)
当我 运行 使用 groovy afile.groovy
时,没有打印出任何内容,当我检查 DynamoDB 中的 table 时,它没有更新为 STOP
。我转义引号的方式有问题,但我不确定是什么。非常感谢任何见解。
旁注:当我执行像 aws s3 ls
这样的简单 aws 命令时,它会工作并打印出结果,所以这个特定的命令会导致它失败。
您不为 groovy(和底层执行官)报价——您必须为您的 shell 报价。 String 上的 execute()
不像 shell 那样工作 - 底层代码只是在空格处拆分 - 任何引号都只是作为参数的一部分传递下来。
使用["aws", "--profile", profile, ..., "--key", '{"group_name": ...', ...].execute()
并忽略任何引用。
而不是将字符串拼在一起生成 JSON,而是使用 groovy.json.JsonOutput.toJson([group_name: [S: "group_1"]])
我运行正在使用 groovy(在 bash 中有效)执行此 shell 命令:
aws --profile profileName --region us-east-1 dynamodb update-item --table-name tableName --key '{"group_name": {"S": "group_1"}}' --attribute-updates '{"attr1": {"Value": {"S": "STOP"},"Action": "PUT"}}'
这会将 DynamoDB 中的项目值更新为 STOP
。在我的 groovy 脚本中,我 运行 像这样执行此命令:
String command = "aws --profile profileName --region us-east-1 dynamodb update-item --table-name tableName --key '{\"group_name\": {\"S\": \"group_1\"}}' --attribute-updates '{\"attr1\": {\"Value\": {\"S\": \"STOP\"},\"Action\": \"PUT\"}}'"
println(command.execute().text)
当我 运行 使用 groovy afile.groovy
时,没有打印出任何内容,当我检查 DynamoDB 中的 table 时,它没有更新为 STOP
。我转义引号的方式有问题,但我不确定是什么。非常感谢任何见解。
旁注:当我执行像 aws s3 ls
这样的简单 aws 命令时,它会工作并打印出结果,所以这个特定的命令会导致它失败。
您不为 groovy(和底层执行官)报价——您必须为您的 shell 报价。 String 上的 execute()
不像 shell 那样工作 - 底层代码只是在空格处拆分 - 任何引号都只是作为参数的一部分传递下来。
使用["aws", "--profile", profile, ..., "--key", '{"group_name": ...', ...].execute()
并忽略任何引用。
而不是将字符串拼在一起生成 JSON,而是使用 groovy.json.JsonOutput.toJson([group_name: [S: "group_1"]])