Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 507
David Parks Avatar asked Jul 12 '11 10:07

David Parks


People also ask

Can bash function access global variable?

Global variablesThey are visible and valid anywhere in the bash script. You can even get its value from inside the function. If you declare a global variable within a function, you can get its value from outside the function.

Are global variables shared between forked processes?

Global variables are still global within its own process. So the answer is no, global variables are not shared between processes after a call to fork().

How do you set a global variable in bash?

The easiest way to set environment variables in Bash is to use the “export” keyword followed by the variable name, an equal sign and the value to be assigned to the environment variable.

How do you make a function variable refer to the global variable?

If you want to refer to a global variable in a function, you can use the global keyword to declare which variables are global.


1 Answers

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

like image 88
Rajish Avatar answered Nov 01 '22 23:11

Rajish