Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Bash变量未更新_Bash - Fatal编程技术网

Bash变量未更新

Bash变量未更新,bash,Bash,有人能给我解释一下为什么下面这个简单的例子不起作用吗 在本例中,“helper”函数包含一个不同的函数作为参数(“setV”和“getV”)。在“setV”函数中,变量的值被更新。尽管如此,“getV”函数中的值仍然是旧值。这是什么原因 vari="Oh no... I'm old." function init() { helper setV helper getV } function helper() { ($1) } function

有人能给我解释一下为什么下面这个简单的例子不起作用吗

在本例中,“helper”函数包含一个不同的函数作为参数(“setV”和“getV”)。在“setV”函数中,变量的值被更新。尽管如此,“getV”函数中的值仍然是旧值。这是什么原因

vari="Oh no... I'm old."

function init() {
    helper setV
    helper getV
}
 
function helper() {
    ($1)
}
 
function setV() {
    vari="Hey! I'm new!"
}
 
function getV() {
    echo $vari
}
 
init
($1)
中的参数导致在子shell中执行
$1
。这意味着当子shell退出时,任何环境/变量更改都将丢失

注意:

$ x=; setx() { x=Y; }; echo "1 x=$x"; (setx); echo "2 x=$x"; setx; echo "3 x=$x"
1 x=
2 x=
3 x=Y
如果希望变量更改继续存在,请不要将命令放在子shell中

文档 从
manbash

(list)
list
在子shell环境中执行(请参阅命令 执行环境(见下文)变量赋值和内置 影响shell环境的命令不会保持有效 命令完成后。返回状态为的退出状态
列表
。[重点补充]


只要去掉“()”谢谢。令人惊叹的!它起作用了。