Check If Bash Array Contains [Letters, Numbers, or Values]

In Bash Scripting, working with arrays is a common task, and at times, you may need to determine whether an array contains letters, numbers, or a combination of both. This ensures data consistency and performs targeted operations validating data integrity.

In this writing, I will discuss 3 different cases with practical Bash script examples to check if an array contains elements in the form of letters, or numbers, or if a user-specified string exists in that array. So let’s get started!

1. Check If Bash Array Contains Only Numbers

Determining whether an array contains numbers involves checking if each element in the array is a numeric value. The if conditional and Bash for loop checks if the elements are only numbers by using the regex pattern ^[0-9]+$. The complete syntax is if ! [[ $elem =~ ^[0-9]+$ ]] where the =~ is the regex operator and it checks if the current value stored by $elem contains only numeric characters defined by the pattern ^[0-9]+$.

Let’s see an example to check if an array contains only numbers in Bash:

#!/bin/bash

my_array=(1 25 3 "prem")
flag=true

 #Displaying elements of my_array
echo "Elements of array 1: ${my_array[@]}"

# Checking if my_array contains only numeric characters
for elem in "${my_array[@]}"; do
    if ! [[ $elem =~ ^[0-9]+$ ]]; then
        flag=false
        break
    fi
done

if $flag; then
    echo "Array 1 contains only numeric characters"
else
    echo "Array 1 contains a mix of characters"
fi
echo
my_array2=(1 25 3)
flag=true

# Displaying elements of my_array2
echo "Elements of array 2: ${my_array2[@]}"
# Checking if my_array2 contains only numeric characters
for elem in "${my_array2[@]}"; do
    if ! [[ $elem =~ ^[0-9]+$ ]]; then
        flag=false
        break
    fi
done

if $flag; then
    echo "Array 2 contains only numeric characters"
else
    echo "Array 2 contains non-numeric characters or a mix of characters"
fi
EXPLANATION

The above code works upon 2 arrays to fact-check if they contain elements containing only numeric characters. The for loop iterates over the elements and the condition if ! [[ $elem =~ ^[0-9]+$ ]] validates if any element does not consist of numbers and returns a message according to the value of the flag variable which keeps track of the checking. Here, flag= true denotes that the array has only numbers as elements. Otherwise flag is set to false notifying that the array contains elements with a mix of characters.

check if bash array contains numbersHere, the script has 2 outputs. In the case of the 1st array, it outputs Array 1 contains a mix of characters because the array has 1 non-numeric element (prem). Contrarily, it prints Array 2 contains only numeric characters due to the perfect matching of patterns.

NOTE: The Bash array treats each element as a string even in the array, my_array2=(1 25 3). That’s why the if statement uses the regex pattern ^[0-9]+$ for numerical character-based pattern matching.

2. Check If Bash Array Contains Only Letters

To check if a Bash array contains elements consisting of only alphabetical characters, you can use the if conditional with the regex pattern ^[[:alpha:]]+$ ]] in the syntactical format: if ! [[ $elem =~ ^[[:alpha:]]+$ ]]. Here, the regex pattern ^[[:alpha:]]+$ represents the alphabet character class and matches each array element with the class to determine if the entire array stores only alphabetic strings as elements.

Here’s a script to check if an array stores only letters:

#!/bin/bash

arr=("hello" "world" "universe" "multi")

#print the array
echo "elements: ${arr[@]}"
echo

#set flag to keep track
flag=true

#for loop with if conditionals to check 
for elem in "${arr[@]}"; do
    if ! [[ $elem =~ ^[[:alpha:]]+$ ]]; then
        flag=false
        break
    fi
if $flag; then
    echo "Array contains only letters"
else
    echo "Array contains a mix of characters"
fi
EXPLANATION

In the above code, the if conditional statement if ! [[ $elem =~ ^[[:alpha:]]+$ ]] along with the  Bash for loop checks whether arr stores any letter-based elements (alphabetical characters). If any element contains characters other than alphabets, flag is set to false and the code executes the else block. Otherwise, the echo command prints a message of the if block.

check if array has elements of lettersThe above script outputs Array contains only letters since the elements of the array (hello world universe multi) only consist of alphabetical characters.

3. Check If Bash Array Contains a Specific Value

It is possible to check if a bash array contains a specific value (a specific string) and the easiest method is to use a regex pattern with the Bash if conditional statement, if [[ ${array[@]} =~ $element ]]. The regex pattern operator =~ finds the match of the specified value stored by $element.

Here’s how to check if an array in Bash has a specific value:

#!/bin/bash

#the array declaration with elements
superHero=("ironMan" "hulk" "batman" "spidy")
Element_2_search="batman"

#print the array
echo "the array elements: ${superHero[@]}"

#check if the element is in the array 
if [[ ${superHero[@]} =~ $Element_2_search ]]
then
  echo "Array element $Element_2_search exists"
else
  echo "Array element does not exist"
fi
EXPLANATION

Here, after the creation of the superHero array, the if statement if [[ ${superHero[@]} =~ $Element_2_search ]] checks if the array has an element named batman. Since, the array contains the value, the echo command prints Array element batman exists. Otherwise, it would have printed the message from the else block.

check if array contains a specified stringThe script outputs Array element batman exists since the array has the element batman.

NOTE: To learn more on how to check if an array contains a specific value, read the article: Check If an Array Contains an Element in Bash

Conclusion

In conclusion, the above tutorial discusses some simple methods employing Bash for loops and if conditional statements to check if an array consists exclusively of letters or numbers, or even verify the presence of specified elements. After going through this article, I hope you gain an understanding of robust data validation and manipulation within Bash arrays to level up your scripting capabilities. Happy scripting!

Frequently Asked Questions

What is an array in Bash?

A Bash array is a data structure that stores elements in an indexed way. Unlike arrays in other programming languages, bash array can store different types of elements. For instance, Bash arrays store both strings and numbers.

What are Array Elements?

Array elements refer to the individual data values that the array stores. These are discrete values that can be accessed, modified, or even processed individually or collectively within the array data structure. Array elements can be of various types, such as strings, numbers, or even other arrays. For instance, the array numbers=(1 2 3) has 3 elements: 1 2 3.

Can I iterate over the elements of an array in Bash?

Yes, you can use the for loop to iterate over the array elements. For example, to iterate over an array named wiki=(pedia leaks media):

for name in ${wiki[@]}
    do
        echo $name
done

Output:

pedia

leaks

media

How do I check if an array is empty in Bash?

To find whether an array is empty or not, determine the length and use it within if-else statements like the following:

array=()   #an empty array

if [ ${#array[@]} -gt 0 ]
then
echo “array is not empty
else 
echo "empty array"
fi

Output:

empty array since the array has no elements and the array length is 0.

How to print a Bash Array?

To print an array, use the length expression command echo ${array[@]}. You can also use length expression ${nums[*]} prefixing with the echo command. For example, to print an array named nums=(1 2 3 4), the command is: echo ${nums[@]} or echo ${nums[*]}.

Related Articles


<< Go Back to Elements of Bash Array | Bash Array | Bash Scripting Tutorial

Rate this post
Md Masrur Ul Alam

Assalamu Alaikum, I’m Md Masrur Ul Alam, currently working as a Linux OS Content Developer Executive at SOFTEKO. I completed my Bachelor's degree in Electronics and Communication Engineering (ECE)from Khulna University of Engineering & Technology (KUET). With an inquisitive mind, I have always had a keen eye for Science and Technolgy based research and education. I strongly hope this entity leverages the success of my effort in developing engaging yet seasoned content on Linux and contributing to the wealth of technical knowledge. Read Full Bio

Leave a Comment