shell学习笔记之条件(二)

test或者[

#检查文件是否存在
if test -f read.c
then
...
fi

if [ -f read.c ]
then
...
fi

#如果then和if在同一行上,就应该用;把if和then分开
if [ -f read.c ];then
...
fi

注意:

1.if空格[空格xxx空格]都有空格
2.test命令的退出码(表明条件是否满足),决定是否要执行后面的代码

------------------------------------------------------------------------------

字符串比较

string1 == string2
string1 != string2
-n string            字符串不为空
-z string             字符串为null(一个空串)

算数比较

exp1 -eq exp2    ==
exp1 -ne exp2    !=
exp1 -gt exp2    >
exp1 -ge exp2    >=
exp1 -lt exp2    <
exp1 -le exp2    <=
!exp1

文件有关的测试

-d file        目录
-e file        文件存在,不可移植,常用-f
-f file        普通文件

-r file        文件可读
-w file        文件可写
-x file        文件可执行
-s file        文件大小不为0

-u file        文件的set-user-id位被设置则为真
-g file        文件的set-group-id位被设置则为真

使用
set-user-id        set-uid位授予了程序其拥有者的访问权限而不是其使用者的访问权限
set-group-id    set-gid
各种与文件有关的条件测试的结果为真的前提是文件必须存在

#!/bin/sh

if    [ -f /bin/bash ]
then
    echo "file /bin/bash exists"
fi

if    [ -d /bin/bash ]
then
    echo "file /bin/bash is a directory"
else
    echo "file /bin/bash is NOT a directory"
fi
原文地址:https://www.cnblogs.com/liulipeng/p/3337481.html