简体   繁体   中英

Bash: How to check if dynamic env variable is set?

I'm writing a script where I want to dynamically create an environment variable name, and check if it has been set.

#!/bin/bash

#######################################
# Builds options string
# Globals:
#   JVM_OPTS_DIR
# Arguments:
#   1. Options env variable name
#   2. File containing options defaults
# Returns:
#   Options
#######################################
function buildOpts() {
  declare -n opts=$1
  declare -n excludeOpts="EXCLUDE_$1"
  local -r optsFile=$2
  local x=
  if [ -z ${excludeOpts+x} ]; then
    while read -r o; do
      if [ -n "${o// }" ]; then
        x+=" $o"
      fi
    done <"$JVM_OPTS_DIR/$optsFile"
  fi
  if [ -n "$opts" ]; then
    for o in $opts; do
      x+=" $o"
    done
  fi
  printf '%s' "$x"
}

# https://docs.oracle.com/javase/8/docs/technotes/tools/unix/java.html

# Standard options
stdOpts=$(buildOpts STD_OPTS std.opts)

...

javaCmd="java $stdOpts $nonStdOpts $advRtOpts $advCompOpts $advServOpts $advGcOpts -jar $APP_DIR/app.jar"

printf '%s' "$javaCmd"

# eval $javaCmd "$@"

The above script serves as a Docker entrypoint

docker build -t jdk . && docker run --rm -it jdk -e APP_NAME=test -e APP_LOG_DIR=test -e APP_DIR=test -e STD_OPTS='a b' -e EXCLUDE_STD_OPTS=true

However, I don't see a and b included in the javaCmd , neither do I see the EXCLUDE working. Basically, none of the if conditions in function buildOpts are working.

I'm a backend programmer, and not a Bash wizard. Help.

You need to put the envs flags before the image name.

Syntax of docker run is:

docker run [OPTIONS] IMAGE[:TAG|@DIGEST] [COMMAND] [ARG...]

Anything after the image name will be treated as [COMMAND][ARG...]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM