Vivek Sable
Vivek Sable

Reputation: 10213

How to get curl command output into variable

I want to take output of following command one variable and then want to get email id and id in two variables.

Code

curl -s -b ${COOKIE_FILE} -c ${COOKIE_FILE} 'https://api.xxxx.xxxx.com/sso/user?email='${USER_EMAIL} |python -m json.tool

Output

[
    {
        "createdAt": "2017-12-08T11:07:15.000Z",
        "email": "[email protected]",
        "gravatarUrl": "https://gravatar.com/avatar/13656",
        "id": 937,
        "updatedAt": "2017-12-08T11:07:15.000Z",
        "username": "339cba4c-d90c-11e7-bc18-005056ba0d15"
    }
]

one more, if USER_EMAIL is wrong then we get output as [] then I have to print Email ID is not present and I will exit code exit -1

I am python developer, doing scripting first time

Upvotes: 0

Views: 1007

Answers (2)

William Pursell
William Pursell

Reputation: 212148

Use jq to parse json:

$ cat input
[
    {
        "createdAt": "2017-12-08T11:07:15.000Z",
        "email": "[email protected]",
        "gravatarUrl": "https://gravatar.com/avatar/13656",
        "id": 937,
        "updatedAt": "2017-12-08T11:07:15.000Z",
        "username": "339cba4c-d90c-11e7-bc18-005056ba0d15"
    }
]
$ jq -r '.[] | (.email,.id)' input
[email protected]
937
$ read email id << EOF
> $(jq -r '.[] | (.email,.id)' input | tr \\n ' ')
> EOF
$ echo $email
[email protected]
$ echo $id
937

To check if email was valid, you can do things like:

echo "${email:?}"

or

test -z "$email" && exit 1

Upvotes: 1

DamianK
DamianK

Reputation: 382

id=$(cat output | grep -w "id" | awk -F ':' {'print $2'} | sed -e 's|[," ]||g'); echo $id

Do the same for email. Or second way like anubhava suggest in comment, using jq. ( Probably you will need to install jq first , apt-get install jq ). And then:

cat output | jq '.[].email'

Upvotes: 1

Related Questions