Bash: how to get the value of a variable inside the background during a loop

As an example, consider the following bash script. There are two loops, the first runs in the background, and the second 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 

In fact, I get:

 AAA AAA AAA ... 

The result that I would like to get:

 AAA BBB CCC BBB CCC ... 
+4
source share
2 answers

This is because & creates a new subshell for the first while loop.

I am sure that you will need to use some kind of IPC to solve this problem. Using a pipe or named pipe to implement producer / consumer configuration would be reasonable.

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 
+7
source

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).

+4
source

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


All Articles