Read a config file in BASH without using “source”

后端 未结 4 1974
南方客
南方客 2021-02-01 07:45

I\'m attempting to read a config file that is formatted as follows:

USER = username
TARGET = arrows

I realize that if I got rid of the spaces,

4条回答
  •  长情又很酷
    2021-02-01 08:10

    I have a script which only takes a very limited number of settings, and processes them one at a time, so I've adapted SiegeX's answer to whitelist the settings I care about and act on them as it comes to them.

    I've also removed the requirement for spaces around the = in favour of ignoring any that exist using the trim function from another answer.

    function trim()
    {
        local var=$1;
        var="${var#"${var%%[![:space:]]*}"}";   # remove leading whitespace characters
        var="${var%"${var##*[![:space:]]}"}";   # remove trailing whitespace characters
        echo -n "$var";
    }
    
    while read line; do
        if [[ "$line" =~ ^[^#]*= ]]; then
            setting_name=$(trim "${line%%=*}");
            setting_value=$(trim "${line#*=}");
    
            case "$setting_name" in
                max_foos)
                    prune_foos $setting_value;
                ;;
                max_bars)
                    prune_bars $setting_value;
                ;;
                *)
                    echo "Unrecognised setting: $setting_name";
                ;;
            esac;
        fi
    done <"$config_file";
    

提交回复
热议问题