Linux Bash Scripting Tutorial

Arrays in Bash Scripting

Bash supports one-dimensional arrays

Arrays are collection of items,accessed by index

Bash also supports associate arrays, accessed by arbitrary string

Bash arrays has no upped bound limit, lower bound starts from zero

Creating a Indexed Bash Array

Creating a Indexed bash array uses variable name followed by square brackets,assigning values to every element is same as variable assigment,arraname[index]=[value],if no value specified null will be assigned to that element.Bash arrays may be continuous or contiguous.
Array elements can be accessed using ${arrayname[index]}


		# Indexed Array "arr"  has 5 elemets

	#Initializing Individual array elements with values

	 #Array "arr"  has 5 elemenrs , index starts from 0 , each element assigned with value.

	#printing array elements
	#accessing individual element, using dollar sign $ followed by curly braces,with in curly braces arrayname 
	followed by sqaure brackes,and within square brackets index value.
	#Note: no space between $ sign and curly braces, and  array name and sqaure brackets.
	echo ${arr[0]} 
	echo ${arr[1]}
	echo ${arr[2]}	
	echo ${arr[3]}
	echo ${arr[4]}

	echo ${ arr[4] } #error : bad substitution No space between curly braces and array variable name
Note: [ is test command , but in arrays it is literally typed.

Creating Index Array using declare command Syntax:

		declare -a ia=([0]="fruits" [1]="dounuts" [2]="Strawberry")

Creating a Indexed Bash Array- Method 2

In this type of array creation, array indexed automatically from 0 to N elements in the list.
below example has 5 names seperated by single space
i.e arr[0] has "sam" arr[1] has "jhon" arr[2] has peter ... so on.

		#Initializing array with fixed values.
		arr=(sam jhon peter marry joe)
		#referencing array elemnts
	echo ${arr[0]} 
	echo ${arr[1]}
	echo ${arr[2]}	
	echo ${arr[3]}
	echo ${arr[4]}



Deleting an Array element

There is no way to delete an array element in Bash, But user can assign "null" value to that element

for zero index value set to null

Adding elements to an Array

Elements can be added to any location in Bash array, because Bash arrays are not contiguous


Updating elements in an Array

Elements can be updated like variable updating or assigning new value to a perticular index value


Remove all elements from an Array

Bash array elements can be removed using unset command

unset arr;

Displaying all Array elements

Bash array elements can be displayed

  • ${arr[@]}
  • ${arr[*]}

Counting Number of elements in an Array

Bash array elements can be counted in following ways

  • ${#arr[@]}
  • ${#arr[*]}

Bash Indexed Array Example: Sum of the Array elements


                a=(13 15 33 27 12)
                for value in "${a[@]}";
                        echo $value
                        (( sum+=value))

                echo "Sum of array elements is ${sum}";
#output: 100

Associate Arrays in Bash

Another type of arrays supported by Bash are Associate Arrays. In Index based Arrays, Integral value acts as a Index, Where as in Associate Arrays "Arbitrary String" acts as a Index. It is similar to Map Data Structure in programming languages like C++,Java,Python etc., where Key associated with value .

Declaring a Associate Array Syntax:

		declare -A aa;   # unintialized Associate Array
		declare -A aa=([sam]="1 2 3 4 5" [pal]="5 6 7 8 9")  #Initialized Associate Array

Creating Associate Arrays

	#Declaring Associate Array with Initial Values

        #Declaring Associate Array with Initial Values

        declare  -A aa=([name]="samuel" [Age]=63 [job]="Analyst");

#Display Array Elements

        echo  "Name: ${aa[name]}"
        echo  "Age:${aa[Age]}"
        echo  "Job: ${aa[job]}"

Display Associate Array Elements using for loop

		        declare  -A aa=([name]="samuel" [Age]=63 [job]="Analyst");
                       for key in "${!aa[@]}"
                                echo -n "$key :"
                                echo " ${aa[$key]}"

job : Analyst
Age : 63
name : samuel

Readarray Shell builtin

readarray or  mapfile mapfile is a synonym for readarray.

readarray syntax:

		readarray array < file

reads from a file line by line ,by default each line seperated by new line character and each field seperated by space and creates an array variable with file content

readarray Example:

		nirvana ~> cat data
			1 2 3
			4 5 6
		nirvana ~> readarray arr < data
		nirvana ~> echo ${arr[@]}
		1 2 3 4 5 6

readarray Example with delimiter: text file 'data' with sample content

		nirvana ~>cat data
		Your home directory is where you’re placed whenever you log on to the system. A special shell variable called HOME is also automatically set to this directory when you log on.

In the above text each sentence is seperated by dot or period(,). so lines extracted based on delimter. Each element in the array has one sentence.In above example there are 2 sentences,each seperated by dot. readarray uses -d option to set delimter.

		nirvana ~> readarray -d '.' a < data
		nirvana ~> echo ${#arr[0})
		Your home directory is where you’re placed whenever you log on to the system.
		nirvana ~> echo ${#arr[1})
		A special shell variable called HOME is also automatically set to this directory when you log on.