1

I'm having issues with the below script. It should exit only if there is not a variable set by that name.

#!/bin/bash
set -e

echo 'START: env_vars_config'

required_var(){
  VARIABLE=$1
  echo "detecting if $VARIABLE exists"
  echo ${!VARIABLE}
  if [ -z ${!VARIABLE}+x ]; then
    echo "${VARIABLE} was defined"
  else
    echo "Need to set environment var $VARIABLE" && exit 1;
  fi
}

# these are required variables to deploy
required_var MONGO_URL
required_var AWS_REGION
required_var AUTOSCALING_GROUP_NAME
required_var LATEST_STABLE_COMMIT
required_var ENV_FILE
required_var DEPLOY_FILE
required_var POSTMAN_ENVIRONMENT_UID
required_var POSTMAN_COLLECTION_UID
required_var POSTMAN_API_KEY
required_var MANDRILL_KEY
required_var SERVER_SECRET
required_var S3_BUCKET
required_var ELASTIC_URL
required_var ELASTIC_PASSWORD
required_var ELASTIC_PREFIX


echo 'END: env_vars_config'

Right now this script always exits on the first check MONGO_URL however I know this is variable set and is a string.

  • What would a check for unset look like?
  • What would a check for unset or empty string look like?

FIXED 2 issues, firstly the + symbol at the end of the if statement was a typo. Secondly I had the order of the if statement backwards.

  if [ -z "${!VARIABLE}" ]; then
    echo "Need to set environment var $VARIABLE" && exit 1;
  else
    echo "${VARIABLE} was defined"
  fi

1 Answer 1

3

The problem is:

if [ -z ${!VARIABLE}+x ]; then
    echo "${VARIABLE} was defined"
else
    echo "Need to set environment var $VARIABLE" && exit 1;
fi

-z "string" is true if string is empty.

+x is a typo? You do not need that.

Working condition:

if [ -z "${!VARIABLE}" ]; then
    echo "Need to set environment var $VARIABLE" && exit 1;
else
    echo "${VARIABLE} was defined"
fi
6
  • Unfortunately I receive similar results with or without the + I've updated my question with the output of your recommendation. Commented Oct 18, 2017 at 12:59
  • 1
    @LessQuesar Notice that @V-Mark also switched the if statements. -z looks if the string is empty. If this is true then exit. You do it the other way round in your script. Commented Oct 18, 2017 at 13:42
  • @duenni You're right, the order i had was backwards. Commented Oct 18, 2017 at 14:22
  • You should put double-quotes around ${!VARIABLE} -- without them, you'll get syntax errors if the variable contains multiple words (or a wildcard that matches multiple files, or...). Commented Oct 21, 2017 at 19:44
  • 1
    True. I modified ${!VARIABLE} to "${!VARIABLE}" Commented Oct 23, 2017 at 19:18

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.