CaptainVoronin CaptainVoronin - 2 months ago 13
Linux Question

Bash. Variable visibility and lifetime

I'm not experienced in bash and I've met a case that makes me perplexed. It's an example of such a case:

f1()
{
ar+=(1)
ar+=(3)
ar+=(2)
var="var value"
echo "0"
}

f2()
{

res=$(f1)
echo -------point 1--------
for i in ${ar[@]}; do
echo "El $i"
done
echo $var

echo -------point 2--------
f1>/dev/null
for i in ${ar[@]}; do
echo "El $i"
done
echo $var
}

f2


This script produces the following result:

-------point 1--------

-------point 2--------
El 1
El 3
El 2
var value


As you can see, the function f1 was called in two different ways and they give very different implications. In the first call the array and variable declared in f1 apparently destroyed.
In the second way the array and the variable were saved.

Does anybody can explain it to me or give me a link to appropriate manual?

Answer

When you do this:

res=$(f1)

You create a subshell, execute f1 inside the subshell and store the output to the variable $res. Any variables created within that subshell are lost after it has closed.

When you do this:

f1>/dev/null

You execute f1within the current shell. The variables that are created within the function are in the global scope, so can be accessed subsequently.

Comments