then
Execute commands after conditional statement's success
TLDR
View documentation for if command
SYNOPSIS
if [ condition ]
then
commands
fi
DESCRIPTION
The `then` command is a keyword in shell scripting, primarily used in conjunction with the `if` statement. It specifies the code block to execute if the condition evaluated by the `if` statement is true. Essentially, it marks the beginning of the "then" part of an `if-then` control structure.
While `then` is technically a command, it's more accurately understood as a syntactic element required for the correct parsing and execution of `if` statements. Without `then`, the shell wouldn't know where the conditional code block begins, which is crucial for deciding which statements to execute based on the condition. It is important to understand that `then` is always used inside of an `if` statement, not by itself.
CAVEATS
The `then` keyword is mostly implicit and part of the shell grammar. It doesn't have arguments or options of its own.
While the `then` command is not strictly required if the following commands are on a newline, using it consistently improves readability and reduces ambiguity.
EXAMPLE
```bash
if [ "$USER" = "root" ]; then
echo "You are the root user."
fi
```
This script checks if the current user is 'root'. If it is, the message 'You are the root user.' is printed.
ALTERNATIVES
Some coding styles will drop the use of `then` if the conditional statement and the action are written on different lines. For example, this is functionally equivalent to the code above:
```bash
if [ "$USER" = "root" ]
echo "You are the root user."
fi
```
HISTORY
The `then` keyword has been part of Bourne shell scripting syntax since its early days. It's inherited and supported by all modern shells like Bash, Zsh, and Ksh. Its purpose is to define a clear block of code to execute conditionally. The design is consistent with programming languages and aims at improving readability of shell scripts. Early shells lacked features for structural programming that now are considered obvious so adding those features has improved the utility and use of shell scripting.