Reference:
The first thing to do is to distinguish between bash indexed
array and bash associative
array. The former are arrays in which the keys are ordered integers, while the latter are arrays in which the keys are represented by strings.
Although indexed arrays can be initialized in many ways, associative ones can only be created by using the declare
command.
Create Indexed Array
1 | # create array with out declare |
Add new element into array:
1 | array+=(${var}) |
Note that in the context where an assignment statement is assigning a value to a
shell variable
orarray
index (see Arrays), the+=
operator can be used to append to or add to the variable’s previous value.
Using "${array[@]}"
(have double quotes) in for loop to fetch array item. "${array[*]}"
is not recommended, the same reason as shell positional parameters with @ and *.
1 | for item in "${array[@]}" |
Or fetch item by index(key):
1 | # this will only return the value existed index |
Sort array, 这里对array的输出使用了pipeline,一个很好的启发:
1 | a=(f e d c b a) |
Create Associated Array
Statement declare
is the only way to go, see reference for more details. Actually this is Map
in bash. 这里的key 默认是string,虽然可以写成数字.
1 | # create all at once |
Iterate over the associated array:
1 | declare -a array=([a]=a [b]=b [c]=c) |
Array Counterpart
Loop through comma separated string, or other delimiter.
1 | var="1,2,3,4,5" |
还可以使用IFS
设置不同的separator (IFS
also is used with read
), 也可以用tr
去替换分隔符。
Caveat
If you use declare -a
or declare -A
to create array in shell function, it by default is local scope in that function. You can move the declare
out to make the array globally access, or use declare -ga
and `declare -gA (only bash 4.2 and later support this).
Notice that variable defined without local
in function is global access.
Assign array to other variables:
1 | a=('a' 'b' 'c') |
Notice that you cannot export
array directly. Array variables may not (yet) be exported.
in some bash verions, but there are some workarounds.
References
Bash associative array examples Bash indexed arrays Indexed and associative array