Home > Blockchain >  extract a value from the output of a script and store in a variable winodws?
extract a value from the output of a script and store in a variable winodws?

Time:12-12

According to the document enter image description here

The Azure AD access token is in the access_token value within the output of the call.

What I want is that I need the get the value of the access_token and set it to the variable, so that I could use it in next REST API scripts.

But I'm not very familiar with Bash and curl, can anyone offer advice?

CodePudding user response:

use jq to extract access_token from the json, and VAR=$(...) to store it in a variable,

ACCESS_TOKEN=$(curl -X POST -H 'Content-Type: application/x-www-form-urlencoded' \
https://login.microsoftonline.com/<tenant-id>/oauth2/v2.0/token \
-d 'client_id=<client-id>' \
-d 'grant_type=client_credentials' \
-d 'scope=2ff814a6-3304-4ab8-85cb-cd0e6f879c1d/.default' \
-d 'client_secret=<client-secret>' \
| jq -r .access_token )

then you can use ACCESS_TOKEN like

curl -d access_token="$ACCESS_TOKEN"
  • but be wary, bash is a shitty scripting language, you should not attempt to use bash for complex logic, you should probably switch to a better scripting language like Python, Perl, or PHP, rather than implementing complex logic in Bash. (same goes for Windows's cmd and PowerShell. all 3 are languages unsuitable, but not incapable, of complex logic)
  • Related