Table of contents

Check if string is empty or not in shell

Shell Jun 15, 2020 Viewed 143 Comments 0

Using bash scripts, sometimes we need to determine whether the string variable is empty. Here are two simple methods.

-n operator

-n opratator will return true if a variable contains characters, or the length of the characters is greater than 0, return false when the variable is empty.

#!/bin/bash
str1="hello world"
if [[ -n "$str1" ]]; then
    echo "str1 is not empty"
fi
str2=""
if [[ ! -n "$str2" ]]; then
    echo "str2 is empty"
fi

Output

str1 is not empty
str2 is empty

-z operator

-z is to check whether the string is empty. The -z operator functions like the -n operator. Here is an example.

#!/bin/bash
str=""
if [[ -z "$str" ]]; then
    echo "str is empty"
fi

Output

str is empty

Example

The following is an example to determine whether the first parameter is empty.

Create a new file named isempty.sh, and enter the script below.

#!/bin/bash
str=$1
[[ -n "$str" ]] && echo "The value of the first argument is $str" || echo "First argument is empty"
[[ -z "$str" ]] && echo "First argument is empty" || echo "The value of the first argument is $str"

Run the script.

$ ./isempty.sh   
First argument is empty
First argument is empty
$ ./isempty.sh hello
The value of the first argument is hello
The value of the first argument is hello
Updated Jun 15, 2020