我有一个如下所示的配置文件:
$ cat .config
PARAM1 = avalue # a comment
PARAM2 = "many values" # another comment
# PARAM3=blabla
我写了一个函数来读取它:
get_from_config_file()
{
A=$(grep "$1" ${config_file} | grep -v "^#" | sed s'/^[[:space:]]*//g' | sed s'/#.*$//' | sed s'/^.*=[[:space:]]*//' | sed s'/[[:space:]]*$//' | sed s'/"//g')
echo "$A"
}
然后我可以从工作正常的配置文件中读取参数:
PARAM1=$(get_from_config_file "PARAM1")
PARAM2=$(get_from_config_file "PARAM2")
但是我想让它变得更好(我在这个配置文件中有很多参数)所以我希望能够获取我所有参数的值,然后在一个简单的 for 循环中分配给变量——在这里我遇到了麻烦:
for name in PARAM1 PARAM2
do
value=$(get_from_config_file "$name")
echo $name, $value
# How to assign here $value to a variable named PARAM1, PARAM2 which is contained in name ?
# Note that I do not want to use an array for this
# param[$name]="$value"
done
谢谢,
直接使用定义变量 declare
for name in PARAM1 PARAM2
do
declare -gx "$name"="$(get_from_config_file "$name")"
#echo $name, $value
# How to assign here $value to a variable named PARAM1, PARAM2 which is contained in name ?
# Note that I do not want to use an array for this
# param[$name]="$value"
done
echo PARAM1="$PARAM1"
echo PARAM2="$PARAM2"
运行此命令时declare -gx "$name"="$value"
,Bash 首先扩展变量name
和value
。然后执行命令,declare -gx PARAM1=foobar
declare options:
-g create global variables when used in a shell function; otherwise
ignored
-x to make NAMEs export
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句