help-bash
[Top][All Lists]
Advanced

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

Re: Organising conditions


From: Greg Wooledge
Subject: Re: Organising conditions
Date: Mon, 2 Aug 2021 13:46:37 -0400

On Mon, Aug 02, 2021 at 05:30:29PM +0000, hancooper wrote:
> I want to write a bash function to display keys and values of an associative 
> array.

The easy way: declare -p myarray

> Have done as follows.  Is it simply a matter of using $1 and $2 for tho 
> associative
> array name and title?
> 
> keyv ()
> {
>   echo "$title"
>   for key in "${!aa[@]}"; do
>     echo "Key:   ${key}"
>     echo "Value: ${aa[$key]}"
>   done
> }

You want 'key' to be a local variable.  Otherwise, this looks pretty good,
for global variables 'title' and 'aa'.

But it sounds like you're actually asking how to pass the name of an
associative array to a function ("by reference").  This is easiest to
do with declare -n (a.k.a. local -n), which creates a name reference.

The bad news is that bash's name refs have a name collision issue that
is a pain in the ass to work around.

keyv() {
  local -n _keyv_array="$1"
  local _keyv_key
  for _keyv_key in "${!_keyv_array[@]}"; do
    printf 'Key:   %s\n' "$_keyv_key"
    printf 'Value: %s\n' "${_keyv_array[$_keyv_key]}"
  done
}

For more details, see <https://mywiki.wooledge.org/BashProgramming>.  Or
just use declare -p, if you don't need "pretty" output.



reply via email to

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