Bash Check if String is Empty


Bash Check if String is Empty

In Bash scripting, checking if a string is empty is useful for various string validation and conditional tasks.


Syntax

if [ -z "$string" ]; then
    # commands if string is empty
fi

The basic syntax involves using the -z operator within an if statement to check if the string is empty.


Example Bash Check if String is Empty

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

1. Check if a Variable is an Empty String

This script checks if the variable str is an empty string and prints a corresponding message.

#!/bin/bash

str=""

if [ -z "$str" ]; then
    echo "The variable str is an empty string."
else
    echo "The variable str is not an empty string."
fi

In this script, the variable str is initialized with an empty string. The if statement uses the -z operator to check if str is an empty string. If true, it prints a message indicating that str is an empty string. Otherwise, it prints a different message.

Check if a variable is an empty string in Bash

2. Check if a User Input String is Empty

This script prompts the user to enter a string and checks if the entered string is empty, then prints a corresponding message.

#!/bin/bash

read -p "Enter a string: " str

if [ -z "$str" ]; then
    echo "You entered an empty string."
else
    echo "You entered: '$str'"
fi

In this script, the user is prompted to enter a string, which is stored in the variable str. The if statement uses the -z operator to check if str is an empty string. If true, it prints a message indicating that the user entered an empty string. Otherwise, it prints the entered string.

Check if a user input string is empty in Bash

3. Check if a String from a Command Output is Empty

This script checks if the output of a command stored in the variable output is an empty string and prints a corresponding message.

#!/bin/bash

output=$(ls non_existent_directory 2>/dev/null)

if [ -z "$output" ]; then
    echo "The command output is an empty string."
else
    echo "The command output is: '$output'"
fi

In this script, the variable output is assigned the result of a command that lists a non-existent directory, redirecting any errors to /dev/null. The if statement uses the -z operator to check if output is an empty string. If true, it prints a message indicating that the command output is an empty string. Otherwise, it prints the command output.

Check if a string from a command output is empty in Bash

Conclusion

Checking if a string is empty in Bash is a fundamental task for string validation and conditional operations in shell scripting. Understanding how to check for empty strings can help you manage and validate strings effectively in your scripts.