Linux脚本编程中最基本的结构化语句为 if-then语句,if-then语句的格式如下:

if command
then
   commands
fi



执行过程为:首先运行在if行定义的命令,如果命令的退出码是0(成功执行命令)


,则将执行 then后面的命令,如果退出码不为0,then后的命令将不会执行,


例如:


$ cat test01                 
#!/bin/bash
#测试一个正常的命令
if date
then 
echo "date worked"
fi
$ ./test01
2017年 01月 03日 星期二 08:31:30 CST
date worked

下面是一个反面例子:

$ cat test02
#!/bin/bash
#测试一个不存在的命令
if asasaas
then 
    echo "the command doesn't work "
fi
echo "this is outside if statement"
$ ./test02
./test.sh:行3: asasaas: 未找到命令
this is outside if statement

注意:命令出错时的错误信息也会显示在屏幕上,可以使用重定向将其定位到其它地方。


用惯其它编程语言的同学会觉得 shell编程的if语句有点别扭,可以使用下面这种写法来:

if command;then
    commands
fi

分支判断语句还有下面两种形式:

if command
then 
    commands
else
    commands1
fi
===================此为分隔线===========================
if   command1
then 
    commands1
elif command2
then 
    commands2
elif command3
then 
    commands3
else 
    commands4
fi



上面介绍的if语句判断的都是shell命令的退出码,很多时候我们需要判断其它


条件,如数字比较,字符串比较等,在bash shell中可以使用test命令判断其它条件。


test 命令有两种写法:

1.第一种写法
if test condition
then 
   commands
fi
===============此为分隔线================================
2.第二种写法

if [ condition ]
then 
   commands
fi

使用第二种写法时一定要注意:前半个括号后面和后半个括号前面必须加个空格,否则会报错。


test命令可以判断以下3种条件:


a.数值比较


n1 -eq n2  检查n1是否相等n2                 n1 -le n2    检查n1是否小于或相等n2


n1 -ge n2  检查n1是否大于或等于n2     n1 -lt n2     检查n1是否小于n2


n1 -gt n2  检查n1是否大于n2                  n1 -ne n2   检查n1是否不相等n2



b.字符串比较



str1 = str2    检查str1与str2是否相同           str1 > str2  检查str1是否大于str2


str1! = str2   检查str1与str2是否不同           -n str1        检查str1长度是否大于0


str1 < str2    检查str1是否小于str2               -z str1        检查str1长度是否为0

需要注意的一点是:这里的 '>'和'<'需要转义 前面加个'\',例如

$ cat test03
#!/bin/bash
val1=hello
val2=hi
if [ $val1 \> $val2 ]
then 
    echo "$val1 > $val2"
else
    echo "$val1 < $val2"
fi
$ ./test04
hello < hi

c.文件比较



-d   file                 检查file是否存在并且是一个目录


-e   file                 检查是否存在 


-f    file                 检查file是否存在并且是一个文件


-r    file                 检查file是否存在并且可读


-s   file                 检查file是否存在并且不为空


-w  file                 检查file是否存在并且可写


-x   file                 检查file是否存在并且可执行


-O  file                 检查file是否存在并且被当前用户拥有


-G  file                 检查file是否存在并且默认组是否为当前用户组


file1 -nt file2      检查file1是否比file2新


file1 -ot file2      检查file1是否比file2旧