判断文件是否存在

参考博客:理解bash的if语句

if语法:和大多语言差不多,condition为'true' 就yes,不然就no
if condition; then
   yes
else
   no
fi

首先创建一个测试文件existed.txt,建立shell脚本testFile.sh

touch existed.txt
vim testFile.sh
#法一:if ls重定向
#!/bin/bash

file=existed.txt
# ls结果重定向到null
if ls $file &> /dev/null ; then
    echo "file existed!";
else
    echo "not exist!";
fi

exit 0

运行结果入下

lean@lean-Aspire-E1-471G:~/testdir$ ./testFile.sh 
file existed!

法二:test

man test 中如是

SYNOPSIS
       test EXPRESSION
       test

       [ EXPRESSION ]
       [ ]
       [ OPTION

部分测试代码

if test -f $file ; then
    echo "yes!";
else
    echo "no!";
fi
exit 0

   参数-f表示检测文件是否存在

运行结果

lean@lean-Aspire-E1-471G:~/testdir$ ./testFile.sh 
yes!

法三: [option file  ]  

这种方法一开始不是很理解,经过参考博客似乎明白了,其实也是test ,

test expression  
or
[ expression ]
if [ -f $file ] ; then
    echo "here"
else
    echo "no"
fi

exit 0

运行结果

lean@lean-Aspire-E1-471G:~/testdir$ ./testFile.sh 
here

bash中if语句和c/c++中的condition有许多不同的地方,还有许多坑等着去踩

多行注释

多行注释的方法也放这了吧

:<<here(注释标识,可随便写)
.........
要注释的代码
here

效果如图

判断文件是否存在













你可能感兴趣的:(shell,if)