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

Viewed 12954

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

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

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

Output:

func before set> OLD
func after set> NEW
final value> OLD

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

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

Output:

func before set> OLD
func after set> NEW
final value> NEW
1 Answers
Related