設定ファイル 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 ----------