The Bourne Shell's if statement is the same as most programming languages-the detection condition is true, and if the condition is true, the shell executes the code block specified by the IF statement, and if the condition is false, the shell skips the if code block and continues executing the code.
Syntax for an IF statement:
The code is as follows:
If [judging condition]
Then
Command1
Command2
........
Last_command
Fi
Example:
#!/bin/bash
number=150
If [$number-eq 150]
Then
echo "Number is 150"
Fi
If-else statement:
In addition to the standard if statement, we can also add an else code block to extend the IF statement. The main purpose of doing so is to execute the code block in the IF if condition is true, and if the IF condition is false, execute the code block in the Else statement.
Grammar:
The code is as follows:
If [judging condition]
Then
Command1
Command2
........
Last_command
Else
Command1
Command2
........
Last_command
Fi
Example:
The code is as follows:
#!/bin/bash
number=150
If [$number-GT 250]
Then
echo "Number is greater"
Else
echo "number is smaller"
Fi
If.. Elif.. else.. Fi Statement (abbreviated else IF)
In the Bourne Shell's if statement syntax, the code block in the Else statement executes when the IF condition is false. We can also embed if statements together to implement multiple condition detection. We can use the ELIF statement (the abbreviation of else if) to construct multiple-condition detection.
Grammar:
The code is as follows:
If [judgment condition 1]
Then
Command1
Command2
........
Last_command
elif [judgment Condition 2]
Then
Command1
Command2
........
Last_command
Else
Command1
Command2
........
Last_command
Fi
Example:
The code is as follows:
#!/bin/bash
number=150
If [$number-GT 300]
Then
echo "Number is greater"
elif [$number-lt 300]
Then
echo "number is smaller"
Else
echo "number is equal to actual value"
Fi
Multiple IF statements:
If and ELSE statements can be nested in a bash script. The keyword "fi" indicates the end of the inner if statement, and all if statements must end with the keyword "fi".
Nested syntax for the base if statement:
The code is as follows:
If [judgment condition 1]
Then
Command1
Command2
........
Last_command
Else
If [Judgment condition 2]
Then
Command1
Command2
........
Last_command
Else
Command1
Command2
........
Last_command
Fi
Fi
Example:
The code is as follows:
#!/bin/bash
number=150
If [$number-eq 150]
Then
echo "Number is 150"
Else
If [$number-GT 150]
Then
echo "Number is greater"
Else
echo "' number is smaller"
Fi
Fi