-2
Num script shell, I want to make an array containing the files of a certain folder.
I tried so:
declare -a array_arquivos
i=0
ls -1 /caminho/minha_pasta | while read file; do
array_arquivos[$i]="$file"
((i++))
done
But it doesn’t work because the array array_arquivos
created at the beginning of script is not visible there inside the pipe, as it creates a new subshell. With this the array_arquivos
is not populated. But, this way it worked:
declare -a array_arquivos
i=0
while read file; do
array_arquivos[$i]="$file"
((i++))
done <<< $(ls -1 /caminho/minhapasta)
That is, instead of using pipe, I sent the result of the LS to my loop through the operator <<<
. That means problem solved.
However, in the first example that did not work, I did not understand the following:
Why the variable array_arquivos
is not visible inside the pipe, but the variable $i
is visible, and the two variables were created together at the beginning of the script?
Just to improve for the friendly community. Doubt has to be summarized in the question title.
– Paulo Sérgio Duff