首页 > 解决方案 > 在 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 脚本,我知道我的方法是不完整的,可能不是最佳实践。谁能帮我?

标签: bashshellscripting

解决方案


您不能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"

推荐阅读