0

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

2
  • 1
    You should be using jq instead of regular unix tools like grep, sed, awk etc. Commented Mar 29, 2020 at 17:58
  • 1
    -1 would be an unusual exit code. Exit codes indicating failure are between 1 and 255 (see manual). Commented Mar 29, 2020 at 18:19

2 Answers 2

1
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'
Sign up to request clarification or add additional context in comments.

2 Comments

can you add how to get output in output variable. I try but it say me ` output: command not found No JSON object could be decoded `
I put your result in to a file with name “output”. You can add “>output” at the end of your first command with curl , and then read this file like in my example .
1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.