help-bash
[Top][All Lists]
Advanced

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

Re: Bash-5.2 Release available


From: Corey Hickey
Subject: Re: Bash-5.2 Release available
Date: Fri, 28 Oct 2022 19:32:39 -0700
User-agent: Mozilla/5.0 (X11; Linux x86_64; rv:102.0) Gecko/20100101 Thunderbird/102.3.1

On 2022-10-28 18:55, Greg Wooledge wrote:
On Fri, Oct 28, 2022 at 06:22:22PM -0700, Corey Hickey wrote:
I'm using '@' for the variable as a deliberately pathological value.
With bash 5.2 defaults, I can't find a way to make this work. Keeping
the subscript variable escaped results in an evaluation to an undefined
key (apparently):

$ ./bash -c 'declare -A assoc ; var=@ ; assoc[$var]=1 ; echo "$((1 + 
assoc[\$var]))"'
1

The [\$key] workaround that works in previous versions of bash does not
work in 5.2.

https://mywiki.wooledge.org/BashPitfalls#pf62

   As of bash 5.2, the only safe, working way to modify an element of an
   associative array in a calculation is to make a temporary copy of the
   value in a regular (string) variable.

   tmp=${hash[$key]}
   ((tmp++))              # Safe.
   hash[$key]=$tmp

   # Or:
   tmp=${hash[$key]}
   hash[$key]=$((tmp+1))  # Safe.

I believe you're hitting the same issue here, even though you're only
trying to retrieve an associative array element in a math context,
rather than trying to modify one.

Yes, that does seem like the same thing. Thanks for confirming that, and thanks for your site in general (which taught me some of how little I knew about shell scripting, despite using it for many years).

Is the current behavior of bash 5.2 the intended way forward or is it an unintentional regression?

The workaround of a temporary variable isn't really that bad, if it's the best and safest method.

Thanks,
Corey



reply via email to

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