【发布时间】:2016-03-15 18:29:36
【问题描述】:
我正在使用getopt 读取我的命令行参数,我正在使用. 读取配置文件:
test.sh:
#!/bin/bash
set -- `getopt C:a:b:c: "$@"`
C="default.cfg"
. $C
while [ $# -gt 0 ]; do
case "$1" in
-a) cfg1="$2"; shift;;
-b) cfg2="$2"; shift;;
-c) cfg3="$2"; shift;;
-C) C="$2"; #you'll see what this is for later
shift;;
--) shift;
break;;
-*) echo "invalid option";
exit 1;;
*) break;;
esac
shift
done
echo "cfg1 = $cfg1"
echo "cfg2 = $cfg2"
echo "cfg3 = $cfg3"
exit 0
default.cfg::
cfg1=hello
cfg2=there
cfg3=friend
这一切都按预期工作:
$ ./test.sh
cfg1 = hello
cfg2 = there
cfg3 = friend
$ ./test.sh -b optional
cfg1 = hello
cfg2 = optional
cfg3 = friend
这个问题是我希望以下列方式优先配置配置:
- 命令行中给出的选项
-
-C选项定义的配置文件中定义的选项 - 默认配置文件中定义的选项
如果我有这个:
test.cfg:
cfg1=custom_file_1
cfg2=custom_file_2
我想得到这个:
$ ./test.sh -b command_line -C test.cfg
cfg1 = custom_file_1
cfg2 = command_line
cfg3 = friend
我只是不知道如何加载默认配置文件,然后搜索-C的选项,然后加载自定义配置文件,覆盖默认值,然后再次搜索命令行参数并再次覆盖配置.我对 shell 脚本很陌生,所以如果我遗漏了一些明显的东西,请原谅我。
【问题讨论】: