Bash 通过变量名查找是否声明了所有环境变量

Bash 通过变量名查找是否声明了所有环境变量

我对下面的脚本有疑问。仅当没有使用该名称设置的变量时,它才应退出。

#!/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'

现在这个脚本总是在第一次检查时退出,MONGO_URL但是我知道这是变量集并且是一个字符串。

  • 支票会是什么样unset子?
  • 支票会是什么样unsetempty string

固定的 2 个问题,首先+if 语句末尾的符号是一个拼写错误。其次,我把 if 语句的顺序颠倒了。

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

答案1

问题是:

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

-z如果字符串为空,则“字符串”为真。

+x是错字吗?你不需要那个。

工作条件:

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

相关内容