【问题标题】:Passing variable into CURL command using bash scripting (with double quotes in variables value)使用 bash 脚本将变量传递给 CURL 命令(变量值中带有双引号)
【发布时间】:2018-11-08 20:43:07
【问题描述】:

我在创建然后使用值中包含双引号的变量时遇到了麻烦,并且真的很难找到任何其他具有此类示例的帖子,其中一些带有特殊字符,但没有专门关注使用双引号。

我希望在 bash 脚本中创建一个变量,它允许我执行以下 CURL 命令,并将“文本”值作为变量

curl -v -o POST \
-u "apikey:-------------------------------------" \
-H "Content-Type: application/json" \
-d '{
  "text":"Hello World",
  "features": {
  "sentiment": {},
  "categories": {},
  "concepts": {},
  "keywords": {},
  "emotion": {} 
  }
}' \
"https://gateway-wdc.watsonplatform.net/natural-language- 
understanding/api/v1/analyze?version=2018-03-19" 
$SHELL

我已经尝试了以下方法,但是,虽然 echo 看起来传递了正确的值,但 CURL 响应是 400 错误 - 无效响应。

VAR1='"Hello World"'

echo "VAR1=${VAR1}"
echo 

curl -v -o POST \
-u "apikey:-------------------------------------" \
-H "Content-Type: application/json" \
-d '{
     "text":${VAR1},
     "features": {
     "sentiment": {},
     "categories": {},
     "concepts": {},
     "keywords": {},
     "emotion": {}  
    }
}' \
"https://gateway-wdc.watsonplatform.net/natural-language- 
understanding/api/v1/analyze?version=2018-03-19"
$SHELL

【问题讨论】:

标签: bash variables curl


【解决方案1】:

(有一个重复的,但我永远找不到它。)

使用jq 之类的工具来构建 JSON。

data=$(jq --argjson x "$VAR1" '
  {
    text: $x,
    features: {},
    sentiment: {},
    categories: {},
    concepts: {},
    keywords: {},
    emotion: {}  
  }'
)
curl ... -d "$data" ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-08
    • 1970-01-01
    • 1970-01-01
    • 2020-05-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多