How to Check if the String is Empty in Bash

Finding if a string or variable that contains a string is empty or not is one of the core features of data validation in bash. It is also important for performance improvement of code, logic control, and avoiding errors. 

In this guide, I will go through various methods to check if a string is empty or not in bash. 

Table of Contents:

Strings and Empty Strings in Bash

A string is a set of characters and special characters enclosed in single () or double quotes (“”). A simple example is as follows:

var="This is a string in bash"

Here, This is a string in bash is string assigned to a var variable. 

In bash scripting, a variable is considered to be an empty string if it is assigned an empty value using quotes or no value at all. There are three ways to assign an empty string in bash.

i. Using single quotes:

var=''

ii. Using double quotes:

var=""

iii. Without using quotes:

var=

It is important to note that an empty string without quotes is valid but not preferred.

How do I Check if a String is Empty in Bash

A range of operators in the bash are dedicated to determining the emptiness of a string, including -z, -n, ==, and != operators. Additionally, one can use parameter expansion as another method to get the same output. 

The following sections will explore several common methods to determine if a string is empty in bash:

1. Using the -z Operator

In bash -z is a string comparison operator that returns true if the string is empty. 

#!/bin/bash
str=""if [ -z "$str" ]then echo "The string does not contain content"else echo "The string contains content"fi

In the provided script, where the string variable is assigned an empty string, the condition will indeed evaluate to true.

Image 706

The single square brackets with the if condition make the script portable because they are compatible with POSIX-compliant Unix and Unix-like operating systems, including Linux.

The -z operator considers a string containing whitespace characters non-empty because it evaluates the length of the string to determine emptiness. So, if the string is declared white space, the string length will be non-zero. Luckily, it can be handled easily either using parameter expansion or tr command.

#!/bin/bash
str=" "str=$(echo "$str" | tr -d ' ')if [ -z "$str" ]then echo "The string variable holds no text"else echo "The string variable holds text"fi

Note: The -z is the string comparison operator, and it only checks if the string is null or empty, it does not check if there are other values such as numbers. Therefore, ensure that the variable being checked by -z is a string.

2. Using the -n Operator

The -n operator is also a string comparison operator which returns false if the string is empty.

#!/bin/bash
str=""if [ -n "$str" ]then echo "The string holds text"else echo "The string does not hold text"fi

3. Using the == Operator

The equal (==) is a comparison operator primarily used to compare strings in bash. The returns true if two strings possess identical content, meaning every character in the first string matches its corresponding character in the second string.

#!/bin/bash
str=""if [ "$str" == "" ]then echo "The string is blank"else echo "The string is not blank"fi

The output shows that the string is empty because the if statement returns true, so the instruction in the if block is executed.

4. Using the != Operator

The != is also known as the not equal operator used to compare strings in bash. It is opposite to the equal operator. It returns true if two strings are unequal. 

#!/bin/bash
str=""if [ "$str" != "" ]then echo "The declared string contains text"else echo "The declared string contains no text"fi

The output shows that the string is empty because the if condition will return false and the instruction in the else block will be executed. 

5. Using the Parameter Expansion

The parameter expansion feature allows you to manipulate the value of the variable in bash. 

#!/bin/bash
str=""if [ "${#str}" -eq 0 ]then echo "The string is null"else echo "The string is not null"fi
Image 721

Note that, we use the -eq operator which is typically used to compare integers. This is because the ${#str} is returning the string length in integers.

Another way to find whether a string variable is empty or not using parameter expansion is given below:

#!/bin/bash
str=""if [ "${str:-}" == "" ]then echo "The string has no data"else echo "The string has data"fi

If the string variable is set, ${str:-} will expand to the string value. If it is set to null or empty, ${str:-} will also expand to an empty string (“”) as demonstrated in the following image.

Check if a String is Empty with Double Square [[]] Brackets

The double square brackets ([[]]) are the enhanced version of single square brackets which are introduced in Ksh. They can also be used in Bash and Zsh scripting; however, it is important to note that they are not compliant with POSIX. 

#!/bin/bash
str=""if [[ ! $str ]]then echo "The string has no data"else echo "The string has data"fi

In the script, the ! $str variable is evaluated as true if the string is empty.

The -z operator can be used with the double square method.

if [[ -z $str ]]

The double square brackets have several advantages: such as the support pattern matching without using quotes, arithmetic comparison, and regular expression.

Note: Double square brackets are not universal in Unix and Unix-like operating systems, so only use them when your script does not need to be portable.

Check if a String is Empty with the test Command

The test command in bash is used to evaluate the expression. It essentially allows you to remove the square brackets with the if statement. The example is as follows:

#!/bin/bash
str=""if test ! $strthen echo "The string is empty"else echo "The string contains the text"fi

Other methods to use the test command are as follows:

if test -z $str

Or:

if test "${str:-}" == ""if test "$str" != ""if test "${#str}" -eq 0

Check if a Variable is Set in Bash

In bash, the -v operator serves as a mechanism for verifying whether a variable is declared or not. It is important to note that the -v does not check if a variable is empty or not, it checks if the variable is declared or not. 

#!/bin/bash
if [ -v var ]then echo "Variable is set"else echo "Variable not set"fi

The output images show that the variable var is not set because it is not declared.

Check if an Element in an Array is Empty in Bash

In bash, the elements of an array can be expanded as space-separated strings. Here is an example:

#!/bin/bash
array=("linux" "" "ubuntu" "example")
for i in "${array[@]}" do  if [ -z "$i" ] then echo "An empty element is found" break fidone

In the above code, the ${array[@]} is expanded as a single string, and -z checks whether the array is empty or not.

Check if an Array of Strings Containing Alphanumeric or Numeric Elements in Bash

Using a regular expression, a string of numbers can be checked from an array. The example is as follows:

#!/bin/bash
array=("linux" "ubuntu24" "24" "noble" "numbat")
for i in "${array[@]}"do if [[ "$i" =~ [a-zA-Z] ]] && [[ "$i" =~ [0-9] ]] || [[ "$i" =~ ^[0-9]+$ ]] then echo "Alphanumeric or numeric element found" exit 0 fidone
echo "No alphanumeric or numeric element found"exit 1

Check if a Text File is Empty in Bash

In bash, the -z operator can also be used to check if a text file is empty or not. The example is as follows:

#!/bin/bash
echo "Enter file name"read file
if [ -z "$(cat ${file})" ]then echo "File is empty"else  echo "File is not empty"fi

Check if the JSON File String is Empty in Bash

The JSON file contains strings of key-value pairs. The -z operator can also be employed to check if a specific field of a JSON file is empty or not.

Let’s understand it with an example.

#!/bin/bash
json_file_path="/home/ilf/file.json"value=$(jq -r '.version' "$json_file_path")
if [ -z "$value" ]then    echo "The field is empty or does not exist in the JSON file"else    echo "The field is not empty. Its value is: $value"fi

The version field of the JSON file is empty as shown in the above output. The primary function of the jq command in the above script is to extract the value associated with a particular field within a JSON file.

Conclusion

In bash empty string handling is important especially to validate the user inputs and other data. 

In Bash, different methods such as -z, -n, ==, and != operators can also be used for string comparison. In this guide, we covered all the methods to check if the string is empty or not and discussed different use cases and scenarios.