I stumbled by accident on the following
bash
behaviour, which is for me kind of unexpected.
# The following works
$ declare bar=Hello # Line 1
$ declare -p bar # Line 2
declare -- bar="Hello"
$ foo=bar # Line 3
$ declare ${foo}=Bye # Line 4
$ declare -p bar # Line 5
declare -- bar="Bye"
# The following fails, though
$ declare -a array=( A B C ) # Line 6
$ declare -p array # Line 7
declare -a array=(="A" ="B" ="C")
$ foo=array # Line 8
$ declare -a ${foo}=(="A" ="XXX" ="C") # Line 9
bash: syntax error near unexpected token ('
# Quoting the assignment fixes the problem
$ declare -a "${foo}=(A YYY C)" # Line 10
$ declare -p array # Line 11
declare -a array=(="A" ="YYY" ="C")
Since shell expansion
1. Brace expansion
2.
* Tilde expansion
* Parameter and variable expansion
* Arithmetic expansion
* Process substitution
* Command substitution
3. Word splitting
4. Filename expansion
is performed on the command line after it has been split into tokens (followed by quote removal) but before the final command is executed, I would not have expected line 9 to fail.
**Which is the rationale behind it, that makes bash
not accept line 9?** Or, said differently, **what am I missing in the way line 9 is processed by bash
that makes it fail but makes line 10 succeed?**
In any case, quoting is not always going to straightforwardly work and it would require extra attention in case the array elements are strings with e.g. spaces.
Asked by Axel Krypton
(336 rep)
Mar 16, 2020, 09:46 AM
Last activity: Mar 16, 2020, 08:26 PM
Last activity: Mar 16, 2020, 08:26 PM