linux - BASH: Global variables aren't updateable in a function only when that function is piped (simple example) -
linux - BASH: Global variables aren't updateable in a function only when that function is piped (simple example) -
this smells buggy, probably, can explain it:
the next script doesn't work, output 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, take off | cat
, 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
a pipe creates subshell. it's said in bash manual subshells cannot modify environment of 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
linux bash variables cat
Comments
Post a Comment