I have an array in my script which I want to use it in for, like this:
for j in "${list[@]}"
do
func $j
done
In function func, sometimes another member will add to the list array, but the for iterates as many time as it was initiated(before the for started)
I want "for" to iterate based on the updated array content
some lines of that function:
if [ $s1 -gt 0 ]
then
(( k = $k +1 ))
list[$k]=$id2
fi
As Eric Renouf said, modifying the list you're working on can be tricky. As long as you're only appending new elements (to the end of the list), and just want those new elements included in the iteration, you can use something like this:
for ((i=0; i<${#list[@]}; i++)); do
#...
if (( s1 > 0 )); then
list+=( "$id2" )
fi
done
Since the length of the list ( ${#list[@]}
) is recalculated every time around, the loop will include new elements. Also, the +=( )
syntax guarantees you're always strictly appending.
It appears that k
is the index of the last element, meaning your function only appends items to the end of the list. It seems the best option is to iterate while a separate counter is less than k
.
i=0
while (( i < k )); do
j=${list[i]}
func "$j"
((i++))
done
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.