Shell Script Conditions - If Else & Short Circuiting

Learn about shell script conditions, including if-else statements, file, string, and number comparisons, and short-circuiting with && and || operators.

Shell Script Conditions

26. Conditions in Shell Scripting

Understanding and implementing conditions is fundamental to writing effective shell scripts. This guide covers the essential conditional structures and operators used in command-line environments.

26.1. If-Else Statements

The if-then-else construct is a core part of shell scripting, allowing scripts to make decisions based on certain criteria. It's supported in command-line environments for conditional execution.

Syntax

The general syntax for an if-else statement in bash is:

if [ condition1 ]; then
    command1
elif [ condition2 ]; then
    command2
else
    command3
fi

A more compact form is also possible:

if [ condition1 ]; then command1; elif [ condition2 ]; then command2; else command3; fi

Types of Conditions

Shell scripting supports various types of conditions to evaluate different aspects of your system and data.

File-Based Conditions

These conditions check the status and properties of files and directories:

Condition Description
-e Checks if a file exists.
-r Checks if a file exists and is readable.
-w Checks if a file exists and is writable.
-d Checks if a file exists and is a directory.

String-Based Conditions

These conditions compare strings based on their content and length:

Condition Description
== Checks if both strings are equal.
!= Checks if both strings are not equal.
> Checks if the first string is lexicographically greater than the second.
< Checks if the first string is lexicographically smaller than the second.
-n Checks if the string has a length greater than 0 (is not empty).
-z Checks if the string is empty (has a length of 0).

Number-Based Conditions

These conditions perform numerical comparisons:

Condition Description
-eq Checks if the numbers are equal.
-ne Checks if the numbers are not equal.
-gt Checks if the first number is greater than the second.
-ge Checks if the first number is greater than or equal to the second.
-lt Checks if the first number is less than the second.
-le Checks if the first number is less than or equal to the second.

In shell scripting, the exit status of a command is crucial. An exit status of 0 is conventionally considered true (success), while any non-zero number (typically greater than 0) is considered false (failure). This convention stems from the Unix/Linux philosophy where a successful process termination returns 0.

26.2. Short-Circuiting with Logical Operators

An efficient way to manage command execution based on conditions is by using logical AND (&&) and logical OR (||). These operators employ short-circuiting, meaning the evaluation of a logical expression stops as soon as the outcome is definitively determined.

Logical AND (&&)

In an expression like command1 && command2, if command1 evaluates to false (fails), the entire expression is false, and command2 is not executed. This is useful for ensuring that a subsequent command runs only if the preceding one succeeds.

Example: command1 && command2 ensures that command2 is executed only if command1 finishes successfully.

Logical OR (||)

In an expression like command1 || command2, if command1 evaluates to true (succeeds), the entire expression is true, and command2 is not executed. This is beneficial for executing a fallback command only if the primary command fails.

Example: command1 || command2 ensures that command2 is executed only if command1 fails.

26.2.1. Practical Examples

  • Create a folder only if it does not exist:
  [ -d ./some/path/folder ] || mkdir -p /some/path/folder

This command checks if the directory ./some/path/folder exists. If it does not (-d returns false), the || operator triggers the execution of mkdir -p /some/path/folder to create the directory and any necessary parent directories.

  • Create a file only if the target folder exists:
  cd /some/path/folder && touch file.txt

This command first attempts to change the directory to /some/path/folder. If the cd command is successful (returns true), the && operator allows the execution of touch file.txt to create the file within that directory. If the directory does not exist or cannot be accessed, cd will fail, and touch will not be executed.

By mastering these conditional constructs and logical operators, you can build more robust and intelligent shell scripts capable of handling diverse scenarios and automating complex tasks.

External Resources