How to check if an environment variable exists?

I created an environment variable which is in this format STAGE_${CIRCLE_USERNAME}. So for my case the environment variable is STAGE_bernard. I am trying to check if the environment variable exists but my logic does not seem to be working.

This is the config.yml :

jobs:
  build:
    parameters:
      stage:
        type: string
        default: ""
    executor: aws-cli/default
    steps:
      - aws-cli/setup
      - checkout
      - run: 
          command: |
            if [[ -z "STAGE_${CIRCLE_USERNAME}" ]]; then
               echo "Hi"
            else
              echo "Bie"
            fi
            echo $stage

But when i run it, the output is Bie. But it should be Hi since the environment variable does exist. Can someone please point out what i’m doing wrong. Thank you.

You are currently not checking an environment variable with

if [[ -z "STAGE_${CIRCLE_USERNAME}" ]]; then

Instead, you have created a string of “STAGE_${CIRCLE_USERNAME}”

ahhhh i see now. Thank you for pointing that. I think i can use an indirect variable expansion to fix it.

You should be able to dereference it with eval and \$$VAR_NAME

% cat test.sh
#!/bin/bash

VAR_NAME="STAGE_${CIRCLE_USERNAME}"
if [[ -z $(eval echo \$$VAR_NAME) ]]; then
    echo "Hi"
else
    echo "Bie"
fi
% ./test.sh
Hi
% STAGE_foo=bar ./test.sh
Bie

I’ve done similar things without needing eval(); there might be a better or terser way to do this, but this seems to work for me.

Depending on what you’re trying to do, you might also be able to approach it differently, for example, using contexts.

1 Like