2016-12-01 70 views
0

我需要检查文件在Unix中的存在。如果文件存在,那么我必须从该位置删除该文件。检查文件的存在

if (file exists) 
then 
    delete the file 
fi 
+4

为什么不直接删除,如果即'/斌/ RM -f ' –

回答

2

您可以使用

[ -e file ] && rm file 
+0

这可能导致出错的形式:' rm:无法删除'文件':是一个目录' –

2

希望这有助于。

if [ -f /home/mfyounus/test/aaa ]; then 

    rm -f /home/mfyounus/test/aaa 
    echo "File \"/home/mfyounus/test/aaa\" Deleted" 

else 

    echo "File not found" 

fi 
+0

这只适用于文件是“常规”文件的情况 - 例如,如果它是块设备,符号链接,FIFO或目录,它将会失败。 –

0

所以最好做rm -f test 这将忽略不存在的文件和参数,从不提示。

如果你想知道文件是否存在,然后删除,你可以做

test -f file && { echo "File exists. Deleting it"; rm -f file ; }