Linux Bash Scripting Tutorial
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]}
#!/usr/bin/bash
# Indexed Array "arr" has 5 elemets
#Initializing Individual array elements with values
arr[0]=1
arr[1]=3
arr[2]=5
arr[3]=8
arr[4]=9
#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.
read -a option
read -a command can be used to created an index based array
read with -a option followed by array name. entered values stored from starting index 0, final index will be number of elements -1
# array has 6 elements index start is 0 end is 5 $ read -a array 1 2 3 4 5 6 echo ${array[0]} echo ${array[1]} echo ${array[2]} echo ${array[3]} echo ${array[4]} echo ${array[5]}Output:
1 2 3 4 5 6
Using read command is one option to create an Index based array in bash scripting
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.
#!/usr/bin/bash #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]}
Output:
sam jhon peter marry joe
Deleting an Array element
There is no way to delete an array element in Bash, But user can assign "null" value to that element
arr[0]=;
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
arr[99]=99;
arr[100]=199;
Updating elements in an Array
Elements can be updated like variable updating or assigning new value to a perticular index value
arr[0]="samuel";
arr[1]="jhonson";
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
Counting Number of elements in an Array
Bash array elements can be counted in following ways
Bash Indexed Array Example: Sum of the Array elements
#!/usr/bin/bash a=(13 15 33 27 12) sum=0; for value in "${a[@]}"; do echo $value (( sum+=value)) done echo "Sum of array elements is ${sum}"; #output: 100
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 declare -A city_population=("Tokyo" 37435191 "Delhi" 29399141 "Shanghai" 26317104 "Cairo" 20484965 "New York" 8467513)
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]}"Displaying array elements can be done using declare -p array_name
$ declare -p city_population declare -A city_population=([Cairo]="20484965" ["New York"]="8467513" [Tokyo]="37435191" [Delhi]="29399141" [Shanghai]="26317104" )
Display Associate Array Elements using for loop
declare -A aa=([name]="samuel" [Age]=63 [job]="Analyst"); for key in "${!aa[@]}" do echo -n "$key :" echo " ${aa[$key]}" doneoutput:
job : Analyst Age : 63 name : samuel
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.
ADS