bug-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: certain strings both legal and illegal as associative array keys


From: Greg Wooledge
Subject: Re: certain strings both legal and illegal as associative array keys
Date: Mon, 2 Mar 2015 08:56:43 -0500
User-agent: Mutt/1.4.2.3i

On Sun, Mar 01, 2015 at 12:05:53AM -0600, address@hidden wrote:
> A string is either legal or not legal as a key for an associative array.
> However, bash accepts certain keys in some contexts but not in other
> contexts, 

It's all about the quoting.

> #!/bin/bash
> 
> declare -A foo
> 
> foo[a]="one"
> foo["a'b"]="two"
> 
> echo "address@hidden"

That's all correct so far.  (Note, however, "declare -p foo" is much
better for showing you the contents of a variable, especially an array.)

> echo ${foo[a]}
> echo ${foo["a'b"]}

Missing quotes.  VERY bad.

imadev:~$ echo "${foo[a]}"
one
imadev:~$ echo "${foo["a'b"]}"
two

> unset foo[a]
> unset foo["a'b"]

Again, missing quotes.  If you have a file named "fooa" in the current
working directory, the first one expands to "unset fooa".  You don't want
that.

imadev:~$ unset "foo[a]"

Now, the second one is MUCH harder.  Your best bet is to store the
index in a variable instead of trying to deal with multiple levels
of quoting in the same argument.

imadev:~$ i="a'b"
imadev:~$ unset 'foo[$i]'
imadev:~$ declare -p foo
declare -A foo='()'



reply via email to

[Prev in Thread] Current Thread [Next in Thread]