user3605317
user3605317

Reputation: 143

Passing Bearer token as variable in bash

I am trying to pass a Bearer token (variable $token)to invoke a job via curl command. However the single quote after the -H is not letting the value of variable $token being passed to curl command.

curl -X POST 'https://server.domain.com/v2/jobs/28723316-9373-44ba-9229-7c796f21b099/runs?project_id=aff59748-260a-476e-9578-b4f4a93e7a92' -H 'Content-Type: application/json' -H 'Authorization: Bearer $token  -d { "job_run": {} }'

I get this error:

{"code":400,"error":"Bad Request","reason":"Bearer token format is invalid. Expected: 'Bearer '. Received: 'Bearer $token -d { "job_run": {} }'.","message":"Bearer token is invalid."}

I tried adding like the escape character with the variable $token:

curl -X POST 'https://server.domain.com/v2/jobs/28723316-9373-44ba-9229-7c796f21b099/runs?project_id=aff59748-260a-476e-9578-b4f4a93e7a92' -H 'Content-Type: application/json' -H 'Authorization: Bearer "\$token\"  -d { "job_run": {} }'

I get the same error: {"code":400,"error":"Bad Request","reason":"Bearer token format is invalid. Expected: 'Bearer '. Received: 'Bearer "\$token\" -d { "job_run": {} }'.","message":"Bearer token is invalid."}

I tried double quotes as well, it has been a few hours and I am unable to extract he variable value $token within single quotes.

Could some please assist and give me the correct syntax?

Thanks in advance

Upvotes: 5

Views: 13403

Answers (2)

Sajan Jacob K
Sajan Jacob K

Reputation: 524

this works for me

token=$(curl 'https://example.com/v1.2/auths/login' \
-H 'Accept: application/json, text/plain, */*' \
-H 'Content-Type: application/json' \
--data-raw '{"username":"username","password":"password"}'  | jq '.token')
echo $token

#to remove the double quotes from the token string 
token=`sed -e 's/^"//' -e 's/"$//' <<<"$token"`  

 curl 'https://example.com/otherapi' \
  -H 'Accept: application/json, text/plain, */*' \
  -H "Authorization: Bearer $token" 

Upvotes: 2

user000001
user000001

Reputation: 33367

The problem here are the quotes. It should be like this:

curl -X POST 'https://server.domain.com/v2/jobs/28723316-9373-44ba-9229-7c796f21b099/runs?project_id=aff59748-260a-476e-9578-b4f4a93e7a92' -H 'Content-Type: application/json' -H "Authorization: Bearer $token"  -d '{ "job_run": {} }'

In multiline:

curl -X POST 'https://server.domain.com/v2/jobs/28723316-9373-44ba-9229-7c796f21b099/runs?project_id=aff59748-260a-476e-9578-b4f4a93e7a92' \
     -H 'Content-Type: application/json' \
     -H "Authorization: Bearer $token"  \ 
     -d '{ "job_run": {} }'

Specifically, variables in bash aren't interpolated when in single quotes ('). Thus, we set the dynamic string inside double quotes (")

-H "Authorization: Bearer $token"

Also the -H and -d arguments are distinct, they should be quoted separately, in your code you have them combined in a single argument.

Upvotes: 12

Related Questions