Home > Software design >  Using Variables in Curl Requests
Using Variables in Curl Requests

Time:01-27

I'm really new to this and could use some beginner's help!

I'm trying to shorten a Curl command by using a variable for the token, but no matter how I try to format it with quotes or double quotes it just won't work.

The following CURL command works fine:

curl -X GET 'https://myurl.com/test' \
  -H 'auth-version: 2' \
  -H 'auth: 2_oXDMeAWeR3tiPLWjjPJHV_1OzeSwwW_0dyO0iLE67'

But when I try and use a variable for the auth value like this, it does not work:

token = "2_oXDMeAWeR3tiPLWjjPJHV_1OzeSwwW_0dyO0iLE67"
curl -X GET 'https://myurl.com/test' \
  -H 'auth-version: 2' \
  -H 'auth: "$token"'

I am also trying to do something similar using JSON but that fails as well:

token = "2_oXDMeAWeR3tiPLWjjPJHV_1OzeSwwW_0dyO0iLE67"
curl -X GET 'https://myurl.com/test' '{"auth-version": 2, "auth": "$token"}'

How can I get these both to work correctly?

CodePudding user response:

What error specifically are you getting? I am pretty sure token = ... should fail with an error like bash: token: command not found because you are not allowed to have spaces between the name, =, and value. It should be token=.... Otherwise, depending on how you are running these curl commands you might need first export the token in order to access it in subsequent bash commands. i.e:

export token=2_oXDMeAWeR3tiPLWjjPJHV_1OzeSwwW_0dyO0iLE67
curl -X GET 'https://myurl.com/test' \
  -H 'auth-version: 2' \
  -H 'auth: "$token"'

You can check this by doing:

echo $token
 // if it prints nothing you need to use export
  •  Tags:  
  • curl
  • Related