table of Contents
In Shell programming, if statements are often used when judging. However, there are some differences between if statements in Shell and C/C++/Java and other languages, which are explained below with examples.
1. Basic grammar
The if statement mainly has the following forms.
1.1 if
(1) Form one
if condition; then
符合 condition 的执行语句
fi
Note: At the end, the if is reversed and written fi as the end sign.
(2) Form two
You can write then on one line with if, or write it in separate lines, as shown below:
if condition
then
符合 condition 的执行语句
fi
1.2 if else
A single if else statement is as follows:
if condition
then
符合 condition 的执行语句
else
不符合 condition 的执行语句
fi
Here then can also be written in one line with if.
1.3 if elif
Note: In Shell, else if is abbreviated as elif, elif must also have then, as shown below:
if condition_1
then
符合 condition_1 的执行语句
elif condition_2
then
符合 condition_2 的执行语句
else
不符合 condition_1 和 condition_2 的执行语句
fi
Of course, there are more combinations, which are not explained here.
2. Examples
2.1 if statement
#!/bin/bash
file="/root"
#形式一
if [ -d $file ]; then
echo "$file is directory!"
fi
#形式二
if [ -d $file ]
then
echo "$file is directory!"
fi
2.2 if else statement
#!/bin/bash
file="/root"
if [ -d $file ]
then
echo "$file is directory!"
else
echo "$file is not directory!"
fi
2.3 if elif statement
#!/bin/bash
file="/root"
if [ -f $file ]
then
echo "$file is regular file!"
elif [ -d $file ]
then
echo "$file is directory!"
else
echo "$file is not regular file and directory"
fi
Three, summary
The judgment logic of if statement is common to various programming languages. In Shell, pay attention to the use of fi at the end of the if statement (if written in reverse), else if should be written as elif, and don't forget then when writing if and elif.