You can encapsulate the extraction of a variable in a function and take advantage of the fact that declare creates local variables when used inside a function. This method reads a file every time a 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} }
For a file named "data" containing:
input[0]='192.0.0.1' input[1]='username' input[2]='example.com' input[3]='/home/newuser' foo=bar bar=baz
You can do:
$ a=$(readvar data input[1]) $ echo "$a" username $ readvar data foo bar
This will read the 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
By doing this this way, you will only need to make one function call, and the entire array will be available, and will not make separate requests.
source share