首页 > 解决方案 > Why is the assignment in a function ignored?

问题描述

Consider following code:

zzz=2

function f()
{
    zzz=4
}

$(f)
echo $zzz

Why is the assignment (zzz=4) ignored? I thought I knew what $( ) does - it takes everything written to stdout and pastes it verbatim in the place where it's used. But why would that affect assignments to a global variable?

标签: bashfunctionscopevariable-assignment

解决方案


你为什么在一个子shell中调用它?

zzz=2
f() { zzz=4; }
$(f)            # assigns COPY of zzz, then goes POOF
echo $zzz
f               # assigns to zzz
echo $zzz

通过在子外壳中运行它,您正在创建一个子环境,该环境获取分配的变量,然后蒸发。


推荐阅读