Linux – BASH: Global variables aren’t updateable in a function only when that function is piped (simple example)

bash, cat, linux, variables

This smells buggy, but probably, someone can explain it:

The following script doesn't work, the output is below:

#!/bin/bashGLOBAL_VAR="OLD"myfunc() {        echo "func before set> $GLOBAL_VAR"        GLOBAL_VAR="NEW"        echo "func after set> $GLOBAL_VAR"}myfunc | catecho "final value> $GLOBAL_VAR"

Output:

func before set> OLDfunc after set> NEWfinal value> OLD

Now, just take off the | cat and it works!

#!/bin/bashGLOBAL_VAR="OLD"myfunc() {        echo "func before set> $GLOBAL_VAR"        GLOBAL_VAR="NEW"        echo "func after set> $GLOBAL_VAR"}myfuncecho "final value> $GLOBAL_VAR"

Output:

func before set> OLDfunc after set> NEWfinal value> NEW

Best Solution

A pipe creates a subshell. It's said in the bash manual that subshells cannot modify the environment of their parents. See these links:

http://www.gnu.org/software/bash/manual/bashref.html#Pipelines

http://wiki.bash-hackers.org/scripting/processtree#actions_that_create_a_subshell