Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: How to retrieve a variable value inside a background while loop

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
...
like image 302
mt22 Avatar asked Dec 17 '22 02:12

mt22


1 Answers

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
like image 177
Eduardo Ivanec Avatar answered Mar 02 '23 00:03

Eduardo Ivanec