I have one file where at every line an array is defined.
Example:
file.txt
a=(1 2 3)
b=(4 5 6)
c=(7 8 9)
I have another file file1.txt where the variables are defined
a
b
c
in the script, I am sourcing the file source file.txt
the script is like
while read -r line
do
echo "${!line[*]}"
done < file1.txt
The output is 0.
Basically, I want to print the individual elements of array defined in file.txt.
source file.txt
How to do that?
sea
April 14, 2020, 2:03pm
2
Hi
You would have better chances with your code, if you would save lists (var="1 2 3")in the file.txt, rather than arrays.
In which case, your code would work just fine - as it is right now.
As a 2nd note, *
and @
behave differently for arrays.
Though, you'll get only the first value of an array shown, with this method.
Hope this helps
2 Likes
How to get all the values for array defined in each line?
Perhaps I'm misinterpreting your request but would this suffice?
. ./file.txt
echo "a[1] = ${a[1]} a[2] = ${a[2]} a[3] = ${a[3]}"
echo "b[1] = ${b[1]} b[2] = ${b[2]} b[3] = ${b[3]}"
echo "c[1] = ${c[1]} c[2] = ${c[2]} c[3] = ${c[3]}"
2 Likes
RudiC
April 14, 2020, 4:40pm
5
I'm afraid you'll have to deploy the dangerous and deprecated eval
like
while read -r line
do eval echo "\${!$line
[*]}: \${$line
[*]}"
done < file1.txt
0 1 2: 1 2 3
0 1 2: 4 5 6
0 1 2: 7 8 9
4 Likes
Hi,
I found one solution.
The space difference between individual elements in file.txt is the key.
while IFS=" " read -r line
do
for i in ${!line}
do
echo "$i"
done
done < "file1.txt"
Thanks everyone for the solutions.
1 Like