Comparing Arrays in Shell Scripting

ShellShellBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, you will learn how to compare arrays in Shell scripting. Arrays are useful data structures for storing multiple values, and comparing them is a common task in programming. You will work with three arrays and develop a script to find the common elements among them. This process will help you understand array manipulation, loops, and conditional statements in Shell scripting.

Create the script file

First, let's create a new file for our script.

  1. Open a terminal in the WebIDE. You should see a command prompt ending with a $ sign.

  2. Navigate to the project directory:

cd ~/project

This command changes your current directory to the project folder. The ~ symbol represents your home directory, and /project is a subfolder within it.

  1. Create a new file named array-comparison.sh:
touch array-comparison.sh

The touch command creates an empty file. If the file already exists, it updates the file's timestamp without modifying its contents.

  1. Open the file in the WebIDE editor. You can do this by clicking on the file name in the file explorer on the left side of your WebIDE interface.

Add the shebang and initialize the arrays

Now, let's start writing our script by adding the shebang and initializing our arrays.

  1. Add the following content to array-comparison.sh:
#!/bin/bash

## Initialize the arrays
a=(3 5 8 10 6)
b=(6 5 4 12)
c=(14 7 5 7)

Let's break this down:

  • The first line #!/bin/bash is called a shebang. It tells the system to use the Bash interpreter to run this script. This line is crucial for any shell script.
  • We then initialize three arrays: a, b, and c. In Bash, arrays are defined by enclosing the elements in parentheses () and separating them with spaces.
  • Each array contains different integer values. We'll use these arrays to find common elements.

Implement the first comparison loop

Let's implement the first comparison loop to find common elements between arrays a and b.

Add the following code to your script:

## Initialize an array to store common elements between a and b
z=()

## Compare arrays a and b
for x in "${a[@]}"; do
  for y in "${b[@]}"; do
    if [ $x = $y ]; then
      z+=($x)
    fi
  done
done

echo "Common elements between a and b: ${z[@]}"

Let's explain this code in detail:

  • z=() initializes an empty array z to store the common elements.
  • for x in "${a[@]}" is a loop that iterates over each element in array a. The "${a[@]}" syntax expands to all elements of the array.
  • We then have a nested loop for y in "${b[@]}" that iterates over each element in array b.
  • if [ $x = $y ] checks if the current element from a is equal to the current element from b.
  • If they are equal, we add this element to array z using z+=($x).
  • Finally, we print the common elements using echo "Common elements between a and b: ${z[@]}". The ${z[@]} syntax expands to all elements of array z.

Implement the second comparison loop

Now, let's implement the second comparison loop to find common elements between array c and the previously found common elements in array z.

Add the following code to your script:

## Initialize an array to store common elements among a, b, and c
j=()

## Compare array c with the common elements found in z
for i in "${c[@]}"; do
  for k in "${z[@]}"; do
    if [ $i = $k ]; then
      j+=($i)
    fi
  done
done

echo "Common elements among a, b, and c: ${j[@]}"

This code is similar to the previous loop, but with a few key differences:

  • We initialize a new empty array j to store the final common elements.
  • The outer loop for i in "${c[@]}" iterates over elements in array c.
  • The inner loop for k in "${z[@]}" iterates over the common elements we found between a and b, which are stored in array z.
  • We compare elements from c with elements in z, and if there's a match, we add it to array j.
  • Finally, we print the common elements among all three arrays.

Make the script executable and run it

Now that we have completed our script, let's make it executable and run it.

  1. In the terminal, make the script executable:
chmod +x ~/project/array-comparison.sh

The chmod command changes the permissions of a file. The +x option adds executable permissions, allowing you to run the script.

  1. Run the script:
~/project/array-comparison.sh

This command executes your script. The ~/project/ part specifies the path to the script.

You should see output similar to this:

Common elements between a and b: 5 6
Common elements among a, b, and c: 5

This output shows that:

  • The common elements between arrays a and b are 5 and 6.
  • The common element among all three arrays (a, b, and c) is 5.

If you don't see this output or encounter an error, double-check your script for any typos or missing parts.

Summary

In this lab, you learned how to compare arrays in Shell scripting. You created a script that finds common elements among three arrays using nested loops and conditional statements. This exercise demonstrated key concepts in Shell scripting, including:

  1. Creating and initializing arrays
  2. Using nested loops to compare array elements
  3. Conditional statements to check for equality
  4. Adding elements to arrays dynamically
  5. Making a script executable and running it

These skills are fundamental in Shell scripting and can be applied to more complex data processing tasks in the future. As you continue to work with Shell scripts, you'll find that array manipulation is a powerful tool for handling sets of data efficiently.

Remember, practice is key to mastering these concepts. Try modifying the script to work with different arrays or to find unique elements instead of common ones. Happy scripting!

Other Shell Tutorials you may like