I have this script:
#!/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
Running it I get this error:
***: line 6: warning: array: circular name reference
What does this mean? How to fix this?
Let's focus on the first line of the function contains
:
local -n array=$1
When one executes
contains array value
$1
is set to array
, so the local
command, after expansions, becomes
local -n array=array
where a circular reference is immediately obvious.
This is a known issue without a perfect solution (see "The problem with bash's name references" in BashFAQ/048). I would suggest what's suggested there:
[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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With