Home > Blockchain >  test on 'null' in bash/shell script not working
test on 'null' in bash/shell script not working

Time:12-04

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?

CodePudding user response:

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.

  • Related