Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unseting a value in an associative bash array when the key contains a quote

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?

like image 284
codebeard Avatar asked Aug 26 '16 18:08

codebeard


People also ask

What is an associative array in bash?

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.

How do you iterate an associative array?

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.

What is the command to create an associative array in bash?

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.

How do I append to an array in bash?

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.


1 Answers

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
like image 86
lnyng Avatar answered Nov 15 '22 03:11

lnyng