gpt4 book ai didi

bash - 局部变量 `unset` 的奇怪行为

转载 作者:行者123 更新时间:2023-12-05 03:16:54 28 4
gpt4 key购买 nike

我无法解释 unset 的以下行为:

#!/bin/bash

my_unset() { unset "$@"; }

fn1() { local var; unset var; var=1; }
fn2() { local var; my_unset var; var=2; }

var=0

fn1; echo "$var"
fn2; echo "$var"
0
2

编辑:我希望结果为 1 2

它在 bash 3/4/5 上的行为是这样的,这是一个错误吗?


更新

这是另一个示例,显示使用 my_unset 不会使变量成为全局变量;它只从当前上下文中删除局部变量:

#!/bin/bash

my_unset() { unset "$@"; }

fn1() { local var; my_unset var; var=1; }
fn2() { local var; fn1; echo "[fn2] var=$var"; }

var=0
fn2
echo "[global] var=$var"
[fn2] var=1
[global] var=0

最佳答案

参见 Chet's answer回到 2012 年:

Back a number of years ago (16, to be exact), bash behaved like you expect. Between bash-1.14 and bash-2.0, I changed it in response to a number of bug reports that complained that a variable declared local in a function wasn't local when assigned a value in the function after being unset. Bash keeps aplaceholder in the function's variable context so subsequent references tothat unset variable don't traverse back through the call chain. Thisplaceholder affects functions called by the function unsetting the localvariable in the way you would expect dynamic scoping to work.

This only affects the current function, though: an unset issued fromfarther down the call chain, as you discovered, will unset the localvariable without creating a placeholder.

关于bash - 局部变量 `unset` 的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74409195/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com