if
if表达式写法
1
2
3
4
5
6
7
8
9
| if condition1
then
command1
elif condition2
then
command2
else
commandN
fi
|
示例
1
2
3
4
5
6
7
8
9
10
11
| a=10
b=20
if [ $a = $b ]; then
echo "a 等于 b"
elif [ $a -gt $b ]; then
echo "a 大于 b"
elif [ $a -lt $b ]; then
echo "a 小于 b"
else
echo "没有符合的条件"
fi
|
输出结果
if else 语句经常与 test 命令结合使用,如下所示:
1
2
3
4
5
6
7
8
| num1=$[2*3]
num2=$[1+5]
if test $[num1] -eq $[num2]
then
echo '两个数字相等!'
else
echo '两个数字不相等!'
fi
|
输出结果
文件比较符
表达式 | 说明 |
---|
if [ -f file ] | 如果文件存在 |
if [ -d … ] | 如果目录存在 |
if [ -L file ] | 文件是否为符号链接 |
if [ -h file ] | 文件是否为软链接 |
if [ -s file ] | 如果文件存在且非空 |
if [ -r file ] | 如果文件存在且可读 |
if [ -w file ] | 如果文件存在且可写 |
if [ -x file ] | 如果文件存在且可执行 |
if [ -O file ] | 文件是否属于当前用户 |
if [ -G file ] | 文件是否属于当前用户组 |
if [ “file1” -nt “file2” ] | 判断file1是否比file2新 |
if [ “file1” -ot “file2” ] | 判断file1是否比file2旧 |
if [ int1 -eq int2 ] | 如果int1等于int2 |
if [ int1 -ne int2 ] | 如果不等于 |
if [ int1 -ge int2 ] | 如果>= |
if [ int1 -gt int2 ] | 如果> |
if [ int1 -le int2 ] | 如果<= |
if [ int1 -lt int2 ] | 如果< |
If [ $a = $b ] | 如果string1等于string2 |
if [ $string1 != $string2 ] | 如果string1不等于string2 |
if [ -n $string ] | 如果string 非空(非0),返回0(true) |
if [ -z $string ] | 如果string 为空 |
if [ $sting ] | 如果string 非空,返回0 (和-n类似) |
条件比较符
表达式 | 说明 |
---|
if [ 条件1 -o 条件2 ] | 或 || |
if [ 条件1 -a 条件2 ] | 与 && |