There are control structures in all programming languages, and shell programming is no exception. The IF structure is the most commonly used branch control structure.
The most common if statements in Linux Shell programming are: If.....then...fi,if....then....else....fi,if....then...elif ...
If....then.....else ... The statement is very simple and the syntax is as follows:
An If expression
then command table
[Else Command table]
Fi
The expression is the judgment condition, the command table is when the conditional execution of the shell command, FI represents the end of the entire if statement, must have.
Let's look at an example:
#!/bin/bash
#filename: if.sh
#author: gyb
read num
($num-lt];then
echo "$num <10"
else
echo "$num >10"
fi
Increase executable Permissions
root@ubuntu:~# chmod +x if.sh
Perform
root@ubuntu:~#./if.sh
2
2<10
root@ubuntu:~#./if.sh
24
24>10
The code [$num-lt 10] is another way of writing the test command, which requires a space before ' [' and '] '.
If....then....elif ..... is a elif structure that can be written indefinitely if the program requires it (where elif represents the abbreviation of else if).
Example:
#!/bin/sh
#filename: elif.sh
#author: gyb
echo "Input score:"
read score
if [$score-ge 0-a $score- Lt];then
echo "E"
elif [$score-ge 60-a $score-lt];then
echo "D"
elif [$score-ge 70-a $score -lt];then
echo "C"
elif [$score-ge 80-a $score-lt];then
echo "B"
elif [$score-ge 90-a $ Score-le];then
echo "A"
else
echo "input error"
fi
The code in the judgement condition in the criterion-a represents the logic and the entire expression is true only if the two conditions are set at the same time.
To add executable permissions:
root@ubuntu:~# chmod +x elif.sh
Perform
root@ubuntu:~#./elif.sh
Input score:
34
E
root@ubuntu:~#./elif.sh
Input score:
67
D
root@ubuntu:~#./elif.sh
Input score:
78
C
root@ubuntu:~#./elif.sh
Input score:
89
B
root@ubuntu:~#./elif.sh
Input score:
99
A
If statements can be nested and can be nested in multiple sets
Example:
#!/bin/bash
#filename: ifnest.sh
#author: gyb
read num
($num-lt];then
echo "$num <100"
if [$num-lt];then
echo "$num <50"
if [$num-lt];then
echo "$num <30"
fi
fi
F I
Add executable permissions
root@ubuntu:~# chmod +x ifnest.sh
Perform
root@ubuntu:~#./ifnest.sh
23
23<100
23<50
23<30
root@ubuntu:~#./ifnest.sh
45
45<100
45<50
End.