Changing a global variable inside a function when using "tee"?

I would like to change the value of a global variable. It works perfect when I execute the function normally. But this is not when I perform it with a tee. I need a tee to have both an output on the screen and in the file.

Why does the tee cause this behavior? Is there a way to change a global variable inside a function using Tee?

FCT_main() { MY_VAR=2 } MY_VAR=1 echo "MY_VAR=$MY_VAR" # -> print 1. FCT_main | tee file.out echo "MY_VAR=$MY_VAR" # -> print 1, but I expect 2 ! echo "\n" echo "MY_VAR=$MY_VAR" # -> print 1. FCT_main echo "MY_VAR=$MY_VAR" # -> print 2 as expected. 
+4
source share
2 answers

The problem is not tee . It is with a pipe. Each command in the pipe is executed in separate subshells.

Thus, any changes made to variables in functions are not reflected.

You can perform the following process substitution, but still it is not equivalent to the pipeline.

 FCT_main > >( tee file.out ) 

Note Process change only works with some shells. This code was found while working with the bash shell.

Whole code

 FCT_main() { MY_VAR=2 } MY_VAR=1 echo "MY_VAR=$MY_VAR" # -> print 1. FCT_main > >( tee file.out ) echo "MY_VAR=$MY_VAR" # -> print 1, but I expect 2 ! echo "\n" echo "MY_VAR=$MY_VAR" # -> print 1. FCT_main echo "MY_VAR=$MY_VAR" # -> print 2 as expected. 
+4
source

The same problem occurs in the following snippet:

 i=0 cat $file | while read line; do i=$(($i + 1)) done 

i will be 0 at the end of the loop.

 i=0 while read line; do i=$(($i + 1)) done < $file 

will work. The problem is that while is executed in a subshell (and therefore cat , for that matter) when used in a string, but not when redirecting stdin.

If you publish the actual code, we can help you develop a solution for your specific fragment.

0
source

Source: https://habr.com/ru/post/1491811/


All Articles