【问题标题】:Best practice to source a config file in Bash [duplicate]在 Bash 中获取配置文件的最佳实践 [重复]
【发布时间】: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 脚本,我知道我的方法不完整,可能不是最佳实践。谁能帮我?

【问题讨论】:

    标签: bash shell scripting


    【解决方案1】:

    您不能在此处使用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"
    

    【讨论】:

    • 请参阅How to Answer 中的“回答正确提出的问题”部分,特别是关于“之前已经多次提出并回答”的问题的要点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-06
    • 2013-02-21
    • 1970-01-01
    • 2012-03-09
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    相关资源
    最近更新 更多