Skip to content

Click on each book below to review & buy on Amazon.

As an Amazon Associate, I earn from qualifying purchases.


LPI Linux Essentials Exam 010-160 - Topic 3.3 - Conditionals / If Statements

The conditional constructs of the Linux shell are foundational to script writing. They allow the shell to react to various conditions and execute commands accordingly. Let's delve into a refined and more detailed exploration of the if statements and related conditional expressions in the context of Linux.

Understanding if Statements

At its core, the if statement allows the execution of a code block contingent upon the satisfaction of a specified condition. Its elegance lies in its simplicity and its utility in facilitating the flow control of a script.

Basic Syntax of an if Statement

The if statement can be thought of as a fork in the road; it asks a question, and the subsequent path taken depends on the answer to that question:

if [ condition ]; then
    # Commands to execute if the condition is true.
else
    # Commands to execute if the condition is false.
fi

When interpreting this structure, the shell evaluates the condition within the square brackets. If the result is true (which in shell terms means it returns an exit status of zero), the commands following the then keyword are executed. If not, the shell will execute the commands following the else keyword, if present.

Condition Evaluation: test and []

The shell offers built-in commands like test and [ ] to evaluate conditions. Both serve similar purposes but differ slightly in syntax.

Evaluating File Attributes:

Both test and [ ] can evaluate file attributes. For example, to check if a file exists and is a regular file, one might use:

if test -f /etc/passwd; then
    echo "/etc/passwd exists and is a regular file."
fi

Or:

if [ -f /etc/passwd ]; then
    echo "/etc/passwd exists and is a regular file."
fi

In the snippets above, -f is a file test operator that checks for the presence of a regular file. The message echoes only if the condition holds true.

Combining Conditions

When there's a need to evaluate multiple conditions simultaneously, the shell provides logical operators.

Using Logical AND and OR:

  • Logical AND (&&): Both conditions must be true for the combined condition to be true.
  • Logical OR (||): Either condition must be true for the combined condition to be true.
var=15

if [ "$var" -gt 10 ] && [ "$var" -lt 20 ]; then
    echo "The value of var is between 10 and 20."
else
    echo "The value of var is not between 10 and 20."
fi

The example uses && for an AND operation to ensure $var lies within the range. Similarly, for an OR operation, one could use ||:

var=8

if [ "$var" -lt 10 ] || [ "$var" -gt 20 ]; then
    echo "The value of var is not between 10 and 20."
else
    echo "The value of var is between 10 and 20."
fi

While -a and -o are still encountered in shell scripts due to their historical usage, it is pertinent to recognize that these operators have been superseded by && and ||. The latter pair are the operators recommended for evaluating conditional expressions in the shell.

Using Conditions with Commands

Apart from tests, conditions can also be based directly on the exit status of commands. This allows for a more dynamic and direct approach to control flow based on the success or failure of commands.

Syntax When Using Commands

if command; then
    # Commands to execute if the previous command succeeds.
else
    # Commands to execute if the previous command fails.
fi

Handling Command Execution

A command's success is indicated by an exit status of zero, while a non-zero value signals a failure. Here's how to use it:

if touch /etc/passwd 2> /dev/null; then
    echo "Successfully updated timestamp."
else
    echo "Failed to update timestamp."
fi

If attempted by a non-privileged user, this command will likely fail, as /etc/passwd is typically owned by the root user. The error is redirected to /dev/null to suppress any unwanted output. By using sudo -i, one switches to the root user, where the command should succeed, resulting in the success message.


Support DTV Linux

Click on each book below to review & buy on Amazon. As an Amazon Associate, I earn from qualifying purchases.

NordVPN ®: Elevate your online privacy and security. Grab our Special Offer to safeguard your data on public Wi-Fi and secure your devices. I may earn a commission on purchases made through this link.