Reputation: 4922
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?
Upvotes: 6
Views: 298
Reputation: 46833
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!
Upvotes: 5
Reputation: 246877
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" )'
Upvotes: 4