How to Check if a Bash Array is Empty: Practical Methods and Code Examples


4 views

In Bash scripting, arrays are zero-based indexed variables that can hold multiple values. Unlike regular variables, checking their emptiness requires special handling because:

  • They have both indices and elements
  • The standard -z test doesn't work directly
  • Different Bash versions handle array declarations differently

The most reliable way is to check the array's length:

error_messages=()  # Empty array

if [ ${#error_messages[@]} -eq 0 ]; then
    echo "Array is empty"
else
    echo "Array contains ${#error_messages[@]} elements"
fi

For compatibility with older Bash versions (pre-4.0):

if [[ -z "${error_messages[@]}" ]]; then
    echo "Array is empty"
fi

Note: This works only for truly empty arrays, not sparse arrays.

For arrays with empty indices but declared elements:

declare -a sparse_array=([3]="error1" [5]="error2")

if [[ ${#sparse_array[@]} -gt 0 ]]; then
    echo "Array has elements, but might be sparse"
fi

Here's how you might implement error collection in a script:

#!/bin/bash

errors=()

# Simulate some operations that might generate errors
if [[ $RANDOM -gt 20000 ]]; then
    errors+=("Disk space low")
fi

if [[ $RANDOM -lt 5000 ]]; then
    errors+=("CPU overload detected")
fi

# Check if any errors were collected
if [[ ${#errors[@]} -eq 0 ]]; then
    echo "All operations completed successfully"
    exit 0
else
    echo "Errors occurred:"
    printf " - %s\n" "${errors[@]}"
    exit 1
fi

For large arrays, prefer the length check method as it's O(1) complexity. The element expansion method requires creating a temporary string which can be expensive for large arrays.

  • Explicitly declare arrays with declare -a for clarity
  • Use length checks for portability across Bash versions
  • Document your array usage with comments
  • Consider using associative arrays for error codes if needed

In Bash scripting, arrays are zero-based indexed data structures that can hold multiple values. Unlike regular variables, arrays require special syntax for manipulation and checking their state.

The common -z test operator works for regular variables but fails with arrays because:


# This won't work as expected
if [ -z "${array[@]}" ]; then
    echo "Empty"
fi

The array expansion ${array[@]} always produces output when expanded, even for empty arrays.

Method 1: Check Array Length

The most straightforward approach is to check the array's length:


if [ ${#array[@]} -eq 0 ]; then
    echo "Array is empty"
else
    echo "Array contains ${#array[@]} elements"
fi

Method 2: Using Parameter Expansion

This method checks if the first element is unset:


if [[ ! -v array[0] ]]; then
    echo "Array is empty"
fi

Method 3: Combined Check

For maximum reliability in all Bash versions:


if [[ ${#array[@]} -eq 0 || ( ${#array[@]} -eq 1 && -z "${array[0]}" ) ]]; then
    echo "Array is empty"
fi

Here's how you might implement this in an error collection script:


#!/bin/bash

errors=()

# Simulate adding errors
if [ some_condition ]; then
    errors+=("Error 1 occurred")
fi

# Check if errors array is empty
if [ ${#errors[@]} -gt 0 ]; then
    echo "Script completed with ${#errors[@]} errors:"
    printf '%s\n' "${errors[@]}"
    exit 1
else
    echo "Script completed successfully"
    exit 0
fi
  • Bash versions before 4.2 might handle empty arrays differently
  • Sparse arrays (with unset indices) require special handling
  • Associative arrays (Bash 4+) use the same checking methods

For scripts processing large arrays, the length check (${#array[@]}) is the most efficient method as it doesn't require expanding array elements.