The IF statement determines which branch to execute by using relational operators to determine whether an expression is true or false. The Shell has three kinds of if ... else statements:
- If ... fi statement;
- If ... else ... fi statement;
- If ... else ... elif. Fi statement.
1) If ... else statement
Syntax for the IF ... else statement:
If [Expression]then Statement (s) to was executed if expression is Truefi
If expression returns True,then, the statement is executed and no statement is executed if False is returned.
Finally must end with FI to close the if,fi is if the inverted spelling, the back will also meet.
Note: There must be a space between expression and square brackets ([]), or there will be a syntax error.
As an example:
- #!/bin/sh
- A=ten
- b=
- If [ $a = = $b ]
- Then
- Echo "A is equal to B"
- Fi
- If [ $a! = $b ]
- Then
- Echo "A is not equal to B"
- Fi
Operation Result:
A is not equal to B
2) If ... else ... fi statement
Syntax for the If ... else ... fi statement:
If [Expression]then Statement (s) to being executed if expression is TrueElse Statement (s) to be executed if express Ion is not Truefi
If expression returns true, then the statement behind the then will be executed, otherwise the statement behind the else is executed.
As an example:
- #!/bin/sh
- A=ten
- b=
- If [ $a = = $b ]
- Then
- Echo "A is equal to B"
- Else
- Echo "A is not equal to B"
- Fi
Execution Result:
A is not equal to B
3) If ... elif ... fi statement
The If ... elif. FI statement can judge multiple conditions, with the syntax:
If [expression 1]then Statement (s) to BES executed if expression 1 is trueelif [expression 2]then Statement (s) To being executed if expression 2 is trueelif [expression 3]then Statement (s) to was executed if Expression 3 is Trueels E Statement (s) to being executed if no expression is Truefi
Which expression evaluates to true, executes the statement after which expression is executed, and if it is false, no statement is executed.
As an example:
- #!/bin/sh
- A=ten
- b=
- If [ $a = = $b ]
- Then
- Echo "A is equal to B"
- Elif [ $a -gt $b ]
- Then
- Echo "A is greater than B"
- Elif [ $a -lt $b ]
- Then
- Echo "A is less than B"
- Else
- echo "None of the condition met"
- Fi
Operation Result:
A is less than B
The IF ... else statement can also be written as a line and run as a command, like this:
- If test $[2*3] -eq $[1+5]; Then echo ' The numbers is equal! ' ; fi;
The IF ... Else statement is also often used in conjunction with the Test command, as follows:
- NUM1=$[2*3]
- num2=$[1+5]
- If test $[num1] -eq $[num2]
- Then
- echo ' The numbers is equal! '
- Else
- echo ' The numbers is not equal! '
- Fi
Output:
The numbers is equal!
The test command is used to check if a condition is true, similar to square brackets ([]).
Shell Scripting Learning 16 shell if Else statement