Bash Arrays

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

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>