Module-3 How to create and use arrays in Bash scripts

Table of Contents

Introduction

Wondering how to create and use arrays in the bash scripts ? This article covers this topic in detail with the script examples 

How to create a simple array in bash

Arrays are variables which have a list of values . In the below example we can see that we created an array named “first_array” which consists of a list of values like “aA” , “bB” , 3 ,4 ,5 ,”fF”. It can be both numbers and strings. We can later retrieve them using the index in which they are stored and the initialized index starts  with 0 and goes until the last value found in the array , in our example the initialized index starts with 0 and ends with 5 as there were 6 values in the first_array variable we created. 

Here is the syntax to create an Array 

first_array=("aA" "bB" 3 4 5 "fF")

Now lets see how to retrieve values using the indexes. We are retrieving the first value using the index 0. Here is the syntax to pull values from the array using the index

${first_array[0]}
[root@discoveringsystems Bash-Scripting]# cat array_script
#!/bin/bash

first_array=("aA" "bB" 3 4 5 "fF")

echo ${first_array[0]}
[root@discoveringsystems Bash-Scripting]# ./array_script
aA

Similarly to pull the 6th value part of the array , we are using the index 5  

[root@discoveringsystems Bash-Scripting]# cat array_script
#!/bin/bash

first_array=("aA" "bB" 3 4 5 "fF")

echo ${first_array[5]}
[root@discoveringsystems Bash-Scripting]# ./array_script
fF

If we are trying to pull values for the indexes which are not initialized , we get null as the return for example , in my first_array variable i have only values initialized for 0-5 indexes , if i am trying to pull index 6 and more i will get null return

[root@discoveringsystems Bash-Scripting]# cat array_script
#!/bin/bash

first_array=("aA" "bB" 3 4 5 "fF")

echo ${first_array[6]}
echo ${first_array[12]}
echo ${first_array[15]}
[root@discoveringsystems Bash-Scripting]# ./array_script


[root@discoveringsystems Bash-Scripting]#

Array values don’t have to be contiguous

 we can have some uninitialized indexes and create values for another index. For example , in my case initially i created a array with 0-5 index and then added another value for the index 12 separately and then tried to retrieve the values based on the index and I was able to see the there is a discontinuous set of indexes initialized , but still i was able to create them and pull the values accordingly. And it is expected to get null values for the indexes which are not initialized


[root@discoveringsystems Bash-Scripting]# cat array_script
#!/bin/bash

first_array=("aA" "bB" 3 4 5 "fF")
first_array[12]="thirteen"

echo ${first_array[6]}
echo ${first_array[12]}
echo ${first_array[15]}
[root@discoveringsystems Bash-Scripting]# ./array_script

thirteen

[root@discoveringsystems Bash-Scripting]#

To see all the initialized values part of the array we can use this 

[root@discoveringsystems Bash-Scripting]# cat array_script
#!/bin/bash

first_array=("aA" "bB" 3 4 5 "fF")
first_array[12]="thirteen"

echo ${first_array[@]}

[root@discoveringsystems Bash-Scripting]# ./array_script
aA bB 3 4 5 fF thirteen

How to delete values from the Array using unset command

We can delete the values from a particular index using the unset command. Here is the syntax to delete index 0 value from the already created array 

unset first_array[0]

Here is the script example for the same 

[root@discoveringsystems Bash-Scripting]# cat array_script
#!/bin/bash

first_array=("aA" "bB" 3 4 5 "fF")
first_array[12]="thirteen"

echo "Here is the entire list of first_array before unsetting ${first_array[@]}"

unset first_array[0]

echo "Here is the entire list of first_array after unsetting ${first_array[@]}"

[root@discoveringsystems Bash-Scripting]# ./array_script
Here is the entire list of first_array before unsetting aA bB 3 4 5 fF thirteen
Here is the entire list of first_array after unsetting bB 3 4 5 fF thirteen
[root@discoveringsystems Bash-Scripting]#

How to loop through the array using the values or indexes 

We can either loop through the indexes of the Array or the values of the Arrays in your bash script based on your requirements 

How to loop through array using the values 

In the script below we can see that an array has been created with some discontinuous indexes and then we looped through the array values and printed them on the terminal 

[root@discoveringsystems Bash-Scripting]# cat array_script
#!/bin/bash

first_array=("aA" "bB" 3 4 5 "fF")
first_array[12]="thirteen"

for value in ${first_array[@]}; do
  echo $value
done


[root@discoveringsystems Bash-Scripting]# ./array_script
aA
bB
3
4
5
fF
thirteen

How to loop through the array using the indexes

In this example , we looped through the array using the index , initially we printed the available initialized indexes and then we looped through them and printed the values as desired . To get the list of indexes part of the array using this syntax ${!first_array[@]}

[root@discoveringsystems Bash-Scripting]# cat array_script
#!/bin/bash

first_array=("aA" "bB" 3 4 5 "fF")
first_array[12]="thirteen"

echo "Here is the entire list of indexes part of first_array ${!first_array[@]}"

for index in ${!first_array[@]}; do
  echo "the value for index $index is ${first_array[index]} "

done


[root@discoveringsystems Bash-Scripting]# ./array_script
Here is the entire list of indexes part of first_array 0 1 2 3 4 5 12
the value for index 0 is aA
the value for index 1 is bB
the value for index 2 is 3
the value for index 3 is 4
the value for index 4 is 5
the value for index 5 is fF
the value for index 12 is thirteen

How to append values to the array

We can append the  values to the array using the syntax  second_array+=( “value” )

In the following example , i created a for loop to append numbers 1 through 10 into the array 


[root@discoveringsystems Bash-Scripting]# cat array_append_script
#!/bin/bash

#initializing empty array
second_array=()



for number in {1..10}; do
  second_array+=( $number )

done

echo " Now the array with appended values is ${second_array[@]}"


[root@discoveringsystems Bash-Scripting]# ./array_append_script
 Now the array with appended values is 1 2 3 4 5 6 7 8 9 10

How to calculate the array size

We are using the same script used in the earlier section , where we were appending numbers 1 through 10 into the second_array variable. After appending all the values we also printed the entire array and also the size of the array using the syntax  ${#second_array[@]}


[root@discoveringsystems Bash-Scripting]# cat array_append_script
#!/bin/bash

#initializing empty array
second_array=()



for number in {1..10}; do
  second_array+=( $number )

done

echo " Now the array with appended values is ${second_array[@]}"
echo " Size of the array is ${#second_array[@]} "

[root@discoveringsystems Bash-Scripting]# ./array_append_script
 Now the array with appended values is 1 2 3 4 5 6 7 8 9 10
 Size of the array is 10
[root@discoveringsystems Bash-Scripting]#

How to overwrite the array values

We can overwrite the array values even after creating it . In the below script example  i created an array , added a index , also overwrote on an index and then printed the changed entire list of the values part of the array 

[root@discoveringsystems Bash-Scripting]# cat array_script
#!/bin/bash

first_array=("aA" "bB" 3 4 5 "fF")
first_array[12]="thirteen"

echo "Here is the entire list of first_array before overwriting ${first_array[@]}"

first_array[0]=1

echo "Here is the entire list of first_array after overwriting ${first_array[@]}"

[root@discoveringsystems Bash-Scripting]# ./array_script
Here is the entire list of first_array before overwriting aA bB 3 4 5 fF thirteen
Here is the entire list of first_array after overwriting 1 bB 3 4 5 fF thirteen

How to store outputs from other commands as array

In the number_files directory we have 5 files , which are empty files. Using our bash script we are going to write “ this is a 1st file” onto file1.txt , likewise we will write to all the files based on their file name . In this bash script we are using the concept of creating the array using the filenames from the output of another command like ls , using the following syntax 

array=( $(ls) )

Here is a script example

[root@discoveringsystems Bash-Scripting]# cat new_array_script
#!/bin/bash

first_array=( $(ls  number_files) )

echo "Entire list of files in first_array: ${first_array[@]}"

for file_name in ${first_array[@]}; do
  echo "this is a ${file_name:4:1}st file" > number_files/$file_name

done

[root@discoveringsystems Bash-Scripting]# ./new_array_script
Entire list of files in first_array: file1.txt file2.txt file3.txt file4.txt file5.txt

[root@discoveringsystems Bash-Scripting]# grep -i file number_files/*
number_files/file1.txt:this is a 1st file
number_files/file2.txt:this is a 2st file
number_files/file3.txt:this is a 3st file
number_files/file4.txt:this is a 4st file
number_files/file5.txt:this is a 5st file

How to retrieve only set of array elements

We can create an array from another array’s set of indexes , let’s say i want to form an array with only 0-2 indexes from the parent array , we can use the following syntax 

Starting index is “s” index and from there the number of indexes to consider is “n” 

${first_array[@]:s:n} 

In this example ,  first_array is the parent array , with filenames file[1-5].txt ( so it has 0-4 indexes initialized )

We are creating a child array first_3_files_array from the parent array using the set of array elements 

first_3_files_array=( ${first_array[@]:0:3} )

Here is the full script and its output result 

[root@discoveringsystems Bash-Scripting]# cat new_array_script
#!/bin/bash

first_array=( $(ls  number_files) )
echo "Entire list of files in first_array: ${first_array[@]}"

echo "Entire list of indexes in first_array: ${!first_array[@]}"


first_3_files_array=( ${first_array[@]:0:3} )


echo "Entire list of files in first_3_files_array: ${first_3_files_array[@]}"

echo "Entire list of indexes in first_3_files_array: ${!first_3_files_array[@]}"


[root@discoveringsystems Bash-Scripting]# ./new_array_script
Entire list of files in first_array: file1.txt file2.txt file3.txt file4.txt file5.txt
Entire list of indexes in first_array: 0 1 2 3 4
Entire list of files in first_3_files_array: file1.txt file2.txt file3.txt
Entire list of indexes in first_3_files_array: 0 1 2

How to initialize a large set of values in arrays

Let’s say we would like to create an array of Base64 characters. We can use the braces expansion concept to initialize some indexed values inside the array. In the below script we demonstrated how to use that braces expansion while  array creation 

[root@discoveringsystems Bash-Scripting]# cat  create_array_script
#!/bin/bash

base64_characters_array=( {0..9} {a..z} {A..Z} + / = )
echo "Entire list of files in base64_characters_array : ${base64_characters_array[@]}"

echo "Entire list of indexes in base64_characters_array= : ${!base64_characters_array[@]}"

[root@discoveringsystems Bash-Scripting]# ./create_array_script
Entire list of files in base64_characters_array : 0 1 2 3 4 5 6 7 8 9 a b c d e f g h i j k l m n o p q r s t u v w x y z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z + / =
Entire list of indexes in base64_characters_array= : 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
[root@discoveringsystems Bash-Scripting]#

Multidimensional Arrays

Multidimensional Arrays are not supported by Bash , so we cannot get array elements that are also arrays.There are ways to simulate the Multidimensional arrays . However not widely used

Associative Arrays in Bash

Associative arrays can store values in a (Key,value) format. It’s almost similar to the dictionaries seen in python. 

To need to use associative Arrays we need to declare the Array using the inbuilt command declare and then we  can initialize the values as per the (Key,value)  pair concept.

In the following example , we have described how to declare the associative array, Initialize the key,value pair. Also how to print the keys and the values separately 


[root@discoveringsystems Bash-Scripting]# cat  associative_array_script
#!/bin/bash

declare -A first_array

first_array[name]="ds admin"
first_array[role]="admin"
first_array[permission]="RW"

echo "Here are the list of keys of first_array : ${!first_array[@]}"
echo "Here are the list of values of first_array : ${first_array[@]}"


[root@discoveringsystems Bash-Scripting]# ./associative_array_script
Here are the list of keys of first_array : name permission role
Here are the list of values of first_array : ds admin RW admin

Leave a Comment

Your email address will not be published. Required fields are marked *