Changing a global variable in a bash script works perfectly. But when a pipe is used it stops working as expected.
This works:
pf_test1:
#! /bin/bash
echo "1) MyGlobal=${MyGlobal}"
source pf_test2
echo "2) MyGlobal=${MyGlobal}"
change_global
echo "3) MyGlobal=${MyGlobal}"
inc_global 2
echo "4) MyGlobal=${MyGlobal}"
pf_test2:
#! /bin/bash
MyGlobal=100
function change_global() {
MyGlobal=200
}
function inc_global() {
RC=$1
MyGlobal=$((MyGlobal + RC))
}
Output is:
$ ./pf_test1
1) MyGlobal=
2) MyGlobal=100
3) MyGlobal=200
4) MyGlobal=202
But changing the pf_test1 by adding a pipe, causes the the global variable not to be changed any more:
updated pf_test1
#! /bin/bash
echo "1) MyGlobal=${MyGlobal}"
source pf_test2
echo "2) MyGlobal=${MyGlobal}"
change_global | tee pf_ja.log
echo "3) MyGlobal=${MyGlobal}"
inc_global 2 | tee pf_ja.log
echo "4) MyGlobal=${MyGlobal}"
Output showing the issue
./pf_test1
1) MyGlobal=
2) MyGlobal=100
3) MyGlobal=100
4) MyGlobal=100
I don't understand why this fails. Any ideas?
And any solutions?
PS This is on Ubuntu
$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description: Ubuntu 22.04.3 LTS
Release: 22.04
Codename: jammy
Update: I changed the pf_test1 as shown in the comments:
echo "1) MyGlobal=${MyGlobal}"
source pf_test2
echo "2) MyGlobal=${MyGlobal}"
change_global > >(tee pf_ja.log)
echo "3) MyGlobal=${MyGlobal}"
inc_global 2 > >(tee pf_ja.log)
echo "4) MyGlobal=${MyGlobal}"
but I also added echo statements in pf_test2:
MyGlobal=100
function change_global() {
echo "in change_global"
MyGlobal=200
}
function inc_global() {
echo "in inc_global $1"
RC=$1
MyGlobal=$((MyGlobal + RC))
}
The output is:
$ ./pf_test1
1) MyGlobal=
2) MyGlobal=100
3) MyGlobal=200
4) MyGlobal=202
$ in change_global
in inc_global 2
The output from the echos are done after pf_test1 ends. And the content of pf_ja.log is just the last line:
in inc_global 2