Home > database >  bash when is a variable read during a fucntion or loop
bash when is a variable read during a fucntion or loop

Time:05-09

In a bash script lets take the extreme below examples where the call/start of the myFn() is 5 minutes before the echo of $inVar -> $myvar happens. During this time between the function start and the interaction with the $myvar, it is updated.

myvar=$(... //some json 
                alpha=hello )
 myFn(){
   local -n inVar=$1     
  //wait for 5 mins .... :)
  echo $inVar
}

myFn "myvar"

if [ -z $var ]
then
  //wait 5 mins
  //but life goes on and this is non blocking 
  //so other parts of the script are running
  echo $myvar
fi

myvar=$(... // after 2 mins update alpha
                alpha=world
          )    

As the $myvar is passed to myFn(), when is $myvar actually read,

  1. at myFn call time (when the function is called/starts)
  2. at the reference copy time inVar=$1
  3. when the echo $inVar occurs

and is this the same for other types of processes such as while, if etc?

CodePudding user response:

You're setting inVar as a nameref, so the value is not known until the variable is expanded at the echo statement

HOWEVER

In your scenario, myFn is "non blocking", meaning you launch it in the background. In this case, the subshell gets a copy of the current value of myVar -- if myVar gets updated subsequently, that update is happening in the current shell, not the background shell.

To demonstrate:

$ bash -c '
  fn() { local -n y=$1; sleep 2; echo "in background function, y=$y"; }
  x=5
  fn x &
  x=10
  wait
'
in background function, y=5

TL;DR: namerefs and background processes don't mix well.

  •  Tags:  
  • bash
  • Related