有提供给你几个比较优雅的选择。
一个将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
这种方法使你的脚本很短。这种方法唯一可能的缺点是它不会报告缺少哪些文件类型。
你知道'find'命令吗? –
没有。我还是新手bash – mots
类似于'find -name'* .torrent'-o -name'* .zip'-o -name'* .deb'-delete'会完全绕过你的问题,但可能不会你想要什么,因为它没有报告什么时候没有给定类型的文件开始。 –