Shell Learning 15 - Shell if else statement

The if statement uses relational operators to determine the truth of the expression to decide which branch to execute. Shell has three kinds of if ... else statements:
if ... fi statements;
if ... else ... fi statements;
if ... elif ... else ... fi statements.
1) if ... else statement
Syntax of if ... else statement:
if [ expression ]
then
Statement(s) to be executed if expression is true
be
If expression returns true, the statement following then will be executed; if it returns false, no statement will be executed.
Finally, it must end with fi to close the if. fi is the reverse spelling of if, which will be met later.
Note: There must be a space between expression and 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"
be
if [ $a != $b ]
then
echo "a is not equal to b"
be
operation result:
a is not equal to b
2) if ... else
... fi statement The syntax of the if ... else ... fi statement:
if [ expression ]
then
Statement(s) to be executed if expression is true
else
Statement(s) to be executed if expression is not true
be
If expression returns true, then the statement after then will be executed; otherwise, the statement after else is executed.
for example:
#!/bin/sh
a=10
b=20
if [ $a == $b ]
then
echo "a is equal to b"
else
echo "a is not equal to b"
be
Results of the:
a is not equal to b
3) if ... elif ... fi statement
The if ... elif ... fi statement can judge multiple conditions, the syntax is:
if [ expression 1 ]
then
Statement(s) to be executed if expression 1 is true
elif [ expression 2 ]
then
Statement(s) to be executed if expression 2 is true
elif [ expression 3 ]
then
Statement(s) to be executed if expression 3 is true
else
Statement(s) to be executed if no expression is true
be
Whichever expression evaluates to true, executes the statement following the expression; if both are false, executes no statement.
for 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"
be
operation result:
a is less than b
The if ... else statement can also be written on one line and run 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 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 two numbers are equal!'
else
echo 'The two numbers are not equal!'
be
output:
The two numbers are equal!
The test command is used to check whether a condition is true, similar to square brackets ([ ]).

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325683538&siteId=291194637