bash how to print array

Answer

Arrays in bash are indexed from 0 (zero based). To print the first element of array use index 0:

array=(one two three four)
echo ${array[0]}

Output: one

To refer to the value of an item in array, use braces "{}". The braces are required to avoid issues with pathname expansion.

To write all elements of the array use the symbol "@" or "*".

The difference between "$@" and "$*" is "$@" expand each element as a separate argument, however "$*" expand to the arguments merged into one argument.

echo "${array[*]}"

Output: one two three four

If you need to get length of the array use symbol "#" before the name of array:

echo "${#array[*]}"

Output: 4

You can explicit define an array:

declare -a MY_ARRAY

Was this information helpful to you? You have the power to keep it alive.
Each donated € will be spent on running and expanding this page about UNIX Shell.