Linux Shell Script - Doubt about variable scope

Asked

Viewed 54 times

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

1 answer

0

I already understand what happens. In the first example, the two variables are visible within the pipe. However, by modifying the variables inside, the modifications are only valid there. That is, the same variables, seen outside the pipe, continue as they were declared at the beginning of the script. This is not a problem for the $i variable, as I no longer use it after the loop is finished. But in the case of the variable array_files, it is populated, but this will only take effect inside the loop. When I try to catch the variable again after finishing the loop, it remains blank, as stated at the beginning of the script. I hope this remark can be useful to someone.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.