Read a config file in BASH without using “source”

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

    Thanks SiegeX. I think the later updates you mentioned does not reflect in this URL.

    I had to edit the regex to remove the quotes to get it working. With quotes, array returned is empty.

    i=0
    while read line; do
      if [[ "$line" =~ ^[^#]*= ]]; then
        name[i]=${line%% =*}
        value[i]=${line##*= }
        ((i++))
      fi
     done < vars
    

    A still better version is .

    i=0
    while read line; do
    if [[ "$line" =~ ^[^#]*= ]]; then
            name[i]=`echo $line | cut -d'=' -f 1`
                value[i]=`echo $line | cut -d'=' -f 2`
            ((i++))
    fi
    done < vars
    

    The first version is seen to have issues if there is no space before and after "=" in the config file. Also if the value is missing, i see that the name and value are populated as same. The second version does not have any of these. In addition it trims out unwanted leading and trailing spaces.

    This version reads values that can have = within it. Earlier version splits at first occurance of =.

    i=0
    while read line; do
    if [[ "$line" =~ ^[^#]*= ]]; then
            name[i]=`echo $line | cut -d'=' -f 1`
                value[i]=`echo $line | cut -d'=' -f 2-`
            ((i++))
    fi
    done < vars
    

提交回复
热议问题