从 bash 脚本中的配置文件访问变量

从 bash 脚本中的配置文件访问变量

我在配置文件 apps.conf 中定义了以下内容:

PORT_INDEX=7

我在 bash 脚本中执行此文件,如下所示,然后显示变量的值PORT_INDEX

. apps.conf
echo $PORT_INDEX

但看起来它不起作用。如何从bash脚本中的配置文件访问该变量?

答案1

您的代码中有一个拼写错误。

配置文件中的变量已命名,PORT_INDEX但您试图显示PORT_IXDEX未定义的变量。

答案2

扩展自我在评论里发的链接...

这里的这个函数只会评估你要求的那些变量。

read_config () { # read_config file.cfg var_name1 var_name2
#
# This function will read key=value pairs from a configfile.
#
# After invoking 'readconfig somefile.cfg my_var',
# you can 'echo "$my_var"' in your script.
#
# ONLY those keys you give as args to the function will be evaluated.
# This is a safeguard against unexpected items in the file.
#
# ref: https://stackoverflow.com/a/20815951
#
# The config-file could look like this:
#-------------------------------------------------------------------------------
# This is my config-file
# ----------------------
# Everything that is not a key=value pair will be ignored. Including this line.
# DO NOT use comments after a key-value pair!
# They will be assigend to your key otherwise.
#
# singlequotes = 'are supported'
# doublequotes = "are supported"
# but          = they are optional
#
# this=works
#
# # key = value this will be ignored
#
#-------------------------------------------------------------------------------
  shopt -s extglob # needed the "one of these"-match below
  local configfile="${1?No configuration file given}"
  local keylist="${@:2}"    # positional parameters 2 and following

  if [[ ! -f "$configfile" ]] ; then
    >&2 echo "\"$configfile\" is not a file!"
    exit 1
  fi
  if [[ ! -r "$configfile" ]] ; then
    >&2 echo "\"$configfile\" is not readable!"
    exit 1
  fi

  keylist="${keylist// /|}" # this will generate a regex 'one of these'

  # lhs : "left hand side" : Everything left of the '='
  # rhs : "right hand side": Everything right of the '='
  #
  # "lhs" will hold the name of the key you want to read.
  # The value of "rhs" will be assigned to that key.
  while IFS='= ' read -r lhs rhs; do
    # IF lhs in keylist
    # AND rhs not empty
    if [[ "$lhs" =~ ^($keylist)$ ]] && [[ -n $rhs ]]; then
      rhs="${rhs%\"*}"     # Del opening string quotes
      rhs="${rhs#\"*}"     # Del closing string quotes
      rhs="${rhs%\'*}"     # Del opening string quotes
      rhs="${rhs#\'*}"     # Del closing string quotes
      eval $lhs=\"$rhs\"   # The magic happens here
    fi
  # tr used as a safeguard against dos line endings
  done <<< $( tr -d '\r' < $configfile )

  shopt -u extglob # Switching it back off after use
} # ----------  end of function read_config  ----------

相关内容