String comparisons help you check if words or texts are equal, different, empty, or not empty in scripts.
0
0
String comparisons (=, !=, -z, -n) in Bash Scripting
Introduction
Check if a user entered the correct password.
See if a file name matches a specific pattern.
Verify if a variable has any value or is empty.
Decide what to do based on user input text.
Compare two strings to control script flow.
Syntax
Bash Scripting
if [ "$string1" = "$string2" ]; then # commands fi if [ "$string1" != "$string2" ]; then # commands fi if [ -z "$string" ]; then # commands for empty string fi if [ -n "$string" ]; then # commands for non-empty string fi
Always put strings in double quotes to avoid errors with spaces or empty values.
Use single brackets [ ] with spaces around operators for string tests in bash.
Examples
This checks if the variable
name is exactly "Alice".Bash Scripting
if [ "$name" = "Alice" ]; then echo "Hello, Alice!" fi
This checks if
input is not empty.Bash Scripting
if [ "$input" != "" ]; then echo "You typed something." fi
This runs if
password has no characters.Bash Scripting
if [ -z "$password" ]; then echo "Password is empty!" fi
This runs if
filename has one or more characters.Bash Scripting
if [ -n "$filename" ]; then echo "Filename is set." fi
Sample Program
This script asks for your name. It checks if you typed nothing, if you typed "Alice", or something else, and prints a message.
Bash Scripting
#!/bin/bash read -p "Enter your name: " name if [ "$name" = "" ]; then echo "You did not enter a name." elif [ "$name" = "Alice" ]; then echo "Welcome back, Alice!" else echo "Hello, $name!" fi
OutputSuccess
Important Notes
Use = for equality and != for inequality in string tests.
-z means the string is empty; -n means it is not empty.
Always quote variables to avoid errors when they are empty or contain spaces.
Summary
Use = and != to compare if strings are equal or not.
Use -z to check if a string is empty, and -n to check if it is not empty.
Always put quotes around variables in comparisons to keep your script safe.