help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Help-bash] Does declare -n support (associative) arrays?


From: Peng Yu
Subject: [Help-bash] Does declare -n support (associative) arrays?
Date: Wed, 12 Dec 2018 22:43:03 -0600

Hi,

The manpage says the following.

declare [-aAfFgilnrtux] [-p] [name[=value] ...]
             -n     Give each name the nameref attribute, making it a
name  reference  to  another
                     variable.   That  other  variable  is defined by
the value of name.  All refer-
                     ences, assignments, and attribute modifications
to name, except those using  or
                     changing  the  -n attribute itself, are performed
on the variable referenced by
                     name's value.  *The nameref attribute cannot be
applied to array variables.*

I am not sure if I understand the last sentence correctly. It seems a
reference to an array can be assigned. What does the last sentence
mean? Thanks.

$ bash --version
GNU bash, version 4.4.23(1)-release (x86_64-apple-darwin17.5.0)
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
$ cat main.sh
#!/usr/bin/env bash
# vim: set noexpandtab tabstop=2:

set -v
function f {
    declare -n ref=$1
    [[ -v ref[a] ]]; echo $?
    [[ -v ref[c] ]]; echo $?
    [[ -v x[a] ]]; echo $?
    [[ -v x[c] ]]; echo $?
}

declare -A x=([a]=A [b]=B)
f x

function g {
    declare -n ref=$1
    declare x
    for x in "address@hidden"
    do
        echo "$x"
    done
}

declare -a x1=(a b)
g x1
$ ./main.sh
function f {
    declare -n ref=$1
    [[ -v ref[a] ]]; echo $?
    [[ -v ref[c] ]]; echo $?
    [[ -v x[a] ]]; echo $?
    [[ -v x[c] ]]; echo $?
}

declare -A x=([a]=A [b]=B)
f x
0
1
0
1

function g {
    declare -n ref=$1
    declare x
    for x in "address@hidden"
    do
        echo "$x"
    done
}

declare -a x1=(a b)
g x1
a
b


-- 
Regards,
Peng



reply via email to

[Prev in Thread] Current Thread [Next in Thread]