Bash Scripting
  • scripting list
  • How to Make Bash Script Executable Using Chmod
  • Shell Script to Check Linux Server Health
  • How to Concatenate String Variables in Bash [Join Strings]
  • How to Do Bash Variable Substitution (Parameter Substitution)
  • Bash Parameter Expansion with Cheat Sheet
  • Bash getopts with Examples
  • How to Pass all Arguments in Bash Scripting
  • Bash Function Return Value
  • Bash Loop Through Lines in a File
  • Bash readarray with Examples
  • Bash let with Examples
  • Bash expr with Examples
  • Bash read password
  • Bash for Loop Range Variable
  • Bash Arrays Explained
  • Ways to Find Bash Array Length
  • Bash Split String by Delimiter
  • Bash if Options
  • Bash If Statements for String Comparison
  • Debugging Techniques for Bash Scripts
  • Determining if a Bash String is Empty
  • Bash if Statement with Multiple Conditions
  • Meaning of Shebang in Bash Scripts
  • How to Comment Code in Bash Script
  • How to Read CSV File in Bash
  • Bash Scripting: How to Check if File Exists
  • Bash If Else Statements: Examples and Syntax
  • Bash Scripting: How to Check if Directory Exists
  • Bash eval Command with Examples
  • How to Use Sleep Command in Bash Scripting
  • Bash Associative Arrays with Examples
  • Bash Script for Counting Lines in a File
  • How to Use While Loop in Bash for Efficient Scripting
  • Bash basename Command with Examples
  • How to Create Multiline Strings in Bash
  • How to Use Bash if With && Operator
  • 50 Bash Script Examples to Kickstart Your Learning
  • Case statement in Bash Shell Scripting
  • Trimming White Space in Bash
  • How to Extract Filename from Absolute Path in Bash
  • How to Get Directory Path in Bash
  • Extract Extension from File Path in Bash
  • Extract Filename without Extension from Full Path in Bash
  • Bash for Each File in a Directory
  • Bash for Loop with Array
  • Bash Continue – Using with for Loop
  • Bash Backticks vs Dollar Parentheses $()
  • How to Assign Variable in Bash
  • How to Assign Variable in Bash
  • Bash Division Explained
  • Bash Modulo (Division Remainder)
  • Bash While Read Line by Line
  • Bash shift Command
  • Bash Looping Through Array of Strings
  • Bash read Command with Examples
  • Bash Check Empty Array
  • Using Bash For Loops to Iterate Over a List of Strings
  • Bash Break – Using with For Loop
  • How to Use seq With for Loop in Bash
  • How to Use $@ in Bash Scripting
  • Get the Current Script Directory in Bash
Powered by GitBook
On this page
  • Check if array is empty
  • Conclusion

Bash Check Empty Array

PreviousBash read Command with ExamplesNextUsing Bash For Loops to Iterate Over a List of Strings

Last updated 1 year ago

Knowing whether the array is empty or can be significant especially when it comes to populating the elements with the data. An array can be considered empty if it doesn’t have any elements or it has been declared but is still uninitialized.

Check if array is empty

"If statements", also referred to as conditional statements allow us to make decisions in our Bash scripts. We can check if an array is empty by finding its length and using it inside the condition. The condition in the if statement is evaluated based on the exit status. An exit status of 0 implies that it completed successfully.

We can find whether an array is empty or not using the length of the array and use it with the Bash if-then-else statement.

Using @

We can find the number of members in the array using the @ symbol as follows:

Example:

#!/bin/basharr=("Pushkin" "Tolstoy" "Chekhov" "Gorky" "Turgenev") #non-empty arrayif [ ${#arr[@]} -gt 0 ]then echo Not emptyelse echo emptyfi arr2=() #empty arrayif [ ${#arr2[@]} -gt 0 ]then echo Not emptyelse echo emptyfi

The presence of @ expands all the elements of the array. Prefixing the # symbol to that array variable finds the number of members present. We have taken 2 arrays with one of them being declared as well as populated with values The other array is just declared. The if statement will check the size of the array in both the cases and decide whether to execute the if block or the else block. Based on that it will echo accordingly.

Using *

We can also find the array length using the @ symbol as follows:

Example:

#!/bin/basharr=("Pushkin" "Tolstoy" "Chekhov" "Gorky" "Turgenev")if [ ${#arr[*]} -gt 0 ]then echo Not emptyelse echo emptyfi arr2=() #empty arrayif [ ${#arr2[*]} -gt 0 ]then echo Not emptyelse echo emptyfi

The * symbol is a quantifier which means "match zero or more". When placed inside the array variable it pulls all the array members. Just like we did last time, prefixing the # symbol to that array variable will give us the array length. Using it with the if statement, helps decide whether the bash array is empty or not.

Using grep

The grep command is an extremely useful tool to filter searches. The keywords can be strings, particular patterns of characters, or regular expressions.

Example:

#!/bin/basharr=("Pushkin" "Tolstoy" "Chekhov" "Gorky" "Turgenev")result=$(echo ${arr[@]} | grep -o " " | grep -c " ")if [ $result -gt 0 ]then echo Not emptyelse if [ ! -z "${arr[0]}" ] then echo Not empty else echo empty fifi arr2=() #empty arrayresult=$(echo ${arr2[@]} | grep -o " " | grep -c " ")if [ $result -gt 0 ]then echo Not emptyelse if [ ! -z "${arr2[0]}" ] then echo Not empty else echo empty fifi

We know that Bash splits the array into a series of words which are separated by spaces. Hence, we are determining the number of blank spaces with the help of the grep command, using a blank space as the pattern for grep. The grep command used with -o option only pulls the matching pattern, which is a space. The -c option only prints the count of the lines that match the pattern.

Using wc command

The wc command is an equally helpful tool to get count of words, characters or lines.

Example:

#!/bin/basharr=("Pushkin" "Tolstoy" "Chekhov" "Gorky" "Turgenev")result=`echo ${arr[@]} | wc -w`if [ $result -gt 0 ]then echo Not emptyelse echo emptyfi

We have taken the same approach which we did with grep to find the array size, which is to count the number of words in the array. The result of the echo command is sent as input to the wc command using the pipe operator. This command when used with the -w option counts the number of words available in the provided input. If the result is greater than zero, the array is not empty.

Conclusion

  • Prefixing the # symbol to that array variable returns the array size.

  • An array is empty if it doesn’t contain any element.

  • There are different approaches to check if the array is empty.

Check if array is empty with grep
Check if array is empty using *
Check if array is empty using @
Check if array is empty with wc