curl可以工作,但是不会在BASH脚本中执行 [英] curl works, but won't execute in BASH script
问题描述
以下curl命令可从命令行使用。我从服务器收到了有效的响应。
The following curl command works from the command line. I get a valid response from the server.
curl -X POST https://somebaseurl/api/v1/auth/login -H "Content-Type:application/json" -d '{"email": "foo@bar,com", "password": "foo"}'
但是我试图编写这样的BASH脚本
However I am trying to write a BASH script like this
baseUrl=https://somebaseurl
contentTypeJson="\"Content-Type:application/json\""
credentials="'{\"email\": \"foo@bar.com",\"password\": \"foo\"}'"
login="curl -X POST $baseUrl/api/v1/auth/login -H $contentTypeJson -d $credentials"
echo ${login}
response=`${login}`
echo ${response}
我从服务器收到错误的请求响应。但是,如果我将echoed curl命令直接复制到我的终端中,它将起作用。我在做什么错?
I get a bad request response from the server. However if I copy the echoed curl command directly into my terminal it works. What am I doing wrong?
编辑:
根据请求,我会得到
错误的请求'POST api / v1 / auth / login'[期望的应用程序/ json]
As requested I get Bad Request For request 'POST api/v1/auth/login' [Expected application/json]
推荐答案
Bash
和 cURL
在脚本中如何使用引号可能非常特别。如果逃脱被抛弃,那么其他所有事情很容易失败。通过shellcheck.net运行脚本通常对于识别此类问题非常有帮助。下面是根据建议在修复后的脚本的修订版:
Bash
and cURL
can be quite particular how quotes are used within a script. If the escaping gets thrown off then everything else can easily fail. Running the script through shellcheck.net is often very helpful in identifying such issues. Below is a revised version of the script after fixing based upon the suggestions:
#!/bin/bash
baseUrl="https://somebaseurl/api/v1/auth/login"
contentTypeJson="Content-Type:application/json"
credentials="{\"email\": \"foo@bar.com\", \"password\": \"foo\"}"
login="$(curl -X POST "$baseUrl" -H "$contentTypeJson" -d "$credentials")"
echo "${login}"
response="${login}"
echo "${response}"
这篇关于curl可以工作,但是不会在BASH脚本中执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!