[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Issue with 'key' for associative arrays
From: |
Greg Wooledge |
Subject: |
Re: Issue with 'key' for associative arrays |
Date: |
Wed, 25 Nov 2020 09:56:19 -0500 |
User-agent: |
Mutt/1.10.1 (2018-07-13) |
On Wed, Nov 25, 2020 at 02:48:44PM +0100, Frans de Boer wrote:
> Addressing associative arrays with an array statement - like echo
> ${k["${a[x]}"] does not work.
That seems to work for me, after I fix your quoting. Using your example
variables:
unicorn:~$ declare -A k
unicorn:~$ declare -a a
unicorn:~$ sString="devel packager's guide"
unicorn:~$ i=2
unicorn:~$ k["$sString"]=$i
unicorn:~$ a[$i]=$sString
unicorn:~$ echo "${k[${a[i]}]}"
2
> Next a script to clarify my point:
> ! /bin/bash
This shebang is wrong.
> unset -v 'k["${a[$i]}"]' # does not work
So, it's actually "unset -v" that doesn't work, not echo.
> sTemp=${a[$i]}
> unset -v 'k["$sTemp"]' # does work
Yeah, I can easily believe that there are bugs or misfeatures hiding
in unset -v. Personally, I'd avoid it entirely.
If you're using unset -v so that you can do existence testing ("make a
decision based on whether my associative array contains this key or not"),
then you can change that to a simple length test on the value. Use a
non-empty string as the value. Then your existence tests becomes
something like:
if [[ ${hash[$key]} ]]; then
echo "key exists"
fi
If you want to remove a key, just assign an empty string as the value,
rather than trying to use unset -v.
Yes, that's just a workaround to something that might very well be a bug.
You can either wait for a bug fix, and then realize that you still can't
actually USE unset -v in any of your scripts for the next 5-10 years, until
everyone in your target audience is on the fixed version of bash... or
you can use the workaround.
Yes, this doesn't work if you use set -u. So don't use set -u.