if
Shell conditional statement
TLDR
SYNOPSIS
if test-commands; then commands; [elif test-commands; then commands;] [else commands;] fi
DESCRIPTION
if is a shell builtin conditional statement. It executes the test-commands list and, if the exit status is zero (success), runs the corresponding then clause. If non-zero, each elif clause is tested in turn. If no condition succeeds and an else clause is present, its commands are executed.Although if is most commonly used with test or [[ ]] expressions, any command can serve as the condition since the decision is based on exit status. For example, if grep -q pattern file branches on whether grep found a match.
PARAMETERS
test-commands
A list of commands whose exit status determines the branch taken. An exit status of 0 (success) means the condition is true.then
Introduces commands to execute when the preceding condition is true.elif
Else-if clause; tests an additional condition if prior conditions were false.else
Commands to execute if all preceding conditions were false.fi
End of the if block.
CAVEATS
Shell builtin. Spaces inside [ ] and [[ ]] are required (e.g., [ "$a" = "$b" ], not ["$a"="$b"]). The POSIX-compatible test syntax is [ ], while [[ ]] is a bash/zsh extension with additional features like pattern matching and regex.
HISTORY
if is a standard Unix shell construct, present in all POSIX-compliant shells since the original Bourne shell.
