使用 bash 脚本将变量传递给 CURL 命令(变量值中带有双引号) [英] Passing variable into CURL command using bash scripting (with double quotes in variables value)

查看:34
本文介绍了使用 bash 脚本将变量传递给 CURL 命令(变量值中带有双引号)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am having trouble with creating and then using a variable that contains double quotes in the value and have really struggled to find any other posts with such an example, some with special characters but none specifically looking at using double quotes.

我希望在 bash 脚本中创建一个变量,该变量将允许我使用text"值作为变量执行以下 CURL 命令

I am looking to create a variable in a bash script that will allow me to perform the following CURL command with the "text" value as the variable

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

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

I have tried the below but, although the echo looks like it was passing the right value, the CURL response is a 400 error - invalid response.

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

推荐答案

(这里有一个副本,但我找不到.)

(There is a duplicate for this, but I can never find it.)

使用像 jq 这样的工具来构建 JSON.

Use a tool like jq to build the JSON.

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

这篇关于使用 bash 脚本将变量传递给 CURL 命令(变量值中带有双引号)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆