Single quote character not handled well in associative array index

Bug #1618224 reported by Jarno Suni
8
This bug affects 1 person
Affects Status Importance Assigned to Milestone
bash (Ubuntu)
New
Undecided
Unassigned

Bug Description

Say you have script named test.sh in current directory

#!/bin/bash
declare -A a
b="80's"
((++a[$b]))
((++a["$b"]))
[[ $((++a[$b])) ]] || true
[[ $((++a["$b"])) ]] || true
echo ${a["$b"]}
echo ${a[$b]}

It outputs

./test.sh: line 4: ((: ++a[80's]: bad array subscript (error token is "a[80's]")
./test.sh: line 5: ((: ++a[80's]: bad array subscript (error token is "a[80's]")
./test.sh: line 6: ++a[80's]: bad array subscript (error token is "a[80's]")
1
1

Expected output is

4
4

like it is when b is "80s". Note that only the incremention on line 7 of the script works.
This bug also happens by bash 4.3-7ubuntu1.5 (Trusty)

ProblemType: Bug
DistroRelease: Ubuntu 16.04
Package: bash 4.3-14ubuntu1.1
ProcVersionSignature: Ubuntu 4.4.0-31.50-generic 4.4.13
Uname: Linux 4.4.0-31-generic x86_64
NonfreeKernelModules: nvidia_uvm nvidia
ApportVersion: 2.20.1-0ubuntu2.1
Architecture: amd64
CurrentDesktop: XFCE
Date: Tue Aug 30 00:24:58 2016
EcryptfsInUse: Yes
InstallationDate: Installed on 2015-11-21 (282 days ago)
InstallationMedia: Xubuntu 15.10 "Wily Werewolf" - Release amd64 (20151021)
SourcePackage: bash
UpgradeStatus: Upgraded to xenial on 2016-06-24 (66 days ago)

Revision history for this message
Jarno Suni (jarnos) wrote :
Revision history for this message
Jarno Suni (jarnos) wrote :

This is reported upstream.

Revision history for this message
xhienne (xhienne) wrote :

Not a bug IMHO, but that may be open to debate. At least the observed behavior conforms to the bash manual which reads:
- ((expression)) is strictly equivalent to: let "expression"
- parameter expansion is performed _before_ the expression is evaluated

Therefore, ((++a[$b])) translates to let "++a[$b]" which translates to let "++a[80's]" which leads to an error.

The proper syntax would be (('++a[$b]')) which is admittedly quite counter-intuitive. This way '$b' is evaluated as a whole during the arithmetic evaluation.

Demonstration:
$ declare -A a
$ b="80's"
$ (('++a[$b]'))
$ printf '%s\n' "${!a[@]}" "${a[@]}"
80's
1
$ (('++a[$b]'))
$ printf '%s\n' "${!a[@]}" "${a[@]}"
80's
2

To post a comment you must log in.
This report contains Public information  
Everyone can see this information.

Other bug subscribers

Remote bug watches

Bug watches keep track of this bug in other bug trackers.