shell adding string to an array
12,122
Solution 1
Try this script:
declare -a properties
while read line
do
[[ "${line}" == *=* ]] && properties+=("$line")
done < "${FILE}"
for x in "${properties[@]}"
do
echo "the value is "$x"
done
Solution 2
As @twalberg mentions in this comment, the problem is not in the top loop, but in the bottom one:
for x in ${!properties[@]}
do
echo "the value is $properties[x]"
done
Array references always need braces { ... }
to expand properly.
For some reason each element in the array is the first line in the file.
Not so. The array is correctly populated, but you need to change the reference to the array from:
echo "the value is $properties[x]"
to:
echo "the value is ${properties[x]}"
Just a simple oversight.
Author by
Pectus Excavatum
Updated on June 08, 2022Comments
-
Pectus Excavatum almost 2 years
I am having some trouble adding a string to an array within a loop. For some reason it always adds the same line. Here is my code:
declare -a properties counter=0 while read line do if [[ ${line} == *=* ]] then properties[${counter}]=${line} (( counter=counter + 1 )) fi done < ${FILE} for x in ${!properties[@]} do echo "the value is $properties[x]" done
For some reason each element in the array is the first line in the file. I must be doing something wrong, just not sure what.
Any help would be greatly appreciated
-
mklement0 over 10 yearsYour recommendation for building the array is helpful, but please consider removing the rest of your answer: Not only is
(( counter=counter + 1 ))
correct (albeit clumsy), your alternatives are not an improvement and in the case ofcounter+=1
incorrect. If anything,(( ++counter ))
is the most concise form to use. -
mklement0 over 10 yearsGreat improvement, but please double-quote
${properties[@]}
to prevent unwanted shell expansions. -
Henk Langeveld over 10 yearsThis eliminates the bug in the original script by looping x over the expanded values, instead of the index. The changes in the upper loop detract from the original bug.
-
Henk Langeveld over 10 yearsCorrect, but does not answer the question. And then, you missed an option:
[[ ${line} == *=* ]] && properties[counter++]=${line}
:-) -
mklement0 over 10 years+1 for explaining the problem and showing me that variable references in array subscripts need not be
$
-prefixed ([x]
vs.[$x]
) (and that subscripts can even be arithmetic expressions).