2017-10-08 84 views
2

我正在处理这个应该删除特定扩展名的文件的bash脚本,我不希望它返回一个没有这样的文件或目录输出,当我检查这些文件是否仍然存在。相反,我希望它返回一个自定义消息,如:“您已经删除了这些文件”。 这里是脚本:Bash脚本删除一个特定的文件

#!/usr/bin/env bash 
read -p "are you sure you want to delete the files? Y/N " -n 1 -r 
echo 
if [[ $REPLY =~ ^[Yy]$ ]] 
then 
    rm *.torrent 
    rm *.zip 
    rm *.deb 
echo "all those files have been deleted............." 
fi 
+0

你知道'find'命令吗? –

+0

没有。我还是新手bash – mots

+1

类似于'find -name'* .torrent'-o -name'* .zip'-o -name'* .deb'-delete'会完全绕过你的问题,但可能不会你想要什么,因为它没有报告什么时候没有给定类型的文件开始。 –

回答

0

有提供给你几个比较优雅的选择。

一个将rm包装在一个函数中,该函数检查是否有任何要删除文件夹中的文件。你可以使用ls,以检查是否有符合通配符的任何文件,按照this question

#!/usr/bin/env bash 

rm_check() { 
    if ls *."${1}" 1> /dev/null 2>&1; then 
     rm *."${1}" 
     echo "All *.${1} files have been deleted" 
    else 
     echo "No *.${1} files were found" 
    fi 
} 

read -p "are you sure you want to delete the files? Y/N " -n 1 -r 
echo 
if [[ $REPLY =~ ^[Yy]$ ]]; then 
    rm_check torrent 
    rm_check zip 
    rm_check deb 
fi 

这个版本是不错的,因为它拥有一切奠定了最初计划的方式。

在我看来,一个更清洁的版本只能查看与您的模式相匹配的文件。正如我在评论中建议,你可以用一个单一的find命令做到这一点:

#!/usr/bin/env bash 
read -p "are you sure you want to delete the files? Y/N " -n 1 -r 
echo 
if [[ $REPLY =~ ^[Yy]$ ]]; then 
    find -name '*.torrent' -o -name '*.zip' -o -name '*.deb' -delete 
    echo "all those files have been deleted............." 
fi 

这种方法使你的脚本很短。这种方法唯一可能的缺点是它不会报告缺少哪些文件类型。

1

你可以这样做:

rm *.torrent *.zip *.deb 2>/dev/null \ 
&& echo "all those files have been deleted............." \ 
|| echo "you have already removed the files" 

这将在存在的所有文件按预期方式工作, 当他们都不存在。

你没有提到如果他们中的一些存在但不是全部该怎么办。 例如,有一些.torrent文件,但没有.zip文件。

添加第三个情况, 其中只有一些文件都在那里(现在删除), 你需要检查取消对每个文件类型, 的退出代码和生成基于该报告。

这里有一个办法做到这一点:

rm *.torrent 2>/dev/null && t=0 || t=1 
rm *.zip 2>/dev/null && z=0 || z=1 
rm *.deb 2>/dev/null && d=0 || d=1 

case $t$z$d in 
    000) 
    echo "all those files have been deleted............." ;; 
    111) 
    echo "you have already removed the files" ;; 
    *) 
    echo "you have already removed some of the files, and now all are removed" ;; 
esac