Shell Scripting Conditions & If-Then Statements - A Beginner's Guide

Exploring Conditional Logic in Shell Scripting
Having established a foundational understanding of shell scripting, you are now equipped to begin practical experimentation. This week’s focus will shift towards more engaging concepts, specifically the implementation of conditions and “if-then” statements within your scripts.
Understanding Conditional Statements
Conditional statements are fundamental to creating dynamic and responsive shell scripts. They allow your scripts to make decisions based on specific criteria, executing different code blocks accordingly.
The core principle revolves around evaluating a condition. If the condition is true, a designated set of commands is executed. Otherwise, an alternative set of commands, or none at all, may be run.
The “if-then” Structure
The “if-then” statement is the most basic form of conditional execution in shell scripting. It follows a straightforward syntax:
if [ condition ]; then
commands to execute if the condition is true
fi
The square brackets [ ] enclose the condition being evaluated. The then keyword signifies the start of the code block to be executed when the condition holds true. The fi command marks the end of the conditional statement.
Examples of Conditions
Conditions can take various forms, including comparisons between numbers, strings, or files. Here are a few common examples:
- Numerical Comparison:
[ $a -eq $b ](checks if $a is equal to $b) - String Comparison:
[ "$string1" = "$string2" ](checks if string1 is equal to string2) - File Existence:
[ -f filename ](checks if a file named filename exists)
These are just a few illustrations; shell scripting offers a wide range of operators for constructing complex conditions.
Expanding with “else” and “elif”
To handle scenarios where the initial condition is false, you can incorporate the else keyword. This allows you to specify an alternative code block to be executed if the “if” condition is not met.
Furthermore, the elif (else if) keyword enables you to chain multiple conditions together, creating a series of checks.
if [ condition1 ]; then
commands if condition1 is true
elif [ condition2 ]; then
commands if condition2 is true
else
commands if all conditions are false
fi
Using else and elif significantly enhances the flexibility and robustness of your shell scripts.
By mastering these conditional constructs, you can create scripts that respond intelligently to different situations, automating tasks with greater precision and efficiency.
Understanding Conditions in Computing
Generally speaking, a condition represents a prerequisite that must be fulfilled for a specific event to take place. Consider a scenario where you want your laptop to access the internet; several conditions need to be satisfied, such as an active Internet Service Provider (ISP), a functioning modem and/or router, and an operational laptop.
If any of these requirements are absent, the desired outcome – internet connectivity – will not be achieved. This concept translates directly into the world of computer programming.
Within computing, we frequently evaluate strings to determine if they correspond to, or differ from, other strings, or even simply verify their existence. Numerical values can also be compared to ascertain if one is larger, smaller, or equivalent to another.
Implementing Conditional Logic with "If-Then" Statements
To execute commands only when specific conditions are true, programmers utilize “if-then” statements. These statements provide a structured way to control the flow of a program based on the evaluation of conditions.
The basic structure of an “if-then” statement is straightforward and easily understood.
if CONDITION
then
command1
command2
...
commandn
fi
This structure allows for the execution of a series of commands – command1 through commandn – only if the specified CONDITION evaluates to true. The 'fi' keyword signifies the end of the conditional block.
If Statements
Let's examine a concise test script to demonstrate the functionality.
if test $1 -gt $2
then
echo "$1 is greater than $2"
fi
The script will only proceed to execute the subsequent command when the specified condition evaluates to true. Otherwise, the execution flow will bypass the code block within the “if” statement. Any commands appearing after the “if” statement will be executed regardless of the condition's outcome.
To further illustrate this behavior, the following line was appended to the preceding script:
echo "This comes after the if statement"
Below are additional numerical operators that can be utilized in your scripts:
- -eq: Represents equality.
- -ne: Indicates inequality.
- -lt: Denotes "less than".
- -le: Signifies "less than or equal to".
- -gt: Represents "greater than".
- -ge: Indicates "greater than or equal to".
These operators allow for flexible comparisons within your shell scripts. They are essential for controlling the flow of execution based on numerical values.
Understanding Conditional Execution
The core principle of an “if” statement is to conditionally execute code. This means a block of commands will only run if a specific condition is met.
The test command is crucial here, as it evaluates the condition. If the condition is true, the commands within the then and fi block are executed.
Practical Application
Consider a scenario where you need to check if a file exists before attempting to process it. An “if” statement can be used to verify the file's existence and only proceed if it is present.
Operator Overview
The operators listed above provide a range of comparison options. Choosing the correct operator is vital for accurately evaluating your desired condition.
String Comparisons in Shell Scripting
Let's examine how to alter our initial script line to the following:
if test $1 = $2
This revised condition evaluates whether the two provided arguments are equivalent. However, a crucial point must be understood! The equals sign (=) performs a comparison of strings, rather than numerical values.
To compare numbers effectively, the operator “-eq” should be utilized, mirroring the approach we employed with “-gt” previously.
Modifying the Test Condition
Consider this further modification to our script:
if test $1 != $2
The introduction of the exclamation mark (!) functions as a negation operator. Specifically, the subsequent command will only execute if the two strings are dissimilar.
Additional String-Based Tests
A variety of string-based tests are available for use within your shell scripts. Here's a breakdown of some common options:
- string: Testing an argument directly determines if the string is neither empty nor undefined.
- -n string: This test verifies that the string is both defined and not empty.
- -z string: This test checks if the string is defined but empty.
These operators provide flexibility when evaluating string values within your shell scripts.
Understanding these distinctions is vital for accurate conditional logic in your shell scripting endeavors.
Expanding on Conditional Logic
Acknowledging a playful title, let's delve deeper into conditional execution. We've established how to run a command when a test evaluates to true. But what about scenarios requiring a different action when the test fails? This is readily achieved by extending our “if-then” structures with an “else” clause.
The 'if-else' Construct
The following illustrates the structure of an 'if-else' statement:
if CONDITION
then
command1
command2
...
commandn
else
command1
command2
...
commandn
fi
This allows for the execution of one set of commands if the condition is met, and an alternative set if it isn't.
A Practical Script Example
Consider this illustrative script:

Note the consistent indentation, crucial for shell script readability and correct execution. Observe the use of square brackets ( [ and ] ) surrounding the condition.
Alternative Condition Syntax
These brackets are functionally equivalent to the 'test' command in this context. You will frequently encounter the bracket notation in shell scripting, and we will adopt it for consistency moving forward.
Expected Output
The script's execution will produce the following output:

Implementing conditional logic with 'if-else' statements is straightforward and powerful. It enables scripts to respond dynamically to varying conditions.
Expanding Scripting Capabilities with Conditional Logic
Having grasped the functionality of “if-then-else” statements, you are now equipped to execute scripts capable of performing evaluations. As an illustration, a script could be developed to compute the MD5 hash of a file and subsequently compare it against a downloaded hash value to verify consistency.
To further enhance your skills, consider constructing a script that incorporates a “for” loop, employing test conditions in lieu of reading data from a list file.
This approach offers a dynamic alternative for iterative processes.
We are progressing into the more engaging aspects of our Beginner’s Guide to Shell Scripting. Should you have missed any preceding lessons, a convenient list is provided for your review:
- The Fundamentals of Shell Scripting
- Leveraging For Loops
- Additional Essential Commands
- Distinguishing Between Linux Shells
- Utilizing Basic Regular Expressions
If you have created or implemented scripts that utilize testing conditions, “if-then-else” structures, and “for” loops, we encourage you to share your experiences in the comments section below!