Declare an array but not define it?

You can specify that a variable is an array by creating an empty array, like so:

var_name=()

var_name will then be an array as reported by

$ declare -p var_name
declare -a var_name='()'

Example:

var_name=()
for i in {1..10}; do
    var_name[$i]="Field $i of the list"
done
declare -p var_name
echo "Field 5 is: ${var_name[5]}"

which outputs something like this:

declare -a var_name='([1]="Field 1 of the list" [2]="Field 2 of the list" [3]="Field 3 of the list" [4]="Field 4 of the list" [5]="Field 5 of the list" [6]="Field 6 of the list" [7]="Field 7 of the list" [8]="Field 8 of the list" [9]="Field 9 of the list" [10]="Field 10 of the list")'
Field 5 is: Field 5 of the list

In addition to above way, we can also create an array by declare statement.

The declare statement with -a option can be used to declare a variable as an array, but it's not necessary. All variables can be used as arrays without explicit definition. As a matter of fact, it appears that in a sense, all variables are arrays, and that assignment without a subscript is the same as assigning to "[0]". Explicit declaration of an array is done using the declare built-in:

declare -a ARRAYNAME

Associative arrays are created using

declare -A name.

Attributes may be specified for an array variable using the declare and readonly builtins. Each attribute applies to all members of an array.

After you have set any array variable, you access it as follows:

${array_name[index]}

Tags:

Bash