我正在写一个读取.config文件的.sh文件。在这个.config文件(我无法编辑)中有一些变量。我想测试这些变量是否被定义为环境变量。
.config文件:
APPLICATION_PATH=/var/www/application
MONGO_DATA_PATH=/var/lib/mongodb
MYSQL_DATA_PATH=/var/lib/mysql
test.sh文件:
#!/bin/sh
if test -e ../my_folder/.config # Test if the .config file exists
then
cat ../my_folder/.config | while read line; do # Read the .config file line per line
env_var="${line%=*}" # Get the part before the '=' character of the current line (e.G. APPLICATION_PATH)
echo $env_var # Display the var (e.G. APPLICATION_PATH)
# Here, I would like to display the env var,
# e.G. like it would do using echo $APPLICATION_PATH
# but using the $env_var
( "echo \$$env_var" ) # Throw an error
done
fi
似乎( "echo \$$env_var" )
是不可能的。当我运行test.sh时,它会显示:
APPLICATION_PATH
./ test.sh:ligne 13:echo $ APPLICATION_PATH:not found
MONGO_DATA_PATH
./ test.sh:ligne 13:echo $ MONGO_DATA_PATH:not found
MYSQL_DATA_PATH
./ test.sh:ligne 13:echo $ MYSQL_DATA_PATH:not found
如何使用$env_var
测试是否存在环境变量?
答案 0 :(得分:0)
您可以使用此处提到的方法:Is it possible to build variable names from other variables in bash?
因此,您的代码将更改为以下内容:
#!/bin/sh
if test -e ../my_folder/.config
then
cat ../my_folder/.config | while read line; do
env_var="${line%=*}"
echo $env_var
eval "echo \$$env_var" # This works
done
fi
答案 1 :(得分:0)
如果您可以牺牲可移植性,则应使用间接参数扩展。可用性和确切语法因shell而异;这就是你在bash
中的表现方式:
while IFS== read -r varname _; do
printf '%s\n' "${!varname}"
done < ../my_folder/.config
如果你想牺牲安全,你会使用eval
:
while IFS== read -r varname _; do
eval "printf '%s\n' \$$varname"
done < ../my_folder/.config
牺牲简洁性超出了Stack Overflow的范围。但是,一种可能性是在使用expr
之前使用varname
确保eval
仅包含有效的shell标识符。
while IFS== read -r varname _; do
expr "$varname" : '[[:alpha:]_][[:alnum:]_]*' || continue
eval "printf '%s\n' \$$varname"
done < ../my_folder/.config