get updated variable value from subshell

70 Views Asked by At

I hava a main shell, during its running, I need to call a function (update_bk) in the background. the purpose of this function is to update a variable (VarA) which will be used by main shell later. I know if I call update_bk function in background, it would be run as subshell, so that the update to the value of VarA by update_bk can not be seen from main shell. therefore, I use mkpipo to solve the problem in update_bk function.

the update_bk function is

update_bk(){

    local VarB
    
    mkfifo ${update_bg_fifo}
    
    until [[ Condition  ]]
    do
        VarB=$(otherFunction)   
        sleep 5
    done
    
    echo ${VarB} > ${update_bg_fifo} && rm ${update_bg_fifo}

}

the main bash shell is

Until [condition]
do
[condition 1] to check if ${update_bg_fifo} is ready, and cat it to the VarA
some thing job2
[condition 3] && [ ! -P ${update_bg_fifo} ] to do call (update_bk) $   (when contion3 is true and no existing update_bk is running)
done

My quesition is how to code the [condition 1] in main shell, to check if ${update_bg_fifo} is ready to cat. I am now using [-p ${update_bg_fifo}] as the condition ,but cat ${update_bg_fifo} is keep wating update_bk() finishes to write ${update_bg_fifo}.

1

There are 1 best solutions below

3
alecxs On

you can use stdout instead fifo. call the function and write output into variable

update_bk(){
  local VarB
  ...
  echo "$VarB"
}

update_bg=$(update_bk)
echo "$update_bg"