As an example consider the following bash script. There are two loops, the first one executes in background and the second one prints myvar
values:
#!/bin/bash
myvar=AAA
while true;
do
sleep 3
myvar=BBB
sleep 3
myvar=CCC
done &
while true;
do
echo "${myvar}"
sleep 1
done
The output I actually get:
AAA
AAA
AAA
...
The output I would like to get:
AAA
BBB
CCC
BBB
CCC
...
This is due to the &
creating a new subshell for the first while loop.
I'm pretty certain you'll need to use some kind of IPC to solve this. Using a pipe or a named pipe to implement a producer/consumer setup would be reasonable.
A rough example:
#!/bin/bash
myvar=AAA
while true;
do
sleep 3
myvar_piped=BBB
echo $myvar_piped # this goes to the pipe.
sleep 1
done | # this connects the two loops.
while true;
do
# if we consumed something (timeout=1) print it, else print our own variable.
if read -t 1 myvar_piped #
then
echo "${myvar_piped}"
else
echo "${myvar}"
fi
done
Outputs:
AAA
AAA
AAA
BBB
AAA
AAA
AAA
AAA
BBB
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