LinuxCommandLibrary

if

Conditionally execute commands based on a test

TLDR

Execute the specified commands if the condition command's exit status is zero

$ if [condition_command]; then [echo "Condition is true"]; fi
copy

Execute the specified commands if the condition command's exit status is not zero
$ if ! [condition_command]; then [echo "Condition is true"]; fi
copy

Execute the first specified commands if the condition command's exit status is zero otherwise execute the second specified commands
$ if [condition_command]; then [echo "Condition is true"]; else [echo "Condition is false"]; fi
copy

Check whether a [f]ile exists
$ if [[ -f [path/to/file] ]]; then [echo "Condition is true"]; fi
copy

Check whether a [d]irectory exists
$ if [[ -d [path/to/directory] ]]; then [echo "Condition is true"]; fi
copy

Check whether a file or directory [e]xists
$ if [[ -e [path/to/file_or_directory] ]]; then [echo "Condition is true"]; fi
copy

Check whether a variable is defined
$ if [[ -n "$[variable]" ]]; then [echo "Condition is true"]; fi
copy

List all possible conditions (test is an alias to [; both are commonly used with if)
$ man test
copy

SYNOPSIS

if command_list
then
  commands_if_true
fi

if command_list
then
  commands_if_true
else
  commands_if_false
fi

if command_list_1
then
  commands_if_true_1
elif command_list_2
then
  commands_if_true_2
else
  commands_if_false
fi

PARAMETERS

if
    Initiates a conditional block. It evaluates the exit status of the subsequent command list.

then
    Specifies the commands to be executed if the preceding if or elif condition evaluates to true (exit status 0).

else
    Specifies the commands to be executed if the preceding if or elif condition evaluates to false (non-zero exit status).

elif
    An 'else if' clause that introduces an additional condition to be tested if the previous if or elif condition was false.

fi
    Marks the end of an if block. All if statements must be terminated with fi.

command_list
    One or more commands whose combined exit status determines the flow of the if statement. Typically, this includes test or [ expressions.

DESCRIPTION

The if construct is a fundamental shell keyword used for conditional execution of commands within a shell script or on the command line.
It evaluates the exit status of a command or list of commands. If the exit status is zero (indicating success or true), the commands following then are executed. If the exit status is non-zero (indicating failure or false), the commands following else (if present) are executed.
The if statement supports various forms: a simple if...then...fi block, an if...then...else...fi block for alternative execution, and an if...then...elif...else...fi block for multiple conditions.
Conditions are typically evaluated using commands like test or the [ (single bracket) and [[ (double bracket) operators, which return an exit status based on their evaluation.

CAVEATS

The if construct is a shell keyword, not an external command found in /usr/bin.
It relies solely on the exit status of the evaluated command: 0 for true (success) and any non-zero value for false (failure).
Proper indentation and newlines/semicolons are crucial for readability and correct parsing by the shell.
Always ensure the if block is correctly terminated with fi.

EXIT STATUS AND CONDITIONALS

The if command evaluates the exit status of the command(s) immediately following it. An exit status of 0 indicates success or true, while any non-zero exit status indicates failure or false. This is a crucial concept in shell scripting, as many commands return specific exit codes to signify different outcomes.
Common conditional expressions use the test command or its shorthand [ for basic tests (e.g., -f file for file existence, -z string for empty string, num1 -eq num2 for numeric equality). More advanced shells like bash also provide [[ for enhanced conditional expressions, supporting regular expressions and logical operators (&&, ||) more directly.

ONE-LINER SYNTAX

For simple if statements, the then keyword and the commands can be placed on the same line as if by separating them with a semicolon. Similarly, else and fi can follow on the same line.
Example: if [ -f file.txt ]; then echo "File exists"; fi
This compact form is often used for quick checks on the command line.

LOGICAL OPERATORS

While if is used for blocks, shell logical operators && (AND) and || (OR) can achieve conditional execution in a more concise way for single commands.
command1 && command2 (Execute command2 only if command1 succeeds)
command1 || command2 (Execute command2 only if command1 fails)
These are often used as alternatives to simple if statements for brevity.

HISTORY

The if conditional construct has been a core component of Unix shells since the early days of the Bourne shell (sh). Its design was crucial for writing robust scripts that could adapt to different conditions and handle errors gracefully.
Modern shells like bash, zsh, and ksh have inherited and expanded upon this fundamental structure, though the core syntax and behavior remain consistent. It is universally available and a cornerstone of shell scripting.

SEE ALSO

test(1), [(1), bash(1), case(1), true(1), false(1)

Copied to clipboard