删除特定文件的Bash脚本

3

我正在处理一个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

你知道find命令吗? - Mad Physicist
不,我还不熟悉Bash。 - mots
1
类似于 find -name '*.torrent' -o -name '*.zip' -o -name '*.deb' -delete 这样的命令可以完全避免你的问题,但可能并不是你想要的,因为它不会报告一开始就没有给定类型的文件。 - Mad Physicist
2个回答

2
你可以这样做:
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

1

您有几个相对优雅的选项可供选择。

其中之一是将 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

这种方法可以让你的脚本变得非常简短。对于你的目的来说,唯一可能的缺点是它不会报告缺少哪些文件类型。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接