Declaring an array

Bash array elements are written inside parentheses with spaces between them. Commas are not required.

sample=("apple" "orange" "grape" "na")

Expanding all elements

The notes compare these two forms:

echo "${sample[@]}"
echo "${sample[*]}"

With double quotes, ${sample[@]} supplies each element as a separate argument, while ${sample[*]} combines the elements into one argument. Use the [@] form when individual elements must remain distinct.

Finding the array length

echo "${#sample[@]}"

The # expansion reports the number of elements.

← Back to all posts