15

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?

24

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
| improve this answer | |
  • minerz029, @a.m.: ..and how to define the elements? I tried but could only define/access a single string.. a little example to define and access the values to array variable would be great... – precise Jan 9 '14 at 6:29
  • well figured that out.. I was missing the braces.. – precise Jan 9 '14 at 6:32
4

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]}
| improve this answer | |
1

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.

| improve this answer | |
  • What is the problem in the answer ? Why down vote ? – Maniruzzaman Akash Oct 23 '17 at 6:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.