Declare an array but not define it?

There are a lot of guides out there which show how to declare and define an array

foo[0]=abc 
foo[1]=def

What I am trying to achieve is to declare an array but not define it because it does not have to be define immediately , in most programming languages it will look something like this

int bar[100];

Is this possible in shell scripting language?


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]}

This is actually same as C. In C, we can take array as you preferred. Here, we can take an empty array and then put any values.

bar=()

Simple For Loop to take value in that array and print that:

bar=()
for ((i=0;i<10;i++));
do
    read bar[$i]  #Take Value in bar array
    echo bar[$i]
done

Hope, it helps.