Bash String Tests
String tests compare text or check whether text is present. They work inside the same square brackets.
Equal Strings
The equals sign compares the variable with a word. Quote the variable so empty values stay safe.
name="Ada"
if [ "$name" = "Ada" ]; then
echo "Hello, Ada"
fiDifferent Strings
The operator != means not equal to. Paris differs from Rome, so the line prints.
city="Paris"
if [ "$city" != "Rome" ]; then
echo "Paris is not Rome"
fiEmpty and Non-Empty
The operator -z tests for empty text. The operator -n tests for text that is present.
nickname=""
fullname="Ada Lovelace"
if [ -z "$nickname" ]; then
echo "The nickname is empty"
fi
if [ -n "$fullname" ]; then
echo "The full name is set"
fiExample
username="sam"
pin=""
if [ -n "$username" ]; then
echo "The username is set"
fi
if [ -z "$pin" ]; then
echo "The PIN is still empty"
fi
if [ "$username" = "sam" ]; then
echo "Welcome back, sam"
fiKey points
- A single equals sign compares two strings.
- The operator != checks that two strings differ.
- The operator -z is true for an empty string.
- The operator -n is true for a non-empty string.
- Quote the variable side of a string test.
- An empty string still needs quotes around the variable.
In this example, three string tests check one sign-in form. The username passes the -n and equals tests, while the empty PIN passes -z.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which operator is true when a string is empty?