Search code examples
jsonshellcurltoken

extract token from curl result by shell script


I write this script

#!/bin/bash
# cm.sh

  curl -i \
  -H "Content-Type: application/json" \
  -d '
{ "auth": {
    "identity": {
      "methods": ["password"],
      "password": {
        "user": {
          "name": "admin",
          "domain": { "id": "default" },
          "password": "secret"
        }
      }
    }
  }
}' \
  "http://localhost/identity/v3/auth/tokens" ; echo



echo $tokenizer1 
echo $tokenizer2

But all of them(awk or sed) it's the same

  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   540  100   312  100   228    312    228  0:00:01 --:--:--  0:00:01  5142

My goal is to put the token in a variable for later. Thanks guys in advance.


Solution

  • Instead of using the direct result of cURL, you could save the result in a file, and use your grep command on it. Something like this maybe :

    curl -o boulou.txt http://localhost/identity/v3/auth/tokens && cat boulou.txt | grep "X-Subject-Token" | awk '{printf $2}'
    

    Edit, if you just want you desired output, add the --silent to the cURL command :

    curl -o boulou.txt http://localhost/identity/v3/auth/tokens --silent && cat boulou.txt | grep "X-Subject-Token" | awk '{printf $2}'
    

    Edit 2: If you want to export it, and delete your file, you could use something like this :

    export OS_TOKEN=$(curl -o billy.txt hhttp://localhost/identity/v3/auth/tokens --silent &&  cat billy.txt | grep "X-Subject-Token" | awk '{printf $2}') && rm billy.txt