Conditional Statements: There are total 5 conditional statements which can be used in bash programming
- if statement
- if-else statement
- if..elif..else..fi statement (Else If ladder)
- if..then..else..if..then..fi..fi..(Nested if)
- switch statement
Their description with syntax is as follows:
This block will process if specified condition is true.
if [ expression ] then statement fi
If specified condition is not true in if part then else part will be execute.
if [ expression ] then statement1 else statement2 fi
if..elif..else..fi statement (Else If ladder)
To use multiple conditions in one if-else block, then elif keyword is used in shell. If expression1 is true then it executes statement 1 and 2, and this process continues. If none of the condition is true then it processes else part.
if [ expression1 ] then statement1 statement2 . . elif [ expression2 ] then statement3 statement4 . . else statement5 fi
Nested if-else block can be used when, one condition is satisfies then it again checks another condition. In the syntax, if expression1 is false then it processes else part, and again expression2 will be check.
if [ expression1 ] then statement1 statement2 . else if [ expression2 ] then statement3 . fi fi
case statement works as a switch statement if specified value match with the pattern then it will execute a block of that particular pattern
When a match is found all of the associated statements until the double semicolon (;;) is executed.
A case will be terminated when the last command is executed.
If there is no match, the exit status of the case is zero.
case in Pattern 1) Statement 1;; Pattern n) Statement n;; esac
$bash -f main.sh a is not equal to b
$bash -f main.sh a is equal to b
$bash -f main.sh Headquarters - Chennai, Tamil Nadu, India.
Note: Shell scripting is a case-sensitive language, which means proper syntax has to be followed while writing the scripts.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.