Arrays are the main advanced data structure in Bash, but the syntax can be hard to remember. The following list summarizes the main operations.
Assigning an entire array:
nodes=(a b c d) nodes=(foo*) |
Copying an entire array:
nodes=("$@") nodes=("${values[@]}") |
Getting individual elements (zero-based indexing) or the element count:
echo ${nodes[i]} echo ${#nodes[@]} |
Iterating an array:
for node in "${nodes[@]}"; do ... done for ((i=0; i<${#nodes[@]}; i++)); do node=${nodes[i]}; ... done |
Appending to an array:
nodes[${#nodes[@]}]=foo |
If you need the last form regularly, it can be simplified with the following shorthand:
function push_back { eval "$1[\${#$1[@]}]=\"\$2\""; } push_back nodes foo |