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
  • Bash: Empty Checks on String
  • Practical example
  • Conclusion

Determining if a Bash String is Empty

PreviousDebugging Techniques for Bash ScriptsNextBash if Statement with Multiple Conditions

Last updated 1 year ago

When writing bash scripts, we generally encounter strings. Many times, the script may involve unset or empty string variables, holding simply a blank value which indicates that the variable does not contain anything. We can use the if statement to check if it is indeed empty so as to develop conditions and alternate conditions for if-then-else blocks.

Bash: Empty Checks on String

At times it becomes essential to check if a variable, holding a string value, is set or not. This step is important for data validations. Unfortunately, Bash doesn’t have any built-in tools to check for empty variables. However, we can still verify if the variables are empty. In this article, we will focus on different ways to use the Bash if statement to check if the string is empty or not. We will use the square brackets [] with the if condition. One important thing we need to remember is to include spaces around the square brackets.

Using the assignment operator

The most basic method of checking whether the string is empty or not is to use the assignment operator (=). This approach can be seen in every programming language.

Example

var1="Football"var2=""if [ "$var1" = "" ]; then echo true; else echo false; fiif [ "$var2" = "" ]; then echo true; else echo false; fi

Whenever we initialize a variable with a string value, we surround the value with double quotes ("..."). An empty variable or string will not have any value between these quotes. Hence, to check for an empty string, we compare the value of the variable with the empty string ("").

If the condition is met, the "then" part executes and echoes true on the screen. If it doesn’t, the "else" part gets called and echoes the string false. The if-else statement ends with the "fi" keyword.

Using -z

The -z option is a string comparison operator which can be used to check empty strings and variables.

Example

var1="Football"var2=""if [ -z "$var1" ]; then echo true; else echo false; fiif [ -z "$var2" ]; then echo true; else echo false; fi

The -z option is a string comparison operator used to check null strings in a Bash. It returns false whenever the string contains one or more characters. It will return true, if the string is empty.

We have two string variables, one is empty and the other one is not. In the if-else statement we perform the empty string check using the "-z" option within the square brackets. If the condition is satisfied and the string is empty, the first part executes, displaying true. However, if the string is non-empty, the else part executes and we get to see a false on the screen.

Using -n

Just like the previous option, we can also use the -n option.

Example

var1="Football"var2=""if [ -n "$var1" ]; then echo false; else echo true; fiif [ -n "$var2" ]; then echo false; else echo true; fi

The "-n" option is a string comparison operator used to check null strings in a Bash. It returns true whenever the string contains one or more characters. It will return false, if the string is empty. It works exactly opposite to the -z option. If the comparison is done using -n, then for empty strings, it will go to the else part of the condition unlike the -z which goes to the if part. In other words we can say, -n flag performs a not-empty check.

Check for unset variables

We can also employ the unset method to check whether the string is empty or not.

Example

var1="Football"echo "With var1: ${var1+x}"echo "With var3: ${var3+x}"if [ "${var1+x}" ]; then echo true; else echo false; fiif [ "${var3+:x}" ]; then echo true; else echo false; fi

We have used the ${variable+value} to set another value.

We can see that the result is true only when the variable is not declared or is unset. The echo statement only expands the first case, when the variable is set. In this approach we make bash perform the parameter expansion using the curly brackets ({}). When we pass the variable name with the plus operator, the value gets ignored if the variable is unset.

Using the string length

Another solution is to find the length of the variable holding the string. If it is zero, it's safe to say that the string is empty.

Example

var1="Football"var2=""if [ ${#var1} -eq 0 ]; then echo true; else echo false; fiif [ ${#var2} -eq 0 ]; then echo true; else echo false; fi

Prefixing the variable using the # symbol returns the length of the string held by that variable. Once we have the length, it becomes a simple integer comparison where the value is compared to zero. For an empty string, its length will be zero and the if block will get executed.

Practical example

We can put everything we learned so far in the following example:

#!/bin/bashemptyCheck(){ input=$1 if [ "$input" == "unset" ] #For 3rd case to empty then unset input fi echo "var1 is currently $input" #condition1 if [ -z "${input}" ] then echo "Unset or empty string" fi #condition2 if [ -z "${input+set}" ] then echo "Unset" fi #condition3 if [ -z "${input-unset}" ] then echo "Empty string" fi #condition4 if [ -n "${input}" ] then echo "Non-empty string" fi #condition5 if [ -n "${input+set}" ] then echo "Set. May or may not be empty" fi #condition6if [ -n "${input-unset}" ]then echo "Either unset or non-empty string"fi} echo "-------Case 1-------"var1="Football"emptyCheck $var1 echo "-------Case 2-------"var1=""emptyCheck $var1 echo "-------Case 3-------"var1="unset"emptyCheck $var1

In this example we have 3 cases to check if the input variable is empty or not. In the first case the input variable holds a string value. Hence, it is not empty and the variable is set. As a result it goes to conditions 4, 5 and 6. In the second case, the string is empty. Therefore the if statements acting on it are from conditions 1, 3 and 5. In the final case, we have unset the input. This triggers the if conditions 1, 2 and 6.

Conclusion

  • We often compare strings while writing Bash scripts.

  • We can apply the if commands on strings to compare them.

  • Regular expressions with string variables and constants inside the if condition help determine if the substring of a string exists.

  • We should not use (()) with if for string comparisons.

Check for unset variables
check string is empty or not using assignment operator
check string is empty using -n
Using the string length
practical example to check if a bash String is Empty or not
check string is empty using -z