bash 什么时候在函数或循环中读取变量
bash when is a variable read during a fucntion or loop
在 bash 脚本中,让我们以下面的极端示例为例,其中 myFn()
的 call/start 在 $inVar -> $myvar
的回显发生之前 5 分钟。在函数启动和与 $myvar
交互之间的这段时间内,它被更新。
myvar=$(... //some json
alpha=hello )
myFn(){
local -n inVar=
//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
)
当$myvar
传递给myFn()
时,$myvar
实际读取时,
- 在
myFn
调用时间(当函数为 called/starts 时)
- 参考复制时间
inVar=
- 当
echo $inVar
发生时
这对于其他类型的流程是否相同,例如 while, if
等?
您将 inVar 设置为 nameref,因此直到变量在 echo
语句
中扩展后,该值才为人所知
然而
在您的方案中,myFn 是“非阻塞”的,这意味着您在后台启动它。在这种情况下,subshell 获取 myVar
的 current 值的副本——如果 myVar 随后更新,则该更新发生在 当前 shell,不是背景 shell.
演示:
$ bash -c '
fn() { local -n y=; sleep 2; echo "in background function, y=$y"; }
x=5
fn x &
x=10
wait
'
in background function, y=5
TL;DR: namerefs 和后台进程不能很好地混合。
在 bash 脚本中,让我们以下面的极端示例为例,其中 myFn()
的 call/start 在 $inVar -> $myvar
的回显发生之前 5 分钟。在函数启动和与 $myvar
交互之间的这段时间内,它被更新。
myvar=$(... //some json
alpha=hello )
myFn(){
local -n inVar=
//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
)
当$myvar
传递给myFn()
时,$myvar
实际读取时,
- 在
myFn
调用时间(当函数为 called/starts 时) - 参考复制时间
inVar=
- 当
echo $inVar
发生时
这对于其他类型的流程是否相同,例如 while, if
等?
您将 inVar 设置为 nameref,因此直到变量在 echo
语句
然而
在您的方案中,myFn 是“非阻塞”的,这意味着您在后台启动它。在这种情况下,subshell 获取 myVar
的 current 值的副本——如果 myVar 随后更新,则该更新发生在 当前 shell,不是背景 shell.
演示:
$ bash -c '
fn() { local -n y=; sleep 2; echo "in background function, y=$y"; }
x=5
fn x &
x=10
wait
'
in background function, y=5
TL;DR: namerefs 和后台进程不能很好地混合。