Bash read array from an external file

后端 未结 3 787
长情又很酷
长情又很酷 2020-12-04 02:32

I have setup a Bash menu script that also requires user input. These inputs are wrote (appended to) a text file named var.txt like so:

input[0]=\'192.0.0.1\'         


        
3条回答
  •  不知归路
    2020-12-04 03:10

    You can encapsulate your variable extraction in a function and take advantage of the fact that declare creates local variables when used inside a function. This technique reads the file each time the function is called.

    readvar () {
        # call like this: readvar filename variable
        while read -r line
        do
            # you could do some validation here
            declare "$line"
        done < "$1"
        echo ${!2}
    }
    

    Given a file called "data" containing:

    input[0]='192.0.0.1'
    input[1]='username'
    input[2]='example.com'
    input[3]='/home/newuser'
    foo=bar
    bar=baz
    

    You could do:

    $ a=$(readvar data input[1])
    $ echo "$a"
    username
    $ readvar data foo
    bar
    

    This will read an array and rename it:

    readarray () {
        # call like this: readarray filename arrayname newname
        # newname may be omitted and will default to the existing name
        while read -r line
        do
            declare "$line"
        done < "$1"
        local d=$(declare -p $2)
        echo ${d/#declare -a $2/declare -a ${3:-$2}};
    }
    

    Examples:

    $ eval $(readarray data input output)
    $ echo ${output[2]}
    example.com
    $ echo ${output[0]}
    192.0.0.1
    $ eval $(readarray data input)
    $ echo ${input[3]}
    /home/newuser
    

    Doing it this way, you would only need to make one call to the function and the entire array would be available instead of having to make individual queries.

提交回复
热议问题