LinuxCommandLibrary

then

Execute commands after conditional statement's success

TLDR

View documentation for if command

$ tldr if
copy

SYNOPSIS

if condition-commands; then
    commands-if-true
[elif another-condition-commands; then
    commands-if-another-true]...
[else
    commands-if-false]
fi

DESCRIPTION

The word 'then' is not a standalone Linux command or executable program. Instead, it is a fundamental keyword in various Unix-like shell scripting languages, including Bash, Zsh, and Ksh. Its primary role is to mark the beginning of a command block that should be executed when a preceding condition evaluates to true within an if or elif statement. It serves as a syntactic separator, indicating that the condition has ended and the commands to be performed should follow. Without 'then', shell conditional constructs would be syntactically incomplete and result in errors. It ensures clarity and structure in shell scripts, allowing for proper flow control based on the outcomes of evaluations.

CAVEATS

Not a standalone command: 'then' is a shell keyword and cannot be executed independently from a shell script or a shell prompt.
Syntax Requirement: It must immediately follow a command or command list that constitutes a condition, separated by a semicolon (;) or a newline.
Context-Specific: 'then' is primarily used with if and elif conditional statements. It is not used with for or while loops, which use the do keyword instead.

USAGE EXAMPLES

Here are common examples demonstrating the use of then in shell scripts:

Simple If-Then:
if grep -q "hello" file.txt;
then
  echo "'hello' found!";
fi

If-Then-Else:
if [ -f "myfile.txt" ];
then
  echo "File exists.";
else
  echo "File does not exist.";
fi

If-Then-Elif-Then-Else:
if ping -c 1 8.8.8.8 &>/dev/null;
then
  echo "Internet is reachable.";
elif command -v curl &>/dev/null;
then
  echo "Curl is installed.";
else
  echo "Neither Internet nor Curl.";
fi

HISTORY

The concept of 'then' as a keyword to introduce conditional blocks has been an integral part of Unix shell syntax since the original Bourne shell (sh) was introduced in 1979. Its design was influenced by programming languages that use similar constructs for flow control. Over the decades, as various shells like Korn shell (ksh), GNU Bash, and Zsh emerged and evolved, the fundamental role and syntax of 'then' remained consistent, underscoring its foundational importance in shell scripting paradigms.

SEE ALSO

if(1), else(1), elif(1), fi(1), test(1), bash(1), sh(1)

Copied to clipboard