Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Bash, Why `then` is needed in the conditional constructs?

The conditional construct of if command looks like this:

if TEST-COMMANDS; then
    CONSEQUENT-COMMANDS;
[elif MORE-TEST-COMMANDS; then
  MORE-CONSEQUENTS;]
[else ALTERNATE-CONSEQUENTS;]
fi

And the loop construct of while command looks like this:

while TEST-COMMANDS; do CONSEQUENT-COMMANDS; done

I was wondering why then is needed in if command but not in while command? Why couldn't it be ommited?

like image 681
Hanfei Sun Avatar asked Apr 06 '15 14:04

Hanfei Sun


People also ask

What is the purpose of conditional expressions in shell scripts?

Conditions in Shell Scripts An if-else statement allows you to execute iterative conditional statements in your code. We use if-else in shell scripts when we wish to evaluate a condition, then decide to execute one set between two or more sets of statements using the result.

Which command provides a way to test different conditions in an IF THEN statement?

We can test more than one conditional expression at once, using && to require that two conditions that both must be true. Or, using || to require that either one (or both) of the conditions must be true.

What is if [[ ]] in Linux?

if is a command in Linux which is used to execute commands based on conditions. The 'if COMMANDS' list is executed. If its status is zero, then the 'then COMMANDS' list is executed.


1 Answers

do in the while syntax serves a similar purpose to then in the if syntax. They both signify the start of the body of the statement - differentiating it from the condition part of the statement.

The if conditional statement is a compound statement in the shell. The if & then sections of the statement are executed as two parts, the then section is only invoked if the if section ends with an exit status of 0. Both sections may contain multiple statements; therefore, a semi-colon alone is insufficient to separate these sections.

like image 141
shibley Avatar answered Nov 15 '22 03:11

shibley