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

11,136

Solution 1

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"

Solution 2

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")
Share:
11,136

Related videos on Youtube

am1
Author by

am1

Updated on June 04, 2022

Comments

  • am1
    am1 almost 2 years

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