Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash hashmap using quote as key

In Bash, I want to unset an entry of a hashmap. But I failed. Code is like below:

declare -A arr
arr["a'b"]=3
echo ${!arr[@]} ## output: a'b
key="a'b"
unset arr[$key] ## error: -bash: unset: `arr[a'b]': not a valid identifier

How can I unset this entry?

like image 640
ruanhao Avatar asked Jun 14 '16 15:06

ruanhao


Video Answer


2 Answers

Just use single quotes:

$ declare -A arr=(["a'b"]=3 [foo]=bar)
$ declare -p arr
declare -A arr='(["a'\''b"]="3" [foo]="bar" )'
$ key="a'b"
$ unset 'arr[$key]'
$ declare -p arr
declare -A arr='([foo]="bar" )'

Done!

like image 121
gniourf_gniourf Avatar answered Oct 10 '22 20:10

gniourf_gniourf


Tricky. You can do it by hand by escaping the "inner" single quote:

$ declare -A arr=(["a'b"]=3 [foo]=bar)
$ key="a'b"
$ unset "arr[$key]"
bash: unset: `arr[a'b]': not a valid identifier
$ unset "arr[a\'b]"
$ declare -p arr
declare -A arr='([foo]="bar" )'

But how to do it "programmatically"? Fortunately bash does have a mechanism to "escape" a string: printf "%q":

$ declare -A arr=(["a'b"]=3 [foo]=bar)
$ echo "$key"
a'b
$ printf "%q" "$key"
a\'b
$ unset "arr[$(printf "%q" "$key")]"
$ declare -p arr
declare -A arr='([foo]="bar" )'
like image 24
glenn jackman Avatar answered Oct 10 '22 21:10

glenn jackman