Bash:将值添加到关联数组,而键=> 值已存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37617297/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bash: Add value to associative array, while a key=>value already exists
提问by am1
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")
回答by chepner
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.
foo
如果它不存在,这将添加为一个键;如果这是一个问题,请务必先验证它foo
实际上是一个密钥。
# 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"
回答by choroba
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")