![使用 curl 用 shell 脚本值替换 Json 变量的问题](https://linux22.com/image/1575737/%E4%BD%BF%E7%94%A8%20curl%20%E7%94%A8%20shell%20%E8%84%9A%E6%9C%AC%E5%80%BC%E6%9B%BF%E6%8D%A2%20Json%20%E5%8F%98%E9%87%8F%E7%9A%84%E9%97%AE%E9%A2%98.png)
#!/bin/bash
#CONFIG_FILE_PATH is the path of the json file as argument while running the script
CONFIG_FILE_PATH=$1
CUST_NAME=$2
curl -X POST -i -H "Accept: application/json" -H "Content-Type:application/json" --data-binary @$CONFIG_FILE_PATH "http://localhost:8080/service"
下面是我尝试用 shell 脚本变量 CUST_NAME 替换 ${CUST_NAME} 的 json。但不起作用。有人能帮忙吗?
{
"queries": [
{
"query": "select * from customer where account_name like '${CUST_NAME}'"
}
]
}
答案1
CONFIG_FILE_PATH
您在行中使用的方法curl
不会被 shell 读取和解析,因此不会发生变量替换。有很多方法可以解决这个问题,但我更喜欢通过以下方式进行自己的替换sed
:
JSON 模板:
{
"queries": [
{
"query": "select * from customer where account_name like '##CUST_NAME##'"
}
]
}
脚本:
#!/bin/bash
#CONFIG_FILE_PATH is the path of the json file as argument while running the script
CONFIG_FILE_PATH=$1
CONFIG_FILE=$(cat "$CONFIG_FILE_PATH" | sed "s/##CUST_NAME##/$2/g")
curl -X POST -i -H "Accept: application/json" -H "Content-Type:application/json" --data-binary "$CONFIG_FILE" "http://localhost:8080/service"