How can i add a value to an existing key within an associative array?
declare -A DATA
DATA=([foo]="bar" [foo2]="bar2" [foo3]="bar3")
Should be something like
DATA=([foo]="bar text" [foo2]="bar" [foo3]="bar")
You can use +=
.
DATA[foo]+=" test"
This will add foo
as a key if it doesn't already exist; if that's a problem, be sure to verify that foo
is in fact a key first.
# bash 4.3 or later
[[ -v DATA[foo] ]] && DATA[foo]+=" test"
# A little messier in 4.2 or earlier; here's one way
( : ${DATA[foo]:?not set} ) 2> /dev/null && DATA[foo]+=" test"
You can use the old value on the right hand side of the assignment.
#!/bin/bash
declare -A DATA
DATA=([foo]="bar" [foo2]="bar2" [foo3]="bar3")
DATA[foo]=${DATA[foo]}' text'
DATA[foo2]=${DATA[foo2]:0:-1}
DATA[foo3]=${DATA[foo3]:0:-1}
declare -p DATA
# DATA=([foo]="bar text" [foo2]="bar" [foo3]="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