EN
Bash - check if string is not empty
0 points
In this article, we would like to show you how to check if string is not empty in Bash.
In this example, we use -n
operator to check if string length is not zero inside the if
statement.
script.sh
file:
xxxxxxxxxx
1
2
3
string="example text..."
4
5
if [ -n "$string" ]; then
6
echo "The string is not empty"
7
fi
Note: this approach should be used in POSIX shells where other solutions may not work.
Run in command line:
xxxxxxxxxx
1
./script.sh
Output:
xxxxxxxxxx
1
The string length is not empty
xxxxxxxxxx
1
2
3
string="example text..."
4
5
if test -n "$string"; then
6
echo "The string is not empty"
7
fi
Note:
[ ]
notation is shorthand oftest
command.
xxxxxxxxxx
1
2
3
string="example text..."
4
5
if [[ -n "$string" ]]; then
6
echo "The string is not empty"
7
fi
Note:
[[ ]]
notation is like extendedtest
command, adding additional features (e.g. regular expressions).