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?
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!
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" )'
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