2015-11-18 6 views
1

У меня есть этот скрипт:Циклическая ссылка имя

#!/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 

Что это значит? Как это исправить?

+0

переименовать 'массив = (а "BC", "d")' в 'somethingelse = (а "Ьс" "d")' – amdixon

+0

@amdixon да, это помогает, но не было 'local -n array = $ 1' должно работать? – warvariuc

+1

Когда вы выполняете 'contains array value', первая строка функции становится' local -n array = array'. См. Круговую ссылку? – 4ae1e1

ответ

7

Давайте сосредоточимся на первой строке функции contains:

local -n array=$1 

Когда один выполняет

contains array value 

$1 установлен в array, поэтому команда local, после расширения, становится

local -n array=array 

, где круговая ссылка сразу очевидна.

Это известная проблема без идеального решения (см. "The problem with bash's name references" в BashFAQ/048). Я хотел бы предложить, что там предлагается:

[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.

Смежные вопросы