Languages
[Edit]
EN

Bash - check if string is empty

0 points
Created by:
Pearl-Hurley
559

This article will show you how to check if the string is empty in Bash.

Quick solution:

#!/bin/bash

variable="Sample text"
[ -z "$variable" ] && echo "variable is empty" || echo "variable is not empty"

Example output:

variable is not empty

 

Practical examples

1. With control operators

#!/bin/bash

variable="Sample text"
empty_variable=""

[ -z "$variable" ] && echo "variable is empty" || echo "variable is not empty"
[ -z "$empty_variable" ] && echo "empty_variable is empty" || echo "empty_variable is not empty"

Example output:

variable is not empty
empty_variable is empty

2. With if statement

#!/bin/bash

variable="Sample text"

if [ -z "$variable" ] 
then 
	echo "variable is empty"
else 
	echo "variable is not empty"
fi

Output:

variable is not empty

Alternative if statement example

#!/bin/bash

variable="Sample text"

if test -z "$variable"
then 
	echo "variable is empty"
else 
	echo "variable is not empty"
fi

Output:

variable is not empty

Alternative titles

  1. Bash - check if variable is empty
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Bash

Bash - check if string is empty
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join