Bash Check if Array is Empty



Bash Check if Array is Empty

In Bash scripting, checking if an array is empty is useful for various tasks that require validating whether an array has elements.


Syntax

if [ ${#array[@]} -eq 0 ]; then
    # commands if array is empty
fi

The basic syntax involves using ${#array[@]} to get the length of the array and checking if it is equal to 0.


Example Bash Check if Array is Empty

Let's look at some examples of how to check if an array is empty in Bash:

1. Check if a Simple Array is Empty

This script initializes an empty array and checks if it is empty, then prints a corresponding message.

#!/bin/bash

array=()
if [ ${#array[@]} -eq 0 ]; then
    echo "The array is empty."
else
    echo "The array is not empty."
fi

In this script, the array variable array is initialized as an empty array using (). The if statement uses ${#array[@]} to check if the length of the array is equal to 0. If true, it prints a message indicating that the array is empty. Otherwise, it prints a different message.

Check if a simple array is empty in Bash

2. Check if an Array with Elements is Empty

This script initializes an array with elements and checks if it is empty, then prints a corresponding message.

#!/bin/bash

array=("element1" "element2" "element3")
if [ ${#array[@]} -eq 0 ]; then
    echo "The array is empty."
else
    echo "The array is not empty."
fi

In this script, the array variable array is initialized with the elements 'element1', 'element2', and 'element3'. The if statement uses ${#array[@]} to check if the length of the array is equal to 0. If true, it prints a message indicating that the array is empty. Otherwise, it prints a different message.

Check if an array with elements is empty in Bash

3. Check if an Array from User Input is Empty

This script initializes an array with elements from user input and checks if it is empty, then prints a corresponding message.

#!/bin/bash

array=()
while true; do
    read -p "Enter an element (or 'done' to finish): " element
    if [ "$element" == "done" ]; then
        break
    fi
    array+=("$element")
done
if [ ${#array[@]} -eq 0 ]; then
    echo "The array is empty."
else
    echo "The array is not empty."
fi

In this script, the array variable array is initialized as an empty array using (). The user is prompted to enter elements, which are added to the array using the += operator. When the user types 'done', the loop exits. The if statement uses ${#array[@]} to check if the length of the array is equal to 0. If true, it prints a message indicating that the array is empty. Otherwise, it prints a different message.

Check if an array from user input is empty in Bash

Conclusion

Checking if an array is empty in Bash is a fundamental task for validating whether an array has elements in shell scripting. Understanding how to check for empty arrays can help you manage and manipulate arrays effectively in your scripts.