MaxPower
MaxPower

Reputation: 871

curl works, but won't execute in BASH script

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"}'

However I am trying to write a BASH script like this

baseUrl=https://somebaseurl
contentTypeJson="\"Content-Type:application/json\""
credentials="'{\"email\": \"[email protected]",\"password\": \"foo\"}'"
login="curl -X POST $baseUrl/api/v1/auth/login -H $contentTypeJson -d $credentials"
 echo ${login}

response=`${login}`
echo ${response}

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?

edit:

As requested I get Bad Request For request 'POST api/v1/auth/login' [Expected application/json]

Upvotes: 6

Views: 12339

Answers (2)

l'L'l
l'L'l

Reputation: 47159

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\": \"[email protected]\", \"password\": \"foo\"}"
login="$(curl -X POST "$baseUrl" -H "$contentTypeJson" -d "$credentials")"
echo "${login}"

response="${login}"
echo "${response}"

Upvotes: 7

Marc Aldorasi
Marc Aldorasi

Reputation: 708

Executing with backticks interprets the command only as a sequence of words, and doesn't treat quotes specially. To have the shell interpret quotes as if they were interactively typed, use eval ${login} instead.

As an aside, bash has a -x option which will show you commands as they are being executed (run your script with bash -x script.sh instead of bash script.sh or ./script.sh). This will show you the commands correctly quoted, and is more helpful than printing them out using echo.

Upvotes: 4

Related Questions