美文网首页
Shell 中 if 判断文件夹或文件是否存在

Shell 中 if 判断文件夹或文件是否存在

作者: 无味wy | 来源:发表于2022-11-27 16:45 被阅读0次

if比较的字符用法:

-e 判断对象是否存在

-d 判断对象是否存在,并且为目录

-f 判断对象是否存在,并且为常规文件

-L 判断对象是否存在,并且为符号链接

-h 判断对象是否存在,并且为软链接

-s 判断对象是否存在,并且长度不为0

-r 判断对象是否存在,并且可读

-w 判断对象是否存在,并且可写

-x 判断对象是否存在,并且可执行

-O 判断对象是否存在,并且属于当前用户

-G 判断对象是否存在,并且属于当前用户组

-nt 判断file1是否比file2新  [ "/data/file1" -nt "/data/file2" ]

-ot 判断file1是否比file2旧  [ "/data/file1" -ot "/data/file2" ]

 

-eq           //等于

-ne           //不等于

-gt            //大于

-lt            //小于

-ge            //大于等于

-le            //小于等于

 

 

在if中多次判断:

||                    单方成立;

&&                   双方都成立表达式。

if判断的几个实例:

文件夹不存在则创建

if [ ! -d "/data/" ];then

mkdir /data

else

echo "文件夹已经存在"

fi

文件存在则删除

if [ ! -f "/data/filename" ];then

echo "文件不存在"

else

rm -f /data/filename

fi

判断文件夹是否存在

if [ -d "/data/" ];then

echo "文件夹存在"

else

echo "文件夹不存在"

fi

判断文件是否存在

if [ -f "/data/filename" ];then

echo "文件存在"

else

echo "文件不存在"

fi

if的嵌套
格式一:

  if [ condition ]
  then 
        if [ condition ]
        then 
            commands1
        else
            commands2
         fi    
   fi

格式二:

if [ condition ]
then 
    if [ condition ]
    then 
         commands1
    else    
         commands2
    fi
else
    commands3
fi

相关文章

网友评论

      本文标题:Shell 中 if 判断文件夹或文件是否存在

      本文链接:https://www.haomeiwen.com/subject/dphkfdtx.html