Read a config file in BASH without using “source”

后端 未结 4 1975
南方客
南方客 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:07

    First, USER is a shell environment variable, so it might be better if you used something else. Using lowercase or mixed case variable names is a way to avoid name collisions.

    #!/bin/bash
    configfile="/path/to/file"
    shopt -s extglob
    while IFS='= ' read lhs rhs
    do
        if [[ $lhs != *( )#* ]]
        then
            # you can test for variables to accept or other conditions here
            declare $lhs=$rhs
        fi
    done < "$configfile"
    

    This sets the vars in your file to the value associated with it.

    echo "Username: $USER, Target: $TARGET"
    

    would output

    Username: username, Target: arrows

    Another way to do this using keys and values is with an associative array:

    Add this line before the while loop:

    declare -A settings
    

    Remove the declare line inside the while loop and replace it with:

        settings[$lhs]=$rhs
    

    Then:

    # set keys
    user=USER
    target=TARGET
    # access values
    echo "Username: ${settings[$user]}, Target: ${settings[$target]}"
    

    would output

    Username: username, Target: arrows

提交回复
热议问题