1

I have a code which returns an access token string.

#!/bin/bash
token=$(curl --globoff -X POST "https://example.com/token" -F 'grant_type=client_credentials' -F 'client_id=d86fc9b690963b8dda602bd26f33454r457e9024a4ecccf4c3bbf66ffcbc241b' -F 'client_code'='ff148c56118728b62c9f2ew3e4r009a7a1c645276b70611fa32fa055b9944934')
echo "$token" > Token.txt

The output given by this command is :

{
    "access_token": "5048e7d38e73b4a809a4fcb219b63ae34f34f43f83d6663ffd777203afb5654ab",
    "token_type": "bearer",
    "expires_in": 7200
}

ie. the variable token contains the above result. My question is how to get the access token 5048e7d38e73b4a809a4fcb219b63ae34f34f43f83d6663ffd777203afb5654ab alone from this and save to another variable.

1
  • Download and install JSON parser utility jq Commented Sep 28, 2017 at 7:39

2 Answers 2

3

First try jq, if not possible, this is a workaround using awk:

access_token=$(curl --globoff -X POST "https://example.com/token" \
                    -F 'grant_type=client_credentials' \
                    -F 'client_id=d86fc9b690963b8dda602bd26f33454r457e9024a4ecccf4c3bbf66ffcbc241b' \
                    -F 'client_code'='ff148c56118728b62c9f2ew3e4r009a7a1c645276b70611fa32fa055b9944934'|\
                    awk -F\" '/access_token/{print $4}')

The way to do this in jq would be to do

access_token=$(curl --globoff -X POST "https://example.com/token" \
                    -F 'grant_type=client_credentials' \
                    -F 'client_id=d86fc9b690963b8dda602bd26f33454r457e9024a4ecccf4c3bbf66ffcbc241b' \
                    -F 'client_code'='ff148c56118728b62c9f2ew3e4r009a7a1c645276b70611fa32fa055b9944934'|\
                    jq -r '.access_token' )
Sign up to request clarification or add additional context in comments.

3 Comments

Why would you want to parse JSON using Awk? I think it would be wise to recommend best practices than suggesgting short-cuts
Well it's a pretty simple JSON @Inian , of course jqis a very nice tool, but you have to take in consideration that some peolple can't install things in the system.
Fair point, but it would be good to check with OP on that and suggest if they could use other tools
0

I am using this in bash to get and use the token ...

access_tok=$(curl -s -X POST -d "client_id=$(< "$LOGON_HOME/client_id" )&client_secret=$(< "$LOGON_HOME/client_secret")&grant_type=client_credentials" "${TOKEN_URL}" )
access_tok=${access_tok#*access_token\":\"}
access_tok=${access_tok%%\"*}

and later

curl -l -s -O -H "Authorization: Bearer ${access_tok}" "${FILE_URL}"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.