Read a config file in BASH without using “source”

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

    The following script iterates over each line in your input file (vars in my case) and does a pattern match against =. If the equal sign is found it will use Parameter Expansion to parse out the variable name from the value. It then stores each part in it's own array, name and value respectively.

    #!/bin/bash
    
    i=0
    while read line; do
      if [[ "$line" =~ ^[^#]*= ]]; then
        name[i]=${line%% =*}
        value[i]=${line#*= }
        ((i++))
      fi
    done < vars
    
    echo "total array elements: ${#name[@]}"
    echo "name[0]: ${name[0]}"
    echo "value[0]: ${value[0]}"
    echo "name[1]: ${name[1]}"
    echo "value[1]: ${value[1]}"
    echo "name array: ${name[@]}"
    echo "value array: ${value[@]}"
    

    Input

    $ cat vars
    sdf
    USER = username
    TARGET = arrows
    asdf
    as23
    

    Output

    $ ./varscript
    total array elements: 2
    name[0]: USER
    value[0]: username
    name[1]: TARGET
    value[1]: arrows
    name array: USER TARGET
    value array: username arrows
    

提交回复
热议问题