I have a bash script that uses filenames as keys in an associative array. Some of the filenames have quotes in them and I can't seem to find any way to unset them.
Here's an example replicating the problem from the terminal:
$ declare -A x
$ y="key with spaces"
$ z="key with spaces and ' quote"
$ x[$y]=5 # this works fine
$ x[$z]=44 # as does this
$ echo "${x[$y]}" "${x[$z]}" # no problems here
5 44
$ unset x["$y"] # works
$ unset x["$z"] # does not work
bash: unset: `x[key with spaces and ' quote]': not a valid identifier
$ echo "${x[$y]}" "${x[$z]}" # second key was not deleted
44
The file names processed in my script are arbitrary and need to work regardless of what characters they have in them (within reason, at least needs to work with printable characters.) The unset is used to clear a flag on files with certain properties.
How can I get bash to unset these particular keys when they might contain quote symbols?
Bash, however, includes the ability to create associative arrays, and it treats these arrays the same as any other array. An associative array lets you create lists of key and value pairs, instead of just numbered values. You can assign values to arbitrary keys: $ declare -A userdata.
Given two arrays arr1 and arr2 of size n. The task is to iterate both arrays in the foreach loop. Both arrays can combine into a single array using a foreach loop.
An associative array in bash is declared by using the declare -A command (How surprising, I know :D). The variable inside the brackets - [] will be the KEY and the value after the equal sign will be the VALUE.
To append element(s) to an array in Bash, use += operator. This operator takes array as left operand and the element(s) as right operand. The element(s) must be enclosed in parenthesis. We can specify one or more elements in the parenthesis to append to the given array.
I find this works for me:
unset 'x[$z]'
This works for other special characters:
$ y="key with spaces"
$ v="\$ ' \" @ # * & \`"
$ x[$y]=5
$ x[$v]=10
$ echo ${x[*]}
5 10
$ unset 'x[$v]'
$ echo ${x[*]}
5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With