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. You will be given three lists of arrays and your task will be to find the common elements among all three arrays.

Initialize the arrays

Create a new file called ~/project/array-comparison.sh.

Start by initializing three arrays: a, b, and c.

a=(3 5 8 10 6)
b=(6 5 4 12)
c=(14 7 5 7)

Compare arrays a and b

Next, compare the elements of arrays a and b to find the common elements. To do this, you can use nested loops.

## initialize an empty array to store the common elements
z=()

## loop through all elements of array a
for x in "${a[@]}"; do
  ## set a flag to false
  in=false

  ## loop through all elements of array b
  for y in "${b[@]}"; do
    if [ $x = $y ]; then
      ## if a match is found, add the element to array z
      z+=($x)
    fi
  done
done

Compare array c with array z

Next, compare the elements of array c with the elements of array z to find the common elements. Again, you can use nested loops for this step.

## initialize an empty array to store the common elements
j=()

## loop through all elements of array c
for i in "${c[@]}"; do
  ## set a flag to false
  in=false

  ## loop through all elements of array z
  for k in "${z[@]}"; do
    if [ $i = $k ]; then
      ## if a match is found, add the element to array j
      j+=($i)
    fi
  done
done

Print the common elements

Finally, print the common elements found in array j.

echo ${j[@]}

Execute the script.

cd ~/project
chmod +x array-comparison.sh
./array-comparison.sh
Common elements: 5

Summary

In this lab, you learned how to compare arrays in Shell scripting. By using nested loops, you were able to find the common elements among three different arrays.

Other Shell Tutorials you may like