In the shell of Linux
The IF statement determines which branch to execute through the relational operator to determine the true or false of an expression. The Shell has three kinds of if ... else statements:
If ... fi statement;
if ... else ... fi statement, if ... elif ... other ...
fi statement.
1 If ... else statement
Syntax for if ... else statement:
If [expression]
then
Statement (s) to was executed if expression is true
fi
Note: If expression returns the statement after True,then, it will be executed, and if false, no statements are executed.
Finally, you have to end up with fi. If,fi is if the spelling is reversed and will be met later.
Note: There must be a space between the expression and the square brackets ([]), otherwise there will be a syntax error.
For example:
#!/bin/sh
a=10
b=20
if [$a = = $b]
then
echo "A is equal to B"
fi
If [$a!= $b]
t Hen
echo "A isn't equal to B"
fi
Run Result:
A is isn't equal to B
2 If ... else ... fi statementSyntax for if ... else ... fi statement:
If [expression]
then
Statement (s) to be executed if expression am true
else
Statement (s) to be executed If expression is not true
fi
If expression returns true, then the statement behind then will be executed, otherwise the statement behind else is executed.
As an example:
#!/bin/sh
a=10
b=20
if [$a = = $b]
then
echo "A is equal to B"
else
echo "a" isn't equal to B "
fi
Execution results:
A is isn't equal to B
3 If ... elif ... fi statementIf ... the elif-fi statement can be used to determine multiple conditions, the syntax is:
If [expression 1]
then
Statement (s) to am executed if expression 1 is true
elif [expression 2]
Then
statement (s) to was executed if Expression 2 is true
elif [expression 3]
then
Statement (s) to be executed I F expression 3 is true
else
Statement (s) to am executed if no expression is true
fi
Which expression evaluates to true, executes the statement after which expression, and if all is false, does not execute any statements.
As an example:
#!/bin/sh
a=10
b=20
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
Run Result:
A is less than B
The IF ... else statement can also be written as a line, running as a command, like this:
if test $[2*3]-eq $[1+5]; Then echo ' The two numbers are equal! '; Fi
The IF ... else statement is often used in conjunction with the Test command, as follows:
NUM1=$[2*3]
num2=$[1+5]
if test $[num1]-eq $[num2]
then
Echo '
two numbers are ' else
Echo ' The two numbers are not equal! '
Fi
Output:
The two numbers are equal!
The test command checks to see if a condition is set up, similar to the square brackets ([]).