- Define an Array by Index
- Define an Array with Multiple Values
- Define an Associative Array
- Count the Array Values
- Read the Array Values by Loop
- Read the Particular Values of the Array
- Insert the Array Values
- Read a File Content into the Array
- Combine the Array Values
- Modify the Array Values
- Remove the Array Values
- Search and Replace the Array Values
- Use an Array as a Function Argument
- Return the Array from the Function
- Make the Array Empty
Define an Array by Index
The method of declaring an array by mentioning the sequential or nonsequential numeric indexes is shown in the following script. This type of array is called a numeric array. Here, the “$books” array is created by defining three sequential indexes and the “$products” array is created by defining four non-sequential indexes. All values of both arrays are printed using the “printf” function.
#Define array index in sequential order
books[0]='Learning the bash Shell'
books[1]='Cybersecurity Ops with bash'
books[2]='Bash Command Line Pro Tips'
echo "All values of the first array:"
printf '%s\n' "${books[@]}"
#Define array index in non-sequential order
products[10]='Pen'
products[5]='Pencil'
products[9]='Rular'
products[4]='A4 Size Paper'
echo
echo "All values of the second array:"
printf '%s\n' "${products[@]}"
Output:
The following output appears after executing the script. The values of both arrays are printed in the output. The index order is maintained at the time of printing for the array of non-sequential indexes:
Define an Array with Multiple Values
A numeric array with multiple values can be declared using the “declare” command with the -a option or without using the “declare” command. In the following script, the first array is declared using the “declare” command and the second array is created without using the “declare” command.
#Declare a numeric array with the 'declare' keyword
declare -a names=('Michael' 'David' 'Alexander' 'Thomas' 'Robert' 'Richard')
#Print the array values
echo "All values of the first array:"
printf '%s\n' "${names[@]}"
#Declare a numeric array without 'declare' keyword
books=('Shell Scripting Tutorials' 'Bish Bash Bosh!' 'Learn Bash Quickly')
#Add newline
echo
#Print the array values
echo "All values of the second array:"
printf '%s\n' "${books[@]}"
Output:
The following output appears after executing the script. The values of both arrays are printed here:
Define an Associative Array
The array that contains the string value as the index is called an associative array. The -A option is used with the “declare” command in Bash to create an associative Bash array. In the following script, the first associative array is declared by mentioning the indexes separately and the second array is declared by mentioning all key-value pairs at the time of the array declaration.
#Declare an associative array variable without value
declare -A employee
#Assign value separately by defining the index
employee['id']='78564'
employee['name']='Sadia Akter'
employee['post']='CEO'
employee['salary']=300000
#Print two values of the array
echo "Employee ID: ${employee[id]}"
echo "Employee Name: ${employee[name]}"
#Declare an associative array with values
declare -A course=( [code]='CSE-206' [name]='Object Oriented Programming' [credit_hour]=2.0 )
#Add newline
echo
#Print two array values of the second array
echo "Course Name: ${course[name]}"
echo "Credit Hour: ${course[credit_hour]}"
Output:
The following output appears after executing the script. The particular values of the associative array are printed here by mentioning the key or index value:
Count the Array Values
The method of counting the total elements of the numeric array and the associative array is shown in the following script:
#Declare a numeric array
declare -a names=('Michael' 'David' 'Alexander' 'Thomas' 'Robert' 'Richard');
echo "The length of the numeric array is ${#names[@]}"
#Declare an associative array
declare -A course=([code]='CSE-206' [name]='Object Oriented Programming' [credit_hour]=2.0)
echo "The length of the associative array is ${#course[@]}"
Output:
The following output appears after executing the script. The array length of the numeric and associative arrays are printed here:
Read the Array Values by Loop
The method of reading all values of a numeric array and an associative array using the “for” loop is shown in the following script:
#Declare a numeric array
declare -a books=("Shell Scripting Tutorials" "Bish Bash Bosh!" "Learn Bash Quickly")
#Print the numeric array values
echo "Numeric array values are:"
for v in "${books[@]}"
do
echo "$v"
done
echo
#Declare an associative array with values
declare -A clients=(
[id]='H-5623'
[name]='Mr. Ahnaf'
[address]='6/A, Dhanmondi, Dhaka.'
[phone]='+8801975642312')
#Print the associative array values
echo "Associative array values are:"
for k in "${!clients[@]}"
do
echo "$k=>${clients[$k]}"
done
Output:
The following output appears after executing the script. Here, the values of the numeric array and the key-value pairs of the associative array are printed in the output:
Read the Particular Range of Values of the Array
The array values of the particular range of the indexes is shown in the following script. In the script, a numeric array of four elements is defined. Two array values from the second index of the array are printed later.
#Declare a numeric array
declare -a cakes=('Chocolate Cake' 'Vanilla Cake' 'Red Velvet Cake' 'strawberry cake')
#Print the particular array values
echo "The 2nd and 3rd elements of the array values are:"
printf '%s\n' "${cakes[@]:1:2}"
Output:
The following output appears after executing the script. The second and third values of the array are “Vanilla Cake” and “Red Velvet Cake” which are printed in the output:
Insert the Array Valuess
The method of adding multiple values at the end of the array is shown in the following script. The main array which is “$books” contains three elements and two elements are added at the end of the “$books” array.
#Declare a numeric array
declare -a books=("Shell Scripting Tutorials" "Bish Bash Bosh!" "Learn Bash Quickly")
#Print the array values before inserting
echo "Array values:"
printf '%s\n' "${books[@]}"
echo
books=("${books[@]}" "Linux Command Line and Shell Scripting Bible" "Advanced Bash Scripting Guide by Mendel Cooper")
#Print the array values after inserting
echo "Array values after inserting two values:"
printf '%s\n' "${books[@]}"
Output:
The following output appears after executing the script. The array values before and after inserting new values are printed in the output:
Read the File Content into the Array
Create a text file named “fruits.txt” with the following content to test the script of this example:
fruits.txt
Jackfruit
Pineapple
Orange
Banana
In the following script, the content of a file is stored in an array named “$data”. Here, each line of the file is stored as each element of the array. Next, the array values are printed.
#Read the filename from the user
read -p "Enter the filename:" filename
if [ -f $filename ]
then
#Read the file content into an array"
data=( `cat "$filename" `)
echo "The content of the file is given below:"
#Read the file line by line
for line in "${data[@]}"
do
echo $line
done
fi
Output:
The following output appears after executing the script. The output that is shown by the “cat” command and the output of the script are similar because the same file is accessed by the “cat” command and the script:
Combine the Array Values
A new array is created by combining the values of multiple arrays. In the following script, two numeric arrays of strings are defined. Then, a new array is created by combining the values of these arrays.
#Declare the first array
declare -a nameList1=('Michael' 'David' 'Alexander' 'Thomas')
echo "The first array values are:"
printf '%s, ' ${nameList1[@]}
echo
#Declare the second array
declare -a nameList2=('Robert' 'Richard')
echo "The second array values are:"
printf '%s, ' ${nameList2[@]}
echo
#Create a new array by combining two arrays
combined_array=("${nameList1[@]}" "${nameList2[@]}")
echo "The combined array values are:"
printf '%s, ' ${combined_array[@]}
echo
Output:
The following output appears after executing the script. Here, the values of three arrays are printed in the output. The third array contains all values of the first and the second array:
Modify the Array Values
The method of updating one or more array values by mentioning the index is shown in the following script:
#Declare the first array
declare -a nameList=('Michael' 'David' 'Alexander' 'Thomas')
echo "Array values:"
printf '%s, ' ${nameList[@]}
echo
#Update the 2nd value of the array
nameList[1]='Robert'
echo "Array values after update:"
printf '%s, ' ${nameList[@]}
echo
Output:
The following output appears after executing the script. The values of the main array and the updated arrays are printed in the output:
Remove the Array Values
The “unset” command is used to remove the particular element or all elements of the array. In the following script, the second element of the array is removed.
#Declare a numeric array
declare -a books=("Shell Scripting Tutorials" "Bish Bash Bosh!" "Learn Bash Quickly")
#Print the array values before removing
echo "Array values:"
printf '%s\n' "${books[@]}"
echo
#Remove the 2nd element
unset books[1]
#Print the array values after remove
echo "Array values after removing the 2nd value:"
printf '%s\n' "${books[@]}"
Output:
The following output appears after executing the script. The values of the main array and the array values after removing one value are printed in the output:
Search and Replace the Array Values
In the following script, the particular value of the array is replaced by another value if the search value that is defined in the pattern is matched with any value of the “$names” array.
#Declare the first array
declare -a names=('Michael' 'David' 'Alexander' 'Thomas')
#Print the original array values
echo "Original array values:"
printf '%s\n' "${names[@]}"
#Generate string after replacing the array values
updated_array=${names[@]/Alexander/Richard}
#Print the array values after replace
echo "Array values after replace:"
printf '%s\n' "${updated_array[@]}"
Output:
The following output appears after executing the script. The values of the main array and the array values after replacing a value are printed in the output:
Use an Array as a Function Argument
In the following script, an array variable is passed as the function argument and the values of that array are printed later.
#Declare an array of numbers
declare -a numbers=(10 6 45 13 8)
#Define a function that will take an argument value
func()
{
#Read the first argument
numbers=$1
#Print the array values
echo "Array values:"
printf '%d\n' "${numbers[@]}"
}
#Call the function with the array as an argument
func "${numbers[@]}"
Output:
The following output appears after executing the script:
Return an Array from the Function
In the following script, the function is called with four numeric arguments. An array is created with the argument values and that array is returned from the function to the caller.
#Define a function that reads four argument values
func()
{
#Read the argument values
numbers=($1 $2 $3 $4)
#Return the array
echo "${numbers[@]}"
}
#Call the function with three arguments
return_val=$(func 78 45 90 23)
#Store the return value in an array
read -a num <<< $return_val
#Print the values of the returned array
echo "The values of the array are:"
for v in "${num[@]}"
do
echo "$v"
done
Output:
The following output appears after executing the script:
Make the Array Empty
The following script shows the method of making an array empty using the “unset” command. The total number of array values is printed before and after making the array empty.
#Declare an array of numbers
declare -a numbers=(10 6 45 13 80)
echo "Numbers of array values: ${#numbers[@]}"
#Make the array empty
unset numbers
echo "Number of array values after making array empty:${#numbers[@]}"
Output:
The following output appears after executing the script. The number of elements of the array became 0 after making the array empty:
Conclusion
Different methods of declaring, accessing, modifying, and removing the array variables in the Bash script are shown in this tutorial using 15 simple examples. We hope that this tutorial will help the Bash users to know the uses of Bash array in detail.