[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Organising conditions
From: |
hancooper |
Subject: |
Re: Organising conditions |
Date: |
Mon, 02 Aug 2021 18:17:43 +0000 |
‐‐‐‐‐‐‐ Original Message ‐‐‐‐‐‐‐
On Monday, August 2, 2021 5:46 PM, Greg Wooledge <greg@wooledge.org> wrote:
> 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.
That's correct. I am still unaware about how to call keyv though
Have done
declare -A aa=([a]="Joe" [b]="Peter" [c]="Sammy")
keyv ${aa[@]}
I get no output.
But then I do
echo "${!aa[@]}"
echo "${aa[@]}"
to get
a b c
Joe Peter Sammy
> 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.
- Re: Organising conditions, (continued)
- Re: Organising conditions, Leonid Isaev (ifax), 2021/08/02
- Re: Organising conditions, hancooper, 2021/08/02
- Re: Organising conditions, Greg Wooledge, 2021/08/02
- Re: Organising conditions, hancooper, 2021/08/02
- Re: Organising conditions, Greg Wooledge, 2021/08/02
- Re: Organising conditions, hancooper, 2021/08/02
- Re: Organising conditions, Greg Wooledge, 2021/08/02
- Re: Organising conditions, Leonid Isaev (ifax), 2021/08/02
- Re: Organising conditions, hancooper, 2021/08/02
- Re: Organising conditions, Greg Wooledge, 2021/08/02
- Re: Organising conditions,
hancooper <=
- Re: Organising conditions, Greg Wooledge, 2021/08/02
- Re: Organising conditions, hancooper, 2021/08/02
- Re: Organising conditions, Greg Wooledge, 2021/08/02
- Re: Organising conditions, hancooper, 2021/08/02