R
R
Ruslan Khoroshkevich2020-10-16 16:58:31
bash
Ruslan Khoroshkevich, 2020-10-16 16:58:31

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[@]}

which at the end of the loop returns an empty array
, while the line honestly renders the output at each iteration. It can be assumed that I'm messing around with the assignment to an array, but the following code
echo "$line"

imageList=()
line="line"
imageList+=("alias")
imageList+=($line)
imageList+=("alias")
imageList+=($line)
imageList+=("alias")
imageList+=($line)
echo ${#imageList[@]}


fulfills as well as conceived

who can clarify the situation

PS. peakle's answer helped. The script works. But there were questions why with for works and with while not

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Saboteur, 2020-10-17
@Zezst

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[@]}

O
Oleg Volkov, 2020-10-16
@voleg4u

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.

V
vreitech, 2020-10-16
@fzfx

> 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 question

Ask a Question

731 491 924 answers to any question