Shell Script Flow Control (If-Else Statements)

Shell Script Flow Control: If-Else Statements

In shell programming, flow control is the core mechanism that determines the execution path of a program. Unlike high-level languages, while shell syntax is relatively concise, its logical rigor demands a deep understanding of conditional expressions from developers. if-else statements allow scripts to decide subsequent code blocks based on the truth or falsity of specific conditions, thereby enabling dynamic responses, error handling, and automated decision-making capabilities. Mastering this structure is the first step in writing robust shell scripts.
The if statement in Shell follows standard C-style logic but possesses unique characteristics regarding its evaluation conditions. The basic structure consists of three components: a test expression, an optional else branch, and an optional elif (or then) section. When the condition is true, the program enters the corresponding code block; if it is false and an else branch exists, that branch's code executes instead.

if [ condition ]; then
    # Command sequence to execute if the condition holds
fi

It is worth noting that in Shell, checking whether a value is empty typically uses -z (zero-length) rather than == "". Furthermore, logical operators such as &&, ||, and ! can be used directly for constructing compound conditions. For example, [ -f file.txt ] && [ -r file.txt ] indicates that the file exists and is readable.

Extension of Multi-Branch Structures with If-Elif-Fi

In practical applications, a single condition often fails to cover all business scenarios; therefore, an if-elif-finally structure (abbreviated as else-if) has been introduced to build multi-level judgment logic. This pattern allows us to sequentially attempt different operation blocks under multiple mutually exclusive conditions.

#!/bin/bash

score=$1

if [ "$score" -ge 90 ]; then
    echo "Excellent score, awarded A+"
elif [ "$score" -ge 80 ]; then
    echo "Good score, awarded B"
elif [ "$score" -gt 60 ]; then
    echo "Passed with credit, awarded C"
else
    echo "Failed, needs retake exam"
fi

The above script accepts the user's input score as a parameter and provides corresponding feedback through nested hierarchical judgments. Each elif branch is only evaluated if the preceding conditions are not met, ensuring logical uniqueness and exclusivity. For complex business rules, this structure is more efficient than using multiple independent if statements and reduces the risk of duplicate executions.

Common Pitfalls and Best Practice Recommendations

When writing shell scripts, developers often fall into logic errors or runtime exceptions due to overlooking details. There are three key points that must be noted: first, variables in all conditional expressions must be quoted (e.g., $var); failure to do so may lead to warnings about undefined variables or even syntax parsing failures; second, avoid using overly long compound command chains within a single line, as this increases readability difficulties and the probability of errors; finally, always remember to add semicolons or newlines for each if block to clearly mark its end.

Additionally, it is recommended to encapsulate complex conditional judgments into functions to improve code reusability, such as defining a check_status() function to handle file permission check logic. Simultaneously, utilizing combination operations like [ -e file ] && [ ! -x file ] can quickly achieve judgment scenarios where "the file exists but is not executable." By adhering to standardized writing habits and rigorous logical design, the maintainability and stability of shell scripts can be significantly enhanced.