Conditional Statements
Computers make decisions based on true or false conditions. This is called a conditional statement. Conditional statements can only evaluate true or false they cannot do maybe there is not grey area. Conditional statements use if statements to evaluate conditions. If something is true then do this. They also use else statements like if this is true do this else (otherwise) do that. They can also use elif statements like if this is true do this elif this is true do this else (otherwise) do that.
The table below is a quick reference for the conditional statements. It is a list of the conditional statements and what they do.
| Structure | What It Does | When to Use It |
|---|---|---|
| Basic if statement | Executes commands only if a condition is true | When you have a single condition to check |
| if-else statement | Executes one set of commands if condition is true, another if false | When you need to handle both true and false cases |
| if-elif-else statement | Checks multiple conditions in sequence | When you have multiple possible scenarios |
| Nested if statements | Places if statements inside other if statements | When conditions depend on other conditions |
Practical Examples
Simple if statement
In this example, we are checking if the name is scott. If it is, we echo the message "The name is ${name}". If it is not, we do anything.
#!/bin/bash
#IMPORTANT: make sure to have a space after the if
#notice both of these work the double and single equalis
#the second one (though works somewhat) is not correct because we are assigning $name to scott which
#evaluates to true but does not actually assign it. When doing a condition make sure you use ==
name="scott"
#this is the correct way to compare a string
if [[ $name == "scott" ]]; then
echo "The name is ${name}"
fi
#this is the incorrect way to compare a string, it will work because it evaluates to true but does not actually assign it or compare it.
#if [[ $name = "scott" ]]; then
# echo "The name is ${name}"
#fi
Simple if-else statement
In this example, we are checking if the name is scott. If it is, we echo the message "The name is ${name}". If it is not, we echo the message "The name is not scott".
#!/bin/bash
name="scott"
if [[ $name == "scott" ]]; then
echo "The name is ${name}"
else
echo "The name is not scott"
fi
Simple if-elif-else statement
In this example, we are checking if the name is scott. If it is, we echo the message "The name is ${name}". If it is not, we check if the name is karen. If it is, we echo the message "The name is karen". If it is not, we echo the message "The name is not scott or karen".
#!/bin/bash
name="scott"
if [[ $name == "scott" ]]; then
echo "The name is ${name}"
elif [[ $name == "karen" ]]; then
echo "The name is karen"
else
echo "The name is not scott or karen"
fi
Nested if elif statements
This is a nested if elif statement. It is a nested if statement inside another if statement. It is used to check multiple conditions in sequence.
In this example, we are checking if the first name is Scott and if the last name is Shaper. If both are true, we echo the name. If the first name is not Scott, we check if the first name is Karen and if the last name is Shaper. If both are true, we echo the name. If neither are true, we echo "Neither first name is Scott or Karen".
#!/bin/bash
fname="Scott"
lname="Shaper"
if [[ $fname == "Scott" ]]; then
if [[ $lname == "Shaper" ]]; then
echo "The name is ${fname} ${lname}"
else
echo "The first name is ${fname} but the last is not Shaper"
fi
elif [[ $fname == "Karen" ]]; then
if [[ $lname == "Shaper" ]]; then
echo "The name is ${fname} ${lname}"
else
echo "The first name is ${fname} but the last is not Shaper"
fi
else
echo "Neither first name is Scott or Karen"
fi
Comparison Operators
Comparison operators are used to compare values and create conditions based on relationships between data.
Common Comparison Operators
| Comparison Type | Operator | Description |
|---|---|---|
| String Comparison | == |
Equal to |
!= |
Not equal to | |
| Numeric Comparison | -eq |
Equal to |
-ne |
Not equal to | |
-gt |
Greater than | |
-lt |
Less than | |
-ge |
Greater than or equal to | |
-le |
Less than or equal to | |
| Logical Operators | && |
Logical AND |
|| |
Logical OR | |
| File Test Operators | -f |
Checks if a file exists and is a regular file |
Practical Examples
String comparison
In this example, we are checking if the name is scott. If it is, we echo the message "The name is ${name}". If it is not, we do nothing.
#!/bin/bash
name="scott"
if [[ $name == "scott" ]]; then
echo "The name is ${name}"
fi
Numeric comparison
In this example, we are checking if the number is 3 using the -eq operator. If it is, we echo the message "The number is three". If it is not, we do nothing.
#!/bin/bash
num=3
if [[ $num -eq 3 ]]; then
echo "The number is three"
fi
Combining conditions with logical OR operator
In this example, we are checking if the first name is Scott, Karen, or Mark using the logical OR operator (||). If the first name matches any of these, we then check if the last name is Shaper. If both conditions are true, we echo the full name. If the first name matches but the last name doesn't, we echo a message indicating the last name doesn't match. If the first name doesn't match any of the options, we echo a message indicating the first name doesn't match.
#!/bin/bash
fname="Scott"
lname="Shaper"
if [[ $fname == "Scott" || $fname == "Karen" || $fname == "Mark" ]]; then
if [[ $lname == "Shaper" ]]; then
echo "The name is ${fname} ${lname}"
else
echo "The first name is ${fname} but the last is not Shaper"
fi
else
echo "Neither first name is Scott, Karen or Mark"
fi
Logical AND operator
This is an example of a logical AND operator to check if two conditions are true, like a username and password. Both username and password must evaluate to true to echo the message "The username and password are correct". If either condition is false, it will echo "The username or password is incorrect".
#!/bin/bash
username="sshaper"
password="123456"
if [[ $username == "sshaper" && $password == "123456" ]]; then
echo "The username and password are correct"
else
echo "The username or password is incorrect"
fi
File test operator (-f)
This is an example of using the -f file test operator to check if a file exists and is a regular file. The -f operator returns true if the file exists and is a regular file (not a directory or special file). In this example, we check if a file named "data.txt" exists. If it does, we echo "The file exists". If it does not, we echo "The file does not exist".
#!/bin/bash
filename="data.txt"
if [[ -f "$filename" ]]; then
echo "The file exists"
else
echo "The file does not exist"
fi
Using with read
This is an example of using read to get input, then checking with logical operators. It will prompt the user to enter a first name and an age. It will then check if the first name is Scott, Karen, Mark, or John and if the age is 20, 30, 40, or 50. If both conditions are true, it will echo the message "The name is ${fname} and the age is ${age}". If either condition is false, it will echo the message "The first name is ${fname} but the age is not 20 or 30 or 40 or 50". If the first name is not Scott, Karen, Mark, or John, it will echo the message "The first names are not Scott or Karen or Mark or John".
#!/bin/bash
# Using read to get input, then checking with logical operators
echo "Please enter a first name"
read fname
echo "Please enter an age"
read age
if [[ $fname == "Scott" || $fname == "Karen" || $fname == "Mark" || $fname == "John" ]]; then
if [[ $age -eq 20 || $age -eq 30 || $age -eq 40 || $age -eq 50 ]]; then
echo "The name is ${fname} and the age is ${age}"
else
echo "The first name is ${fname} but the age is not 20 or 30 or 40 or 50"
fi
else
echo "The first names are not Scott or Karen or Mark or John"
fi
Learning Aids
Tips for Success
- Always quote variables - Even with
[[ ]], quoting variables is a good habit that prevents issues with spaces and special characters - Use
[[ ]]when possible - Double brackets provide more features and safer behavior in most cases - Indent your code - Proper indentation makes conditional blocks much easier to read and debug
- Test your conditions - Use
echoto print the result of complex conditions to verify they work as expected - Use descriptive variable names - Names like
is_validorfile_countmake your conditionals self-documenting - Break complex conditions into parts - Assign parts of complex conditions to variables with meaningful names
- Use functions for repeated tests - If you use the same condition in multiple places, create a function for it
- Add comments - Explain the purpose of complex conditionals, especially for edge cases
Common Mistakes to Avoid
- Forgetting spaces inside brackets -
[[$var == "value"]]is incorrect; use[[ $var == "value" ]] - Using
=instead of==-=is for assignment,==is for comparison. While=may work in some cases, it's not correct for comparisons - Mixing string and numeric comparisons -
==is for strings,-eqis for numbers. Using-eqwith strings doesn't work correctly - Omitting then/fi keywords - Every
ifneeds a matchingthenandfi - Not escaping special characters in
[ ]- Characters like<need escaping in single brackets - Using
[[without]]- Always ensure your brackets are balanced - Assuming all variables exist - Check if a variable exists before using it in conditions
Best Practices
- Use meaningful exit codes - Return 0 for success and specific non-zero values for different errors
- Check user input thoroughly - Validate all user input before using it in your scripts
- Handle edge cases - Consider what happens if files don't exist or inputs are unexpected
- Provide helpful error messages - When conditions fail, give users clear information about what went wrong
- Use early returns - Exit from scripts early when prerequisites aren't met
- Be consistent with your style - Choose either
[[ ]]or[ ]and stick with it throughout your script - Test conditions separately - For complex conditions, test each part individually first
- Default to safe behavior - When in doubt, make your script fail safely rather than proceed with uncertainties