Check If Array Contains an Element in Bash [6 Methods]

LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now

Bash arrays provide a powerful tool for storing multiple values in one variable. While dealing with arrays, determining whether a particular element is present is a common task. This article will provide 6 methods to check if an array contains an element in bash. By gaining an understanding of these techniques, you will be able to create more efficient and reliable shell scripts.

6 Methods to Check if Array Contains an Element in Bash

To check if an array contains an element in bash, you can use the “regex” and “equal to” operator. Additionally, several commands can be employed to verify the existence of an element in the array, such as fgrep, grep, printf, etc. Besides, you can also use ‘for loop’ to accomplish this task.

In this part, I will discuss 6 methods of checking array elements in bash:

1. Using “regex” Pattern

To check if an array contains an element in bash, use a regular expression operator inside the if condition which works by partially matching the pattern of the specific element. It does not match the exact word rather it checks if the specified element matches any part of the array as a whole. Here’s how:

#!/bin/bash
array=("grapes" "potatoes" "bananas" "apples")
element="potatoes"
if [[ ${array[@]} =~ $element ]]
then
  echo "Array element '$element' exists"
else
  echo "Array element does not exist"
fi
EXPLANATION

Here, ${array[@]} represents all the elements of the bash array separated by spaces. If the specific array element “potatoes” exists in the array, this script will print the if block expression otherwise, it will execute the statement “Array element does not exist”. It also prints the “Array element ‘element’ exists” if you want to find the “potato” from the array as it is a substring of an element of the array.

checking if an element exists in bash array using regex

In this image, you can see that the array element “potatoes” is present in the bash array so it shows “Array element ‘potatoes” exists”.

2. Using “fgrep” Command

The “fgrep” command can be piped with the echo "${array[@]}" (output of bash array) to search for a specific element in the bash array. For that, the -w option of the fgrep command is used, which stands for word match. This ensures the search for whole words, preventing partial matches. Here’s how you can check the existence of an array element using the fgrep command in a Bash script:

#!/bin/bash
array=("grapes" "potatoes" "bananas" "apples")
element="grapes"
if [[ $(echo "${array[@]}" | fgrep -w "$element") ]]; then
  echo "Array element '$element' exists"
else
  echo "Array element does not exist"
fi
EXPLANATION

The script returns the if block statement when the whole word ‘grapes’ is found within the array. Otherwise, it will print the else block statement.

checking if an element exists in bash array using fgrep command

As you can see in this image “Array element ‘grapes’ exists” since it’s present in the bash array.

3. Using a “for” Loop

To find the particular array element, you can use if [[ "$i" == "$element" ]] syntax within a for loop which iterates through the array and compares the $element with each array element. Besides, you can check multiple elements using a for loop. Here’s a complete bash script to check if an element exists in a bash array:

#!/bin/bash
array=("grapes" "potatoes" "bananas" "apples")
element="oranges"

# Loop through the array
for i in "${array[@]}"
do
    # Check if the element matches the search value
    if [[ "$i" == "$element" ]]; then
        echo "Array contains '$element'."
        exit 0
    fi
done

# If the loop completes without finding the element
echo "Array does not contain '$element'."
exit 1
EXPLANATION

If a match is found, it prints a message indicating that the array contains the specified element with a success status (exit 0). In contrast, it exits “Array does not contain ‘$element’.” with an error status exit 1.

checking if an element exists in bash array using for loop

Since the array element “oranges” is absent in the bash array, it displays “Array does not contain ‘oranges’.”

If you want to figure out if a bash array contains multiple elements, use if [[ ${array[@]} =~ $element ]] syntax inside the for loop instead of if [[ "$i" == "$element" ]].

4. Using “printf” and “grep”

The combination of printf and grep commands can be used to check whether the specified element exists in the bash array.

You can use '%s\0' in printf which separates the array elements with null characters as delimiters. The -q (quiet mode) option of the grep command is used along with the -w to suppress the normal output and find the exact match. Check the script below to see how it works:

#!/bin/bash
array=("grapes" "potatoes" "bananas" "apples")
element="bananas"
if printf '%s\0' "${array[@]}" | grep -qw "$element"; then
  echo "Array element '$element' exists"
else
  echo "Array element does not exist"
fi
EXPLANATION

If a match is found, the condition in the if statement becomes true, and the if code block is executed; otherwise, the code block within the else statement is executed.

checking if an element exists in bash array using printf and grep

You can see in the image that it displays “Array element “bananas” exists” because it’s defined in the bash array.

5. Using “${array[@]/pattern/}” Syntax With Not Equal To “!=” Operator

Using ${array[@]/pattern/} syntax with != operator is another way to find the desired element from the bash array. The != checks the inequality between the elements.

The expression if [[ "${array[@]/$element/}" != "${array[@]}" ]] returns true if the element which is removed from the bash array, is different from the original array. Here’s a bash script for this:

#!/bin/bash
array=("grapes" "potatoes" "bananas" "apples")
element="apples"
if [[ "${array[@]/$element/}" != "${array[@]}" ]]; then
    echo "Array contains '$element'."
else
  echo "Array does not contain '$element'."
fi
EXPLANATION

If the specified element “apples” is in the array, the condition is true, and it prints “Array contains ‘apples’.” But if “apples” is not in the array, the condition is false, and it prints “Array does not contain ‘apples’.”. If the specified element is “appl”, it will print the “Array contains ‘appl’.”  as it is a substring of the “apples”.

checking if an element exists in bash array using not equal to operator

The script executes “Array contains ‘apples’.” as the condition is true.

6. Using “=” Operator

To check if an array contains an element, you can write [[ " ${array[*]} " = *"$element"* ]] syntax inside the if condition with equal to operator =. It checks if the array contains the specified element, with wildcards allowing for the element to appear anywhere in the string. Check the full script below:

#!/bin/bash
array=("grapes" "potatoes" "bananas" "apples")
element="apples"
if [[ " ${array[*]} " = *"$element"* ]]; then
    echo "Array contains '$element'."
    exit 0
else
    echo "Array does not contain '$element'."
    exit 1
fi
EXPLANATION

Here when the condition is true, it will execute exit status 0 and print “Array contains $element”. Otherwise, it will print the else block statement with exit status 1.

checking if an element exists in bash array using equal to operator

This picture shows that Array contains ‘apples’. as “apples” is in the bash array.

Conclusion

I hope this article helps you to understand how to check if an array contains an element in bash. Throughout the writing, I’ve discussed 6 different ways to check array elements. Just make sure to follow each method closely & choose the best one according to your needs & comfort. Good luck!

People Also Ask

How to declare an array?

To declare an array, you need to give it a name, and then use an equal sign to refer to it. There should be no spaces around the equal sign, and the array should be enclosed in brackets ‘()’. You have to use quotes to write strings but without commas. Here’s an example:

array=("apple" "banana" "cherry" "date" "elderberry")

How to remove an element from an array?

To remove an element from an array, you can create a new array by slicing the original array to exclude the element you want to remove. Here’s a bash script to remove “orange” from the myArray.

#!/bin/bash
myArray=("apple" "orange" "banana" "grape")

# Element to remove (e.g., "orange")
elementToRemove="orange"

# Create a new array excluding the element to remove
newArray=("${myArray[@]/$elementToRemove}")

# Print the modified array
echo "${newArray[@]}"

How can I determine array length in Bash?

To determine array length (number of elements in an array), you can use array_length=${#array[@]} syntax. Here’s an example script below:

#!/bin/bash
array=("apple" "banana" "cherry" "date" "elderberry")

# Get the length of the array
array_length=${#array[@]}

# Print the array length
echo "Array length: $array_length"

This script gives you an output of 5 as the array contains 5 elements.

How to check if an array is empty in bash?

To check if an array is empty, you can use [[ -z "${array[@]}" ]] syntax within the if condition. The -z option checks if the array is empty. Check the full script below:

#!/bin/bash
array=()
if [[ -z "${array[@]}" ]]; then
    echo "array is empty"
fi

How to check if an array contains multiple elements?

To check the presence of multiple elements in a bash array, you can use regex within a for loop. Here’s an example:

#!/bin/bash
array=("grapes" "potatoes" "bananas" "apples")

# Specify elements to check for
elements=("potatoes" "oranges" "grapes")

# Iterate over each element and check its existence in the array
for element in "${elements[@]}"; do
  if [[ ${array[@]} =~ $element ]]; then
    echo "Array element '$element' exists"
  else
    echo "Array element '$element' does not exist"
  fi
done

This script checks if the elements “potatoes” “oranges” and “grapes” exist in the main array. If an element is found in the array, it will print “Array element ‘element’ exists”; otherwise, it will print “Array element ‘element’ does not exist.”.

How to check if a bash array is not empty?

To check if an array is not empty, you can use [[ -n "${array[@]}" ]] syntax within the if condition. The -n option checks if the array is not empty. Check the full script below:

#!/bin/bash
array=("apple" "banana" "cherry" "date" "elderberry")
if [[ -n "${array[@]}" ]]; then
    echo "array is not empty"
fi

Related Articles


<< Go Back to If Else in Bash | Bash Conditional Statements | Bash Scripting Tutorial

5/5 - (5 votes)
Mitu Akter Mou

Hello, This is Mitu Akter Mou, currently working as a Linux Content Developer Executive at SOFTEKO for the Linuxsimply project. I hold a bachelor's degree in Biomedical Engineering from Khulna University of Engineering & Technology (KUET). Experiencing new stuff and gathering insights from them seems very happening to me. My goal here is to simplify the life of Linux users by making creative articles, blogs, and video content for all of them. Read Full Bio

2 thoughts on “Check If Array Contains an Element in Bash [6 Methods]”

  1. The first method does NOT check whether the element is in the array. It checks whether the element is a substring of any element of the array. Meaning if you set element = “potato” and the array contains “potatoes” it would match. I haven’t even looked at the other methods.

    Reply
    • Yes Teo, you are right. As the “potato” is a substring of an array element, it will print that the array element contains “potato”. Actually, Method 1,5, and 6 find the array element by partial matching. If you want to check whether the exact element is in the array, try method 2, 3, or 4.

      Reply

Leave a Comment