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

migrated from serverfault.com Nov 2 '17 at 14:30

This question came from our site for system and network administrators.

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
  • Unfortunately I receive similar results with or without the + I've updated my question with the output of your recommendation. – LessQuesar Oct 18 '17 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. – duenni Oct 18 '17 at 13:42
  • @duenni You're right, the order i had was backwards. – LessQuesar Oct 18 '17 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...). – Gordon Davisson Oct 21 '17 at 19:44
  • 1
    True. I modified ${!VARIABLE} to "${!VARIABLE}" – V-Mark Oct 23 '17 at 19:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.