Linux笔记:shell脚本测试文件

除了测试字符串和算术式,用户还经常需要测试文件(或目录)的状态,下表列出了文件测试的常用选项。

选项作用
-e File如果文件File存在(Exist),则为True
-s File如果文件File存在且文件大小(Size)大于零,则为True
-f File如果文件File存在且是普通文件(File),则为True
-d File如果文件File存在且是目录(Directory),则为True
-b File如果文件File存在且是块(Block)特殊文件,则为True
-c File如果文件File存在且是字符(Character)特殊文件,则为True
-L File如果文件File存在且是符号链接(Link)文件,则为True
-r File如果文件File存在且是可读的(Readable),则为True
-w File如果文件File存在且是可写的(Writable),则为True
-x File如果文件File存在且是可执行的(Executable),则为True
-O File如果文件File存在且属于当前用户(Owner),则为True
-G File如果文件File存在且属于当前用户组(Group),则为True
File1 -nt File2如果文件File1新于(Newer Then) File2,则为True
File2 -ot File2如果文件File1旧于(Older Then) File2,则为True

例如:

#!/bin/bash
echo -n "Please input the file name:"
read filename
if [ ! -e $filename ]
then
        echo "File"${$filename}"not exist."
        exit
fi

if [ -f $filename ]
then
        echo "File "${filename}" is an ordinary file."
elif [ -d $filename ]
then
        echo "File "${filename}" is a directory file."
else
        echo "File "${filename}" is neither an ordinary file nor a directory file."
fi

上述shell脚本解释:

  • 脚本接收用户输入的文件名后,判断该文件是否存在。如果不存在,则输出错误信息并结束。
  • 如果存在,判断是普通文件还是目录文件,输出相应信息,如果既不是普通文件也不是目录文件,则执行else后面的语句输入相应信息。
  • 符号"!"表示把逻辑值取反。
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值