Shell scripting, there are three kinds of control structure are: sequential structure, conditional judgment structure, loop structure. This article summarizes the use of conditional judgment constructs in shell scripts.
The structure of conditional judgment is divided into three kinds, single branch, double branch, multi Branch, and so on.
The syntax for a single branch structure is as follows:
if [expression]; then
Statement1
Statement2
.........
Fi
Two-branch syntax structure:
if [Expression];then
Statement1
Statement2
.....
Else
Statement3
Statement4
......
Fi
Multi-branch syntax structure:
if [Expresion1];then
Statement1
....
elif [Expression2];then
Statement2
......
elif [Expression3];then
Statement3
......
Else
Statement4
......
Fi
You need to be aware of when to use then, and then the semicolon in front of it is essential, otherwise it will go wrong.
If always paired with fi
If or elif, there must be then.
Multi-branch Conditional statement instance:
[email protected] sh]# cat test.sh
#!/bin/bash
Read-p ' Please input your file ' file
#FILE =/etc/passwddd
if [!-e $FILE];then
echo "$FILE is not exist"
Exit 3
Fi
If [-F $FILE];then
echo "$FILE is common FILE"
elif [-D $FILE];then
echo "$FILE is directory FILE"
elif [-X $FILE];then
echo "$FILE can be excuteable"
elif [-W $FILE];then
echo "$FILE can be written"
elif [-R $FILE];then
echo "$FILE can read"
Else
echo "Unkown file"
Fi
Shell script Programming: Conditional judgment if Statement usage summary