Shell Script: correct way to declare an empty array

Run it with bash:

bash test.sh

And seeing the error, it seems you're actually running it with dash:

> dash test.sh
test.sh: 5: test.sh: Syntax error: "(" unexpected

Only this time you probably used the link to it (/bin/sh -> /bin/dash).


I find following syntax more readable.

declare -a <name of array>

For more details see Bash Guide for Beginners: 10.2. Array variables.


In BASH 4+ you can use the following for declaring an empty Array:

declare -a ARRAY_NAME=()

You can then append new items NEW_ITEM1 & NEW_ITEM2 by:

ARRAY_NAME+=(NEW_ITEM1)
ARRAY_NAME+=(NEW_ITEM2)

Please note that parentheses () is required while adding the new items. This is required so that new items are appended as an Array element. If you did miss the (), NEW_ITEM2 will become a String append to first Array Element ARRAY_NAME[0].

Above example will result into:

echo ${ARRAY_NAME[@]}
NEW_ITEM1 NEW_ITEM2

echo ${ARRAY_NAME[0]}
NEW_ITEM1

echo ${ARRAY_NAME[1]}
NEW_ITEM2

Next, if you performed (note the missing parenthesis):

ARRAY_NAME+=NEW_ITEM3

This will result into:

echo ${ARRAY_NAME[@]}
NEW_ITEM1NEW_ITEM3 NEW_ITEM2

echo ${ARRAY_NAME[0]}
NEW_ITEM1NEW_ITEM3

echo ${ARRAY_NAME[1]}
NEW_ITEM2

Thanks to @LenW for correcting me on append operation.

Tags:

Arrays

Shell

Bash