shell基础——判断

if语法:

if [条件];then
    command
fi


if [条件];then
    command
else
    command
fi


if [条件1];then
    command1
elif [条件2];then
    command2
else [条件3];then
    command3
fi

 

case语法:

case "choice" in
    "var1")
        command
      ;;
    "var2")
        command
      ;;
    *)
        command
esac


例:
case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart)
        stop
        start
        ;;
    *)
        echo $"Usage:{start|stop|restart}"
        exit1
esac

 

 

判断文件:

test或者[],test -e $file或[ -e $file ]

[ -e $file ]    判断是否存在
[ -f $file ]    判断是否为普通文件
[ -d $dir ]    判断是否为目录
-S    socket
-p    pipe
-c    character
-b    block
-L    软链接

 

文件权限判断:

[ -r $file ]    判断当前用户是否可读
-w    可写
-x    可执行
-u    是否有suid
-g    是否有sgid
-k    是否有t位
-s    是否为空白文件

 

两个文件比较判断:

[ $file1 -nt $file2 ]    比较file1是否比file2新
-ot    比较file1是否比file2旧     
-ef    比较是否为同一个文件,或者判断硬链接(指向同一个inode)

 

整数之间的判断:

[ $? -eq 0 ]    相等
-ne    不等
-gt    大于
-lt    小于
-ge    大于等于
-le    小于等于

 

字符串之间的判断:

-z    是否为空字符串
-n    是否为非空字符串
string1 = string2    是否相等
string1 != string2    是否不等

 

多重条件判断:

逻辑与,两个条件同时满足,才为true
if [ condition1 -a condition2 ]  
if [ condition1 ] && [ condition2 ]
if [[ condition1 && condition2 ]]

逻辑或,两个条件满足其一,就为true
if [ condition1 -o condition2 ]  
if [ condition1 ] || [ condition2 ]
if [[ condition1 || condition2 ]]

 

posted @ 2016-10-26 20:14  沄持的学习记录  阅读(131)  评论(0)    收藏  举报