[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: issue with [[ -v A[\$k] ]]
From: |
Greg Wooledge |
Subject: |
Re: issue with [[ -v A[\$k] ]] |
Date: |
Sun, 21 May 2023 16:48:06 -0400 |
On Sun, May 21, 2023 at 10:35:03PM +0200, alex xmb ratchev wrote:
> q : what bash code to write to have random input as secure keys ?
1) I would avoid using the -v operator, period. I've seen nothing but
bug reports coming from people who try to use it. There's even a
BashPitfall for it <https://mywiki.wooledge.org/BashPitfalls#pf61>.
Your backslash workaround might be OK, in some versions of bash,
but I wouldn't trust it, especially given how many workarounds
were broken by bash 5.2.
Instead of using -v to test for existence of a key, use a non-empty
value. Then actually EXPAND the array element, and see if you get
a non-empty string.
hash[$key]=1
if [[ ${hash[$key]} ]]; then # BUT! See part 2.
echo "key exists"
else
echo "key does not exist"
fi
2) To allow arbitrary keys, including the empty string, use the "x hack".
hash[x$key]=1
if [[ ${hash[x$key]} ]]; then
echo "key exists"
else
echo "key does not exist"
fi
3) Don't use an associative array expansion inside an arithmetic context,
because of <https://mywiki.wooledge.org/BashPitfalls#pf62>. This may
not apply to your use of the associative array as a set, but I'll
just mention it here for posterity.
Part 1 means you can't use set -u. So don't use set -u. Simple!