gpt4 book ai didi

bash - 通告名称引用

转载 作者:行者123 更新时间:2023-11-29 09:20:11 26 4
gpt4 key购买 nike

我有这个脚本:

#!/bin/bash

function contains() {
local -n array=$1
local value=$2
for item in "${array[@]}"; do
[ "$item" = "$value" ] && return 0
done
return 1
}

array=(a "b c" "d")
value="b c"

contains array value

运行它我得到这个错误:

***: line 6: warning: array: circular name reference

这是什么意思?如何解决这个问题?

最佳答案

让我们关注函数contains的第一行:

local -n array=$1

执行时

contains array value

$1 被设置为 array,所以 local 命令在展开后变成了

local -n array=array

循环引用显而易见。

这是一个没有完美解决方案的已知问题(参见 BashFAQ/048 中的 "The problem with bash's name references")。我会建议那里的建议:

[T]here is no safe name we can give to the name reference. If the caller's variable happens to have the same name, we're screwed.

...

Now, despite these shortcomings, the declare -n feature is a step in the right direction. But you must be careful to select a name that the caller won't use (which means you need some control over the caller, if only to say "don't use variables that begin with _my_pkg"), and you must reject unsafe inputs.

关于bash - 通告名称引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33775996/

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