【发布时间】:2019-01-07 01:52:13
【问题描述】:
source bash 中的配置文件并在脚本中导入其变量/内容的最佳方法是什么?
比方说,我有一个名为/path/index.conf 的配置文件,类似于:
VAR1=
VAR2 = 1
VAR3=A&C
#comment
PASSWORD=xxxx
EMAIL=abc@abc.com
我正在编写一个 shell 脚本,它将执行以下操作:
1) 如果配置文件不存在,则脚本将使用默认值创建配置文件。
2) 如果缺少任何变量的值,脚本会将这些特定变量替换为默认值。例如VAR1= 值缺失,应将其替换为VAR1=0
3) 脚本应该跳过 cmets 和空格(例如,VAR2 = 1 一些空格),并在任何行包含 $、% 和 & 字符时进行抱怨
这是我到目前为止所做的:
#!/bin/sh
#Check the config file
source_variables () {
source /path/index.conf
#TODO: if the file does not exist, create the file
#TODO: file exists, but missing some variables, fill them with default values
test -e /path/index.conf
if test "$VAR1" = "0" ; then
echo "VAR1 successfully replaced "
fi
#TODO: If any variable contains $,%, and & (for example VAR3). Flag it and return 1.
#import all the variables and declare them as local
local var_a = $VAR1
local var_b = $VAR2
# ...etc
return 0 #checking successful
}
我正在学习 bash 脚本,我知道我的方法不完整,可能不是最佳实践。谁能帮我?
【问题讨论】: