linux - Bash. Variable visibility and lifetime -


i'm not experienced in bash , i've met case makes me perplexed. it's example of such case:

f1() {   ar+=(1)   ar+=(3)   ar+=(2)   var="var value"   echo "0" }  f2() {     res=$(f1)    echo -------point 1--------    in ${ar[@]};        echo "el $i"    done    echo $var     echo -------point 2--------    f1>/dev/null    in ${ar[@]};        echo "el $i"    done    echo $var }  f2 

this script produces following result:

-------point 1--------  -------point 2-------- el 1 el 3 el 2 var value 

as can see, function f1 called in 2 different ways , give different implications. in first call array , variable declared in f1 apparently destroyed. in second way array , variable saved.

does can explain me or give me link appropriate manual?

when this:

res=$(f1) 

you create subshell, execute f1 inside subshell , store output variable $res. variables created within subshell lost after has closed.

when this:

f1>/dev/null 

you execute f1within current shell. variables created within function in global scope, can accessed subsequently.


Comments

Popular posts from this blog

java - Jasper subreport showing only one entry from the JSON data source when embedded in the Title band -

serialization - Convert Any type in scala to Array[Byte] and back -

SonarQube Plugin for Jenkins does not find SonarQube Scanner executable -