EN
Bash - check if string is empty
0 points
This article will show you how to check if the string is empty in Bash.
Quick solution:
xxxxxxxxxx
1
2
3
variable="Sample text"
4
[ -z "$variable" ] && echo "variable is empty" || echo "variable is not empty"
Example output:
xxxxxxxxxx
1
variable is not empty
xxxxxxxxxx
1
2
3
variable="Sample text"
4
empty_variable=""
5
6
[ -z "$variable" ] && echo "variable is empty" || echo "variable is not empty"
7
[ -z "$empty_variable" ] && echo "empty_variable is empty" || echo "empty_variable is not empty"
Example output:
xxxxxxxxxx
1
variable is not empty
2
empty_variable is empty
xxxxxxxxxx
1
2
3
variable="Sample text"
4
5
if [ -z "$variable" ]
6
then
7
echo "variable is empty"
8
else
9
echo "variable is not empty"
10
fi
Output:
xxxxxxxxxx
1
variable is not empty
xxxxxxxxxx
1
2
3
variable="Sample text"
4
5
if test -z "$variable"
6
then
7
echo "variable is empty"
8
else
9
echo "variable is not empty"
10
fi
Output:
xxxxxxxxxx
1
variable is not empty