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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With