Problem
Getting the result declare -pfor a valid Bash associative array in which the keys contain square brackets results in a bad array error .
Testing procedure
do:
$ declare -A array
$ key='var[0]'
$ array["$key"]=37
$ echo ${array["$key"]}
37
$ declare -p array > def.sh
$ cat def.sh
declare -A array='(["var[0]"]="37" )'
$ . def.sh
bash: [var[0]]=37: bad array subscript
In the code above, note:
- I can specify a key containing square brackets:
var[0] - Key quoted for setters and getters
- I can complete the assignment using this key
- I can get the value from an associative array using this key
- Usage
declare -pI can save this definition in a file:def.sh - An
def.sherror is thrown while searching for a file .
My environment
- Bash 4.2.46 (1) -release (x86_64-redhat-linux-gnu).
- CentOS 7.3.1611 (Core)
declare -p array > def.sh :
{
echo 'declare -A array'
for Key in "${!array[@]}"; do
EscapedKey="$(sed 's|"|\\"|g' <<<"$Key")"
echo "array[\"$EscapedKey\"]=${array["$Key"]}"
done
} > def.sh
def.sh. , , . , , , . - , , .
- shopt, set -o <option> - , , , ? , .