Answer the question
In order to leave comments, you need to log in
Why doesn't bash add a value to an array inside a loop?
There is a harmless code
imageList=()
ls -al | while read line
do
echo "$line"
imageList+=("alias")
imageList+=($line)
done
echo ${#imageList[@]}
echo "$line"
imageList=()
line="line"
imageList+=("alias")
imageList+=($line)
imageList+=("alias")
imageList+=($line)
imageList+=("alias")
imageList+=($line)
echo ${#imageList[@]}
Answer the question
In order to leave comments, you need to log in
ls -al | while read line
In this construction, you use the pipe "|" you call a subprocess, inside which the whole while loop is spinning, and at the end of this process, the variables defined inside it die with it.
You can change the redirect to bypass the pipe:
imageList=()
while read line
do
echo "$line"
imageList+=("alias")
imageList+=($line)
done<<< $(ls -al)
echo ${#imageList[@]}
In bash, while is not a built-in function at all. It calls fork and so everything else is done in the sub-shell. It is unrealistic to make while work intelligibly.
> why it works with for and not with while
if in short - while in your case does not have access to variables outside the loop body.
when it comes to piping the output of one command to another, you should remember that this other one is running in a separate bash process with all the consequences like its environment.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question