Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Circular name reference

Tags:

bash

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?

like image 917
warvariuc Avatar asked Nov 18 '15 09:11

warvariuc


1 Answers

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.

like image 169
4ae1e1 Avatar answered Oct 18 '22 10:10

4ae1e1