iXora Custom Software Development Blog

Read | Practice | Advance

All about array in Linux shell (bash) script

Posted by on in Blog
  • Font size: Larger Smaller
  • Hits: 1182
  • 0 Comments
  • Print

Array is very important data structure in any programming language. Almost all programming languages support array. Modern languages have list, dictionary, stack, queue, linkedlist data structures. So very few times actually array is used. Linux has built in bash shell scripting language. This bash script has only array data structure and it does not support any dictionary, list type data structure. So array is very important here and also array usage (declare, assign, read, traverse) is more difficult than other object oriented languages array. So array has little more learning curve in bash script than others.

Creating/Assigning array variable:

You can create array variable in the following ways:

declare –a array_name

Here array_name is the array variable name. –a indicates that variable is an array variable. declare is the keyword indicates it is a declare statement.

array_name[index]=10

Here array_name is the array variable name. [index] is the array subscript and it would be any positive integer value or expression.

If you put like:

games[-1]=100

It will generate error because index should be contain positive integer value.

You can create array like:

games[10+5]=100

It will assign 100 to games[15] subscript

array_name=(10 20 30)

It will create array_name variable with 3 subscripts. The assign value will be stored like:

array_name[0]=10;   array_name[1]=20;  array_name[3]=30

Point to be remember that here array element separator is space. Often you may confuse about that.

Personally I mistakenly use “,” as separator and in run-time I caught the mistake.

If you create an array like:                

countries=(“Bangladesh”, “india”, “Pakistan”)

Surprisingly it assigned all values to the countries[0] element. So you should remember that. Your intention was you create an array with 3 elements. Its syntax will be

countries=(“Bangladesh”  “india”  “Pakistan”) 

 

Reading array variable:

If you have an array like:

countries[0]=“Bangladesh”
countries[1]=“India”
countries[2]=“Pakistan”

* You want to read a particular subscript suppose it would be 1 then code will be like:

echo ${countries[1]} # it will display India

* You want to display all elements, code will be like:

echo ${countries[@]}  or echo ${countries[*]} 

Here you can use either “*” or “@” for indicates all elements in array.

* You want to read/navigate array elements inside for loop:

arr[0]=100
arr[1]=200
arr[2]=300
for elem in ${arr[@]}
do
   echo "$elem"
done

It will display all array elements like ist line 100 then next 2nd line 200 then 3rd line 300

In while loop:

arr_len="${#arr[@]}"
i=0;
while [ $i -lt "$arr_len" ]
do
  echo "${arr[$i]}"
  i=$(( $i+1 ))
done 

C style loop in bash script with array navigation:

arr_len=${#arr[@]}  #array length here it is 3
for((i=0; i<arr_len; i++))
do
   echo "${arr[$i]}"
done

Same result. it will print 1st line 100 then next line 200 then next line 300

One point need to remember that if you read an array element with array index like

echo  “${my_arr[5]}”

and if 5 index is not exists in array instead of return error it will return empty/null value

 

Deleting array element from an array:

Suppose you have an array:

countries[0]=100
countries[1]=200
countries[2]=300
countries[3]=400
you check the length of this array
echo ${#countries[@]}

It will return 4

Then you want to remove 3 subscript element. Code like:

unset contries[3]

Now recheck the length of the array. Instead of 4 it will show 3.

Point to be remember that if you use any subscript/index that does not exists in array, unset command will not throw any error.

 

Sending and receiving array to and from a function

In bash script we can modularize code with creating functions. Now we may need to send array to a function and receive that array from that function and work on that.

Sending array to a function:

function send_array(){
  teams[0]="real"
  teams[1]="barca"
  teams[2]="atlatico" 
  process_teams "teams[@]"
}

Just see the last line of the send_array function. Usually we access array element like “${arr_name[@]}” But here we use “arr_name[@]”. Just point to be remember that we did not use there ${} with the array variable.

function receive_array(){
   team_array="${!1}"
   echo "${team_array[@]}"
}

Just observe again, Usually we receive argument in function like “${1}”. But though it is an array so our syntax changed here and it is “${!1}”

 

Array support dynamically add element

You can create an array like:

teams[0]=”barca”

now we need to add another element in that array at runtime. No problem you can just assign it like

teams[1]=”real”
teams[2]=”atlatico”

an also you can add inside the loop

teams=();
for i in {1..5}
do
  teams[$i]=$i
done
echo "${teams[@]}"

Multiple-type support in an array

We know that type declaration in bash script is optional that means type is implicit in bash script. So we ignore declaration and based on that value bash interpreter assign type at run-time.

The main point here is in array we can define various typed data in various element in array. 

Code example:

arr=();
arr[0]=100
arr[1]="Bangladesh"
arr[2]=2015/12/01
echo "${arr[@]}" 

Try to explain various ways/scenarios where we can use array in bash script. Array usage in bash script little different then other language. For that reason it seems little harder. Hope after reading that write-up you can much easier way to use array and write standard bash script.

Rate this blog entry:
0

Comments

  • No comments made yet. Be the first to submit a comment

Leave your comment

Guest
Guest Saturday, 25 May 2019