Bash Parse Arrays From Config File

前端 未结 4 1854
孤独总比滥情好
孤独总比滥情好 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 13:12

    You can declare array in bash scripts with

    declare -a =(value1 value2 value 3)

    Then you can use them like this

    echo ${[index]}

    Edit:

    Ok, to construct arrays from config file. I would recommend to have a different file for each array you would like to create.

    So here are the steps

    1.config file (create a file and place your values in it)

    100
    200
    300
    

    2.script file (read values from file and prepare an array)

        array=()
    
        #setup array
        while IFS=$'\n' read -a config
        do
          array+=(${config})
        done < file_name
    
        #access values
        echo ${array[0]}
        echo ${array[1]}
    

    IFS denotes the delimiter
    -a specifies the array name you want to extract to, so that you can access them inside the while loop.

提交回复
热议问题