Exploring Bash — Part 8

Dineshkumaar R
6 min readApr 15, 2024

--

Introduction

Hey Friends, Welcome back to my Bash exploration blog series! Let’s dive right in! Arrays in Bash are powerful data structures that facilitate managing multiple values under a single variable name. In this guide, we’ll dive into the intricacies of arrays in Bash scripting, covering everything from basic operations to advanced techniques.

Introduction to Arrays

Arrays in Bash provide a convenient way to handle collections of related data. They allow you to store multiple values under a single variable name, making it easier to manage and manipulate data within your scripts.

Declaring Arrays

Arrays in Bash are declared using parentheses, with elements separated by spaces. You can initialize arrays with values at the time of declaration or create empty arrays for later use.

# Declaring an array with values
my_array=(apple banana cherry)
your_array=("Red" "blue" "green")

# Declaring an empty array
empty_array=()

Accessing Array Elements

You can access individual elements of an array using their indices. Array indices start from 0, and negative indices can be used to access elements from the end of the array. Additionally, you can access all elements of an array using ${array[@]}.

# Accessing individual elements
echo "First element: ${my_array[0]}"
echo "Last element: ${my_array[-1]}"

# Accessing all elements
echo "All elements: ${my_array[@]}"

Example:

#!/bin/bash

# Declaring an array with values
my_array=(apple banana cherry)
your_array=("Red" "blue" "green")

# Declaring an empty array
empty_array=()

# Accessing individual elements
echo "First element of my array: ${my_array[0]}"
echo "Last element of your array: ${your_array[-1]}"

# Accessing all elements
echo "All elements: ${my_array[@]} ${your_array[@]}"

Array Operations

Bash provides various operations for manipulating arrays, such as adding, removing, and modifying elements. These operations enable you to dynamically update arrays based on your requirements.

# Adding elements to an array
my_array+=(grape)

# Removing elements from an array
unset my_array[1]

# Modifying elements in an array
my_array[0]="orange"

Example:

#!/bin/bash

# Declaring an array with values
my_array=(apple banana cherry)

# Accessing all elements
echo "All elements: ${my_array[@]}"

# Adding elements to an array
my_array+=(grape)

# Accessing all elements
echo "All elements: ${my_array[@]}"

# Removing elements from an array
unset my_array[1]

# Accessing all elements
echo "All elements: ${my_array[@]}"

# Modifying elements in an array
my_array[0]="orange"

# Accessing all elements
echo "All elements: ${my_array[@]}"

Iterating Over Arrays

You can iterate over the elements of an array using loops, such as the ‘for’ loop. This allows you to perform actions on each element of the array sequentially.

# Iterating over array elements
for fruit in "${my_array[@]}"
do
echo "Fruit: $fruit"
done

Example :

#!/bin/bash

# Declaring an array with values
my_array=(apple banana cherry orange grape)

# Iterating over array elements
for fruit in "${my_array[@]}"
do
echo "Fruit: $fruit"
done

Associative Arrays

Associative arrays, also known as key-value pairs, allow you to associate keys with values in Bash. They provide a way to store data with arbitrary keys, making them useful for various applications.

# Declaring an associative array
declare -A my_assoc_array
my_assoc_array[key1]=value1
my_assoc_array[key2]=value2

# Accessing values by keys
echo "Value associated with key1: ${my_assoc_array[key1]}"
echo "Value associated with key2: ${my_assoc_array[key2]}"

Example :

#!/bin/bash

# Declare an associative array to store customer information
declare -A customer_info

# Add customer information
customer_info["Dinesh"]="dinesh@medium.com india 123-456-7890"
customer_info["Kumar"]="kumar@medium.com america 987-654-3210"

# Function to retrieve customer information by name
get_customer_info() {
local name=$1
echo "Customer: $name"
echo "Email: $email$(echo "${customer_info[$name]}" | awk '{print $1}')" # Extract email
echo "Country: $country$(echo "${customer_info[$name]}" | awk '{print $2}')" # Extract Country
echo "Phone: $phone$(echo "${customer_info[$name]}" | awk '{print $3}')" # Extract phone number
echo ""
}
# Example usage
get_customer_info "Dinesh"
get_customer_info "Kumar"

• The script uses an associative array named customer_info to store customer information.
• Each entry in the customer_info array consists of a customer’s name as the key and their details (email, country, and phone number) as the value, separated by spaces.
• It defines a function called get_customer_info which retrieves and displays a customer’s information based on their name.
• The get_customer_info function takes a customer’s name as an argument.
• Inside the function, it extracts the email, country, and phone number of the customer using the awk command.
• Then, it prints out the customer’s name along with their extracted details.
• The script demonstrates the usage of the get_customer_info function by retrieving and displaying the information of two customers: “Dinesh” and “Kumar”.

Array Length

You can determine the length of an array in Bash using ‘${#array[@]}’. This allows you to retrieve the number of elements in the array dynamically.

# Getting the length of an array
length=${#my_array[@]}
echo "Length of the array: $length"

Example:

#!/bin/bash

# Declaring an array with values
my_array=(apple banana cherry grapes)

# Getting the length of an array
echo "Length of the array: ${#my_array[@]}"

# Getting the length of an banana
echo "Length of the banana: ${#my_array[1]}"

Multidimensional Arrays

Bash supports multidimensional arrays for storing tabular data. You can declare and access elements of multidimensional arrays using nested indices.

#!/bin/bash
# Declaring a multidimensional array to represent a classroom seating arrangement
declare -A classroom

# Assigning values to represent the seating arrangement
classroom[0,0]="Dinesh"
classroom[0,1]="Dhanush"
classroom[1,0]="Ramesh"
classroom[1,1]="Anusha"

# Accessing elements of the multidimensional array
echo "Student at position (0,0): ${classroom[0,0]}"
echo "Student at position (1,1): ${classroom[1,1]}"

Real World Example

Real-world examples demonstrate how to use arrays in Bash scripts for various tasks, such as processing lists of files, storing configuration settings, and managing data structures.

#!/bin/bash
# Example script to process a list of files

# Declare an empty array to store file names
files=()

# Iterate over files in the current directory and add them to the array
for file in *
do
if [ -f "$file" ]
then
files+=("$file")
fi
done

# Print all file names in the array
echo "List of files:"
for file in "${files[@]}"
do
echo "$file"
done

Summary of the blog

1. Introduction to Arrays: Bash arrays handle collections of data efficiently under one variable name.
2. Declaring Arrays: Declare arrays using parentheses, initializing with values or as empty for later use.
3. Accessing Array Elements: Access elements by index starting from 0, with negative indices for accessing from the end.
4. Array Operations: Bash provides operations like adding, removing, and modifying elements for dynamic updates.
5. Iterating Over Arrays: Use loops, like for, to perform actions on each array element sequentially.
6. Associative Arrays: Key-value pairs for associating keys with values in Bash, useful for various scenarios.
7. Array Length: Determine array length dynamically using ${#array[@]}.
8. Multidimensional Arrays: Bash supports multidimensional arrays for tabular data storage and access.
9. Real World Example: Demonstrates practical array usage in Bash for tasks like file processing, configuration storage, and data management.

URL’s :

  1. Exploring bash — Part1 : https://medium.com/@dineshkumaar478/exploring-bash-part-1-3dabf4b5ef9e
  2. Exploring bash — Part2 : https://medium.com/@dineshkumaar478/exploring-bash-part-2-71f341fb5700
  3. Exploring bash — Part3 : https://medium.com/@dineshkumaar478/exploring-bash-part-3-db1fc958eb17
  4. Exploring bash — Part4 : https://medium.com/@dineshkumaar478/exploring-bash-part-4-4521aaac30ea
  5. Exploring bash — Part5 : https://medium.com/@dineshkumaar478/exploring-bash-part-5-a136eb036b4f
  6. Exploring bash — Part6 : https://medium.com/@dineshkumaar478/exploring-bash-part-6-31887f5c3695
  7. Exploring bash — Part7 : https://medium.com/@dineshkumaar478/exploring-bash-part-7-f9a3e37a5931

Thank you for taking the time to read my blog. Wishing you a joyful learning experience ahead!

--

--

Dineshkumaar R

🔐 Cyber Security Engineer | Penetration Tester | VAPT Specialist | 🚩 Hackthebox (Pro Hacker) | 🏆 Tryhackme (Guru)