gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 04:09:05 25 4
gpt4 key购买 nike

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

关于用于删除特定文件的 Bash 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46631787/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com