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.