I am trying to use a global variable inside two different functions, kind of a shared variable.
Program 1:
#!/bin/bash
glob="1"
func1(){
echo "start1: $glob"
((glob++))
}
func2(){
echo "start2: $glob"
}
func1
func2
The output is :
start1: 1
start2: 2
This is fine and expected.. Now if i put them in a loop, and send one of the function to background...
#!/bin/bash
glob="1"
func1(){
echo "start1 :$glob"
while :; do
((glob++))
echo "Incremneter: $glob"
sleep 1
done
}
func2(){
echo "start2: $glob"
while :; do
echo "Receiver $glob "
sleep 1
done
}
func1 &
func2
output:
Incremneter: 3
Receiver 1
Incremneter: 4
Receiver 1
Incremneter: 5
Receiver 1
Incremneter: 6
Receiver 1
Incremneter: 7
Receiver 1
Incremneter: 8
Receiver 1
Incremneter: 9
Receiver 1
Incremneter: 10
and goes on..
The output is such that both the functions are keeping their own copy of the variable "glob". Is this due to the fact that one process is working in the background? Is there a way out, to synchronize the copy of "glob" in both functions.