Essentially, you can do nothing to read the variable directly in the parent shell.
The first loop starts in a sub-shell due to & ; the memory of the subnets is completely independent of the main memory of the shell, and there is no way (not delivering terrible things, such as running a debugger in a sub-shell) to access child memory from the parent shell.
If you can modify the sub-shell process to write its variable value each time, the parent can detect this. Alternatively, if a sub-shell writes a variable to a file with a known name every time it changes a variable, you can read the file as often as you want in the parent:
#!/bin/bash tmp=$(mktemp) trap "rm -f $tmp; exit 1" 0 1 2 3 13 15 myvar=AAA echo $myvar > $tmp while true; do sleep 3 myvar=BBB echo $myvar > $tmp sleep 3 myvar=CCC echo $myvar > $tmp done & while cat $tmp do sleep 1 done rm -f $tmp trap 0
The trap ensures that the temporary file will be deleted in most cases (signals HUP, INT, QUIT, PIPE and TERM).
source share