使用curl POST和bash脚本函数中定义的变量

AGl*_*nTU 144 bash json curl javascript-objects

当我回音时,我得到了这个,当我将它输入终端时运行

curl -i \
-H "Accept: application/json" \
-H "Content-Type:application/json" \
-X POST --data '{"account":{"email":"akdgdtk@test.com","screenName":"akdgdtk","type":"NIKE","passwordSettings":{"password":"Starwars1","passwordConfirm":"Starwars1"}},"firstName":"Test","lastName":"User","middleName":"ObiWan","locale":"en_US","registrationSiteId":"520","receiveEmail":"false","dateOfBirth":"1984-12-25","mobileNumber":"9175555555","gender":"male","fuelActivationDate":"2010-10-22","postalCode":"10022","country":"US","city":"Beverton","state":"OR","bio":"This is a test user","jpFirstNameKana":"unsure","jpLastNameKana":"ofthis","height":"80","weight":"175","distanceUnit":"MILES","weightUnit":"POUNDS","heightUnit":"FT/INCHES"}' https://xxx:xxxxx@xxxx-www.xxxxx.com/xxxxx/xxxx/xxxx
Run Code Online (Sandbox Code Playgroud)

但是当在bash脚本文件中运行时,我收到此错误

curl: (6) Could not resolve host: application; nodename nor servname provided, or not known
curl: (6) Could not resolve host: is; nodename nor servname provided, or not known
curl: (6) Could not resolve host: a; nodename nor servname provided, or not known
curl: (6) Could not resolve host: test; nodename nor servname provided, or not known
curl: (3) [globbing] unmatched close brace/bracket at pos 158
Run Code Online (Sandbox Code Playgroud)

这是文件中的代码

curl -i \
-H '"'Accept: application/json'"' \
-H '"'Content-Type:application/json'"' \
-X POST --data "'"'{"account":{"email":"'$email'","screenName":"'$screenName'","type":"'$theType'","passwordSettings":{"password":"'$password'","passwordConfirm":"'$password'"}},"firstName":"'$firstName'","lastName":"'$lastName'","middleName":"'$middleName'","locale":"'$locale'","registrationSiteId":"'$registrationSiteId'","receiveEmail":"'$receiveEmail'","dateOfBirth":"'$dob'","mobileNumber":"'$mobileNumber'","gender":"'$gender'","fuelActivationDate":"'$fuelActivationDate'","postalCode":"'$postalCode'","country":"'$country'","city":"'$city'","state":"'$state'","bio":"'$bio'","jpFirstNameKana":"'$jpFirstNameKana'","jpLastNameKana":"'$jpLastNameKana'","height":"'$height'","weight":"'$weight'","distanceUnit":"MILES","weightUnit":"POUNDS","heightUnit":"FT/INCHES"}'"'" "https://xxx:xxxxx@xxxx-www.xxxxx.com/xxxxx/xxxx/xxxx"
Run Code Online (Sandbox Code Playgroud)

我假设我的引号有问题,但我和他们玩了很多,我也遇到了类似的错误.所有变量都在实际脚本中使用不同的函数定义

Sir*_*hos 240

您不需要将包含自定义标头的引号传递给curl.此外,data应引用参数中间的变量.

首先,编写一个生成脚本后期数据的函数.这样可以避免出现与shell引用相关的各种麻烦,并且可以更轻松地读取维护脚本,而不是像在尝试中那样在curl的调用行上提供post数据:

generate_post_data()
{
  cat <<EOF
{
  "account": {
    "email": "$email",
    "screenName": "$screenName",
    "type": "$theType",
    "passwordSettings": {
      "password": "$password",
      "passwordConfirm": "$password"
    }
  },
  "firstName": "$firstName",
  "lastName": "$lastName",
  "middleName": "$middleName",
  "locale": "$locale",
  "registrationSiteId": "$registrationSiteId",
  "receiveEmail": "$receiveEmail",
  "dateOfBirth": "$dob",
  "mobileNumber": "$mobileNumber",
  "gender": "$gender",
  "fuelActivationDate": "$fuelActivationDate",
  "postalCode": "$postalCode",
  "country": "$country",
  "city": "$city",
  "state": "$state",
  "bio": "$bio",
  "jpFirstNameKana": "$jpFirstNameKana",
  "jpLastNameKana": "$jpLastNameKana",
  "height": "$height",
  "weight": "$weight",
  "distanceUnit": "MILES",
  "weightUnit": "POUNDS",
  "heightUnit": "FT/INCHES"
}
EOF
}
Run Code Online (Sandbox Code Playgroud)

然后在调用curl时很容易使用该函数:

curl -i \
-H "Accept: application/json" \
-H "Content-Type:application/json" \
-X POST --data "$(generate_post_data)" "https://xxx:xxxxx@xxxx-www.xxxxx.com/xxxxx/xxxx/xxxx"
Run Code Online (Sandbox Code Playgroud)

这就是说,这里有一些关于shell引用规则的说明:

-H参数中的双引号(如中-H "foo bar")告诉bash将内部的内容保留为单个参数(即使它包含空格).

--data参数中的单引号(如同--data 'foo bar')执行相同的操作,除了它们逐字传递所有文本(包括双引号字符和美元符号).

要在单个引用文本的中间插入变量,您必须结束单引号,然后使用双引号变量连接,并重新打开单引号以继续文本:'foo bar'"$variable"'more foo'.

  • "'"$ <variable name>"'"解决了我的问题,我需要引号不被省略.谢谢. (9认同)
  • 这个解决方案有效,但我认为您可以在变量周围发出额外的双引号。因此,您可以这样做: --data '{"account": {"email": "'"$email"'"} }' 你可以这样做: --data '{"account": {"email": " '$电子邮件'"} }' (4认同)
  • 在第二个EOF之后有一个空格时没有工作:`EOF`.删除后一切都很好. (3认同)
  • @dbreaux 这取决于您在哪里运行 curl 命令。如果命令在脚本中,您只需在同一脚本中的任意位置定义该函数。如果您直接从命令行运行 curl,您有多种选择,其中之一是在新文件中键入函数,然后在命令行运行 `source my_new_file` 以在当前环境中定义函数。之后,您可以按照指示运行 curl 命令。 (2认同)
  • @slashdottir 这是一个名为 Here Documents 的 bash 功能。您可以在[此链接](http://tldp.org/LDP/abs/html/here-docs.html) 阅读更多详细信息 - 特别是查看示例 19-5。这里也已经有一个[关于它的完整问题](/sf/ask/206715701/)所以。 (2认同)

pba*_*ski 81

使用https://httpbin.org/和内联bash脚本测试解决方案
1.对于没有空格的变量ie 1:
只需在替换所需字符串'之前和之后添加$variable

for i in {1..3}; do \
  curl -X POST -H "Content-Type: application/json" -d \
    '{"number":"'$i'"}' "https://httpbin.org/post"; \
done
Run Code Online (Sandbox Code Playgroud)

2.对于带空格的输入:
使用附加包装变量"ie "el a":

declare -a arr=("el a" "el b" "el c"); for i in "${arr[@]}"; do \
  curl -X POST -H "Content-Type: application/json" -d \
    '{"elem":"'"$i"'"}' "https://httpbin.org/post"; \
done
Run Code Online (Sandbox Code Playgroud)

哇工作:)

  • 我发现接受的和第二个投票的答案在`/ bin/sh`中不起作用.但是,这个答案就行了.它比其他答案简单得多.非常感谢!我用一些更好的换行格式编辑了你的答案.否则,很难发现这种光彩.队友的欢呼声 (3认同)
  • 当“$i”包含空格时不起作用。:( (2认同)

小智 29

Curl可以从文件发布二进制数据,所以我一直在使用进程替换并利用文件描述符,每当我需要发布一些令人讨厌的curl并仍然想要访问当前shell中的vars时.就像是:

curl "http://localhost:8080" \
-H "Accept: application/json" \
-H "Content-Type:application/json" \
--data @<(cat <<EOF
{
  "me": "$USER",
  "something": $(date +%s)
  }
EOF
)
Run Code Online (Sandbox Code Playgroud)

这看起来就像--data @/dev/fd/<some number>正常文件一样被处理.无论如何,如果你想看到它在本地工作,只需nc -l 8080先运行,然后在另一个shell中触发上述命令.你会看到类似的东西:

POST / HTTP/1.1
Host: localhost:8080
User-Agent: curl/7.43.0
Accept: application/json
Content-Type:application/json
Content-Length: 43

{  "me": "username",  "something": 1465057519  }
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,你可以在heredoc中调用子shell和诸如此类的引用变量.快乐的黑客希望这有助于'"'"'""""'''""''.

  • 另一个答案对我不起作用,因为我正试图在Zabbix的警报中调用它。这一个完美地解决了它,并且更加干净。 (2认同)

xgM*_*gMz 8

在此处的答案指导下,以下是对我真正有用的方法:

export BASH_VARIABLE="[1,2,3]"
curl http://localhost:8080/path -d "$(cat <<EOF
{
  "name": $BASH_VARIABLE,
  "something": [
    "value1",
    "value2",
    "value3"
  ]
}
EOF
)" -H 'Content-Type: application/json'
Run Code Online (Sandbox Code Playgroud)


gly*_*yph 7

迟了几年,但是如果您使用eval或反引号替换,这可能会对某人有所帮助:

postDataJson="{\"guid\":\"$guid\",\"auth_token\":\"$token\"}"
Run Code Online (Sandbox Code Playgroud)

使用sed从响应的开头和结尾除去引号

$(curl --silent -H "Content-Type: application/json" https://${target_host}/runs/get-work -d ${postDataJson} | sed -e 's/^"//' -e 's/"$//')
Run Code Online (Sandbox Code Playgroud)


小智 5

  • 来自阿索斯爵士的信息非常有效!!

这是我必须在我的 couchDB 的 curl 脚本中使用它的方式。它真的帮了很多忙。谢谢!

bin/curl -X PUT "db_domain_name_:5984/_config/vhosts/$1.couchdb" -d '"/'"$1"'/"' --user "admin:*****"
Run Code Online (Sandbox Code Playgroud)


小智 5

现有的答案指出,curl 可以从文件中发布数据,并使用heredocs 来避免过多的引号转义,并清楚地将 JSON 分解为新行。但是,无需定义函数或捕获 cat 的输出,因为curl 可以从标准输入发布数据。我发现这个表格非常可读:

curl -X POST -H 'Content-Type:application/json' --data '$@-' ${API_URL} << EOF
{
  "account": {
    "email": "$email",
    "screenName": "$screenName",
    "type": "$theType",
    "passwordSettings": {
      "password": "$password",
      "passwordConfirm": "$password"
    }
  },
  "firstName": "$firstName",
  "lastName": "$lastName",
  "middleName": "$middleName",
  "locale": "$locale",
  "registrationSiteId": "$registrationSiteId",
  "receiveEmail": "$receiveEmail",
  "dateOfBirth": "$dob",
  "mobileNumber": "$mobileNumber",
  "gender": "$gender",
  "fuelActivationDate": "$fuelActivationDate",
  "postalCode": "$postalCode",
  "country": "$country",
  "city": "$city",
  "state": "$state",
  "bio": "$bio",
  "jpFirstNameKana": "$jpFirstNameKana",
  "jpLastNameKana": "$jpLastNameKana",
  "height": "$height",
  "weight": "$weight",
  "distanceUnit": "MILES",
  "weightUnit": "POUNDS",
  "heightUnit": "FT/INCHES"
}
EOF
Run Code Online (Sandbox Code Playgroud)


Sha*_*iri 5

我们可以使用单引号为 curl分配一个变量,'并将其他一些变量包装在双单双引号中,"'"以便在curl-variable 中进行替换。然后我们可以很容易地使用curl 变量,这里是MERGE.

例子:

# other variables ... 
REF_NAME="new-branch";

# variable for curl using single quote => ' not double "
MERGE='{
    "repository": "tmp",
    "command": "git",
    "args": [
        "pull",
        "origin",
        "'"$REF_NAME"'"
    ],
    "options": {
        "cwd": "/home/git/tmp"
    }
}';
Run Code Online (Sandbox Code Playgroud)

注意这一行:

    "'"$REF_NAME"'"
Run Code Online (Sandbox Code Playgroud)

所以我们可以使用这个 bash 变量$MERGE并像往常一样调用curl

curl -s -X POST localhost:1365/M -H 'Content-Type: application/json' --data "$MERGE" 
Run Code Online (Sandbox Code Playgroud)