Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: Add value to associative array, while a key=>value already exists

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")
like image 459
am1 Avatar asked Jun 03 '16 14:06

am1


2 Answers

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"
like image 54
chepner Avatar answered Nov 15 '22 04:11

chepner


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")
like image 21
choroba Avatar answered Nov 15 '22 03:11

choroba