bash - 在 Bash 中获取配置文件的最佳实践
问题描述
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) 脚本应该跳过注释和空格(例如,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 脚本,我知道我的方法是不完整的,可能不是最佳实践。谁能帮我?
解决方案
您不能source
在此处使用,因为您的示例配置不是有效
bash
代码。获取文件意味着按原样包含它 - 就像
#include
在 C 世界中一样。相反,请使用适当的
INI解析器,例如
https://github.com/rudimeier/bash_ini_parser。您的脚本可能如下所示:
#!/usr/bin/env sh
config=config
var1_default=0
var2_default=0
var3_default=0
password_default="default_password"
email_default="default@email.com"
source_variables () {
if [ ! -f "$config" ]
then
printf "No config found, creating default config\n" >&2
{
echo VAR1="$var1_default" >> "$config"
echo VAR2="$var2_default" >> "$config"
echo VAR3="$var3_default" >> "$config"
echo PASSWORD="$password_default" >> "$config"
echo EMAL="$email_default" >> "$config"
} >> "$config"
fi
. "$PWD"/read_ini.sh
read_ini "$config"
var1="${INI__VAR1:-${var1_default}}"
var2="${INI__VAR2:-${var2_default}}"
var3="${INI__VAR3:-${var3_default}}"
password="${INI__PASSWORD:-${password_default}}"
email="${INI__email:-${email_default}}"
}
source_variables
echo VAR1: "$var1"
echo VAR2: "$var2"
echo VAR3: "$var3"
echo PASSWORD: "$password"
echo EMAIL: "$email"
推荐阅读
- node.js - 使用 Node.JS 编辑 XML 文件
- python - 在不填充的情况下调整 numpy 数组的大小
- html - Keycloak 领域登录页面渲染问题
- r - 使用重叠包将时间转换为太阳时间时出错
- eclipse - AEM WKND 教程组件基础 eclipse 无法识别 jcr 属性
- c++11 - C++11调用虚成员函数
- javascript - Hotw 将片段的动态数据加载到 thymeleaf 项目中的另一个 HTML 页面
- python - SNMP pass_persist 似乎没有执行
- mysql - mysql中的USING()函数有什么用?
- spring - 禁用弹簧集成指标