0

Executing this command my end up with 'null':

oauth_token=$(curl -kls \
   --header "Authorization: Bearer $TFE_TOKEN" \
   --header "Content-Type: application/vnd.api+json" \
   --request GET $HOST/api/v2/organizations/$ORGANIZATION/oauth-clients | jq -r ".data[] | select(.attributes.name == \"$1\") | .relationships.\"oauth-tokens\".data[0].id")
    
info "oauth token is: $oauth_token"
if [[ -z $oauth_token ]]; then
    warn "Connection to VSC was not successful as oauth_token is null."
    exit 0
fi

The log output is like this:

[INFO] Showing oauth token of myuser...
[INFO] oauth token is: null
null
null
[INFO] Setting oauth token as env variable)

Why does the 'if' clause in that case not work?

1
  • 3
    Why does the 'if' clause in that case not work? Because null null null is not an empty string. Commented Dec 3, 2021 at 13:54

1 Answer 1

2

Use @tsv to force jq -r to output an empty string for null values:

#!/bin/bash

get_oauth_clients() {
    curl -kls \
    --header "Authorization: Bearer $TFE_TOKEN" \
    --header "Content-Type: application/vnd.api+json" \
    --request GET \
    "$HOST/api/v2/organizations/$ORGANIZATION/oauth-clients"
}

IFS=$'\t' read -r oauth_token < <(
    get_oauth_clients |
    jq -r --arg ATTNAME "$1" '
        .data[]
        | select(.attributes.name == ATTNAME)
        | [ .relationships."oauth-tokens".data[0].id" ]
        | @tsv'
)

info "escaped oauth token is: $oauth_token"

printf -v oauth_token '%b' "$oauth_token" # unescape oauth_token

info "oauth token is: $oauth_token"

if [ -z "$oauth_token" ]
then
    warn "Connection to VSC was not successful as oauth_token is null."
    exit 0
fi

A few things to take note of:

  • you might consider wrapping your complex curl | jq command in a function.

  • it's safer to pass your shell variables to jq as arguments instead of expanding them in the query. See Passing bash variable to jq.

  • using read is not mandatory here but the construct can be handy when you want to get multiple values at the same time with jq -r '[...]|@tsv.

  • TSV values might be escaped; you'll need to unescape them.

Sign up to request clarification or add additional context in comments.

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.