novacik
novacik

Reputation: 1507

Assign associative array value only if empty in bash

Have associative array

OPTIONS[a]="a-value"

have another array id and need set a value from OPTIONS only when some value is NOT set, so something like

id[KEY1]=${id[KEY1]:-OPTIONS[a]}

but this not works.

How to use the bash's :- "variable substitution" with associative arrays?

Upvotes: 2

Views: 303

Answers (1)

Manny D
Manny D

Reputation: 20724

You were pretty close. This works for me:

$ OPTIONS[a]="a-value"
$ id[KEY1]="b"
$ id[KEY1]=${id[KEY1]:-${OPTIONS[a]}}
$ echo ${id[KEY1]}
b
$ unset id
$ id[KEY1]=${id[KEY1]:-${OPTIONS[a]}}
$ echo ${id[KEY1]}
a-value

Upvotes: 3

Related Questions