linux shell 学习(三)——判断文件和文件夹

来源:互联网 发布:网络机顶盒爱奇艺会员 编辑:程序博客网 时间:2024/05/01 01:42

linux shell 学习(三)——判断文件和文件夹

下面是判断文件和文件夹的相关例子:
主要有如下几个方法:
-d 文件夹是否存在
-e 文件夹或文件是否存在
-f 文件是否存在
-s 文件是否存在且非空
-r 文件是否可读
-w 文件是否可写
-x 文件是否可执行
-O 文件是否存在,且归当前用户所有
-G 文件是否存在,且文件所属组合当前用户所属组相同
file1 -nt file2  文件1是否创建时间比文件2晚
file1 -ot file2 文件1是否比文件2创建时间早

下面是一个简单的例子:
#!/bin/bashif [ -d $HOME ]thenecho 'home is exist'cd $HOMEls -a elseecho 'home is not exist'fiif [ -e ~/xyshell ]thenecho '/xyshell exist'cd ~/xyshellif [ -d ./testing ]thenecho 'there is a testing dir'elsemkdir testingficd testing/if [ -f ./now.txt ]thenecho 'add new date'date >> now.txtelseecho 'add new file and add new date'date > now.txtfifiif [ -d ~/xyshell/testing ] && [ -f ~/xyshell/testing/now.txt ]thenecho 'dictionary exists and file exists'elseecho 'dictionary or file does not exists'fiif [ -d ~/xyshell/testing ] || [ -f ~/xyshell/testing/now.txt ]thenecho 'dictionary or file exists'elseecho 'dictionary and file do not exist'fi

运行效果:

0 0