用于删除特定文件的Bash脚本

用于删除特定文件的Bash脚本,bash,terminal,Bash,Terminal,我正在编写这个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 *.z

我正在编写这个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

你可以这样做:

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

您可以选择几个相对优雅的选项

一种方法是将
rm
包装到一个函数中,该函数检查文件夹中是否有任何您想要删除的文件类型。您可以使用
ls
检查是否有与通配符匹配的文件,如下所示:

这个版本很好,因为它按照您最初计划的方式安排了所有内容

在我看来,一个更干净的版本应该是只查看与您的模式相匹配的文件。正如我在评论中所建议的,您可以使用一个
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

此方法使脚本非常简短。对于您来说,此方法唯一可能的缺点是它不会报告丢失的文件类型。

您知道
find
命令吗?不知道。我对bash还是新手,类似
find-name'*.torrent'-o-name'*.zip'-o-name'*.deb'-delete
的方法可以完全避免您的问题,但可能不是您想要的,因为当没有给定类型的文件时,它不会报告。
#!/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