Bash Parse Arrays From Config File

前端 未结 4 1856
孤独总比滥情好
孤独总比滥情好 2021-02-06 12:28

I need to have an array for each \"section\" in the file containing:

[array0]
value1=asdf
value2=jkl

[array1]
value1=1234
value2=5678

I want t

4条回答
  •  北荒
    北荒 (楼主)
    2021-02-06 12:58

    One eval-free, 100% pure Bash possibility:

    #!/bin/bash
    
    die() {
       printf >&2 "%s\n" "$@"
       exit 1
    }
    
    aryname=''
    linenb=0
    while read line; do
       ((++linenb))
       if [[ $line =~ ^[[:space:]]*$ ]]; then
          continue
       elif [[ $line =~ ^\[([[:alpha:]][[:alnum:]]*)\]$ ]]; then
          aryname=${BASH_REMATCH[1]}
          declare -A $aryname
       elif [[ $line =~ ^([^=]+)=(.*)$ ]]; then
          [[ -n aryname ]] || die "*** Error line $linenb: no array name defined"
          printf -v ${aryname}["${BASH_REMATCH[1]}"] "%s" "${BASH_REMATCH[2]}"
       else
          die "*** Error line $linenb: $line"
       fi
    done
    

    Reads on standard input. If you want to read from a file, change the done by:

    done < "filename"
    

    Lines of the form

    space and funnŷ sÿmbòl=value that will have an equal sign: look = it's funny
    

    are allowed

提交回复
热议问题