10

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")

2 Answers 2

18

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"
Sign up to request clarification or add additional context in comments.

Comments

4

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")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.