文件、目录属性判断

接收用户的输入
read -t 30 -p "please input a number." n //-t为时间30秒

1.[ -f file ]判断是否是普通文件,且存在为真
[root@localhost shell]# f="./if01.sh"
[root@localhost shell]# [ -f $f ]&&echo ok || echo no
ok

[root@localhost ~]# vi file01.sh
#!/bin/bash
f="/tmp/lsxlinux"
if [ -f $f ]
then
echo $f exist
else
touch $f
fi

[root@localhost ~]# bash -x file01.sh //-x查看执行的步骤

  • f=/tmp/lsxlinux
  • '[' -f /tmp/lsxlinux ']'
  • touch /tmp/lsxlinux
    [root@localhost ~]# bash -x file01.sh
  • f=/tmp/lsxlinux
  • '[' -f /tmp/lsxlinux ']'
  • echo /tmp/lsxlinux exist
    /tmp/lsxlinux exist

2.[ -d file ] 判断是否是目录,且存在为真
[root@localhost shell]# [ -d ./lsx ] && echo ok || echo no
no

#!/bin/bash
d="/tmp/lsxlinux"
if [ -d $d ]
then
echo $d exist
else
touch $d
Fi

[root@localhost ~]# bash -x file02.sh

  • f=/tmp/lsxlinux
  • '[' -d /tmp/lsxlinux ']'
  • touch /tmp/lsxlinux

3.[ -e file ] 判断文件或目录存在为真,不辨明是目录还是文件
[root@localhost shell]# if [ -e ./lsx ];then echo exists;else echo on;fi //目录不存在
on
[root@localhost shell]# if [ -e ./if03.sh ];then echo exists;else echo on;fi //文件存在
exists
[root@lr shell]# [ -e if09.sh ]&&echo ok||echo no
no

4.[ -r file ] 判断文件存在且可读为真
#!/bin/bash
f="/tmp/lsxlinux"
if [ -r $f ]
then
echo $f read
fi

[root@localhost ~]# bash -x file02.sh

  • f=/tmp/lsxlinux
  • '[' -r /tmp/lsxlinux ']'
  • echo /tmp/lsxlinux read
    /tmp/lsxlinux read

5.[ -w file ] 判断文件存在且可写为真
#!/bin/bash
f="/tmp/lsxlinux"
if [ -w $f ]
then
echo $f write
fi

[root@localhost ~]# bash -x file02.sh

  • f=/tmp/lsxlinux
  • '[' -w /tmp/lsxlinux ']'
  • echo /tmp/lsxlinux write
    /tmp/lsxlinux write
  1. [ -x file ] 判断文件存在且可执行为真
    #!/bin/bash
    f="/tmp/lsxlinux"
    if [ -x $f ]
    then
    echo $f exe
    fi

[root@localhost ~]# bash -x file02.sh

  • f=/tmp/lsxlinux
  • '[' -x /tmp/lsxlinux ']'

##判断存在的情况
#!/bin/bash
f="/tmp/lsxlinux"
[ -f $f ] && rm -f $f
#if [ -f $f ]
#then

rm -f $f

#fi

//判断不存在
#!/bin/bash
f="/tmp/lsxlinux"
[ -f $f ] && touch $f
if [ ! -f $f ]
then
touch $f
fi




本文转自 虾米的春天 51CTO博客,原文链接:http://blog.51cto.com/lsxme/2058289,如需转载请自行联系原作者

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值