0
0
Bash Scriptingscripting~15 mins

String comparisons (=, !=, -z, -n) in Bash Scripting - Mini Project: Build & Apply

Choose your learning style9 modes available
String comparisons (=, !=, -z, -n) in Bash scripting
📖 Scenario: You are writing a small script to check user input strings for different conditions. This is common when you want to make decisions based on text values in scripts.
🎯 Goal: Build a bash script that creates a string variable, sets a condition string, compares them using = and !=, and checks if strings are empty or not using -z and -n.
📋 What You'll Learn
Create a string variable called input with the exact value hello
Create a string variable called check with the exact value hello
Use an if statement to compare if input equals check using =
Use an if statement to compare if input does not equal world using !=
Use -z to check if a variable empty_str is empty
Use -n to check if a variable non_empty_str is not empty
Print messages for each condition to show the result
💡 Why This Matters
🌍 Real World
Scripts often need to check text values to decide what to do next, like checking if a filename is empty or if a user typed a specific command.
💼 Career
Understanding string comparisons in bash is essential for writing automation scripts, deployment scripts, and system maintenance tasks in many IT and DevOps roles.
Progress0 / 4 steps
1
Create the initial string variables
Create a string variable called input and set it to hello. Also create a string variable called check and set it to hello.
Bash Scripting
Need a hint?

Use variable="value" syntax to create string variables in bash.

2
Add variables to test empty and non-empty strings
Create a string variable called empty_str and set it to an empty string "". Create another string variable called non_empty_str and set it to bash.
Bash Scripting
Need a hint?

Set empty_str to "" and non_empty_str to "bash" using the same syntax as before.

3
Write string comparison conditions using = and !=
Write an if statement that checks if input equals check using =. Inside it, print "Strings are equal". Then write another if statement that checks if input does not equal world using !=. Inside it, print "Strings are not equal".
Bash Scripting
Need a hint?

Use if [ "$var1" = "$var2" ] and if [ "$var1" != "value" ] syntax for string comparisons in bash.

4
Check if strings are empty or not using -z and -n and print results
Write an if statement that uses -z to check if empty_str is empty. If true, print "empty_str is empty". Then write an if statement that uses -n to check if non_empty_str is not empty. If true, print "non_empty_str is not empty".
Bash Scripting
Need a hint?

Use if [ -z "$var" ] to check empty and if [ -n "$var" ] to check not empty.