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
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.
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().
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.
If you want to refer to a global variable in a function, you can use the global keyword to declare which variables are global.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With