Linux删除脚本

标签 linux macos bash shell

我编写了一个 shell 脚本(称为 Trash.sh),当它运行时会显示我的“垃圾箱”目录中的所有文件,并询问用户是否希望逐一删除每个文件。脚本如下:

#if directory is empty, display message
if test ! -f ~/dustbin/* 
then
echo "Directory is empty"
#if directory is not empty, then display each item and ask to delete
else
for resfile in ~/dustbin/* #for each file in directory, store it in resfile variable
do
    if test -f $resfile ; then #if a file exists
    echo "Do you want to delete $resfile?"
    echo "Enter y or n"
    read ans #store user input in ans variable
    if test $ans = y ; then
    rm $resfile
    echo "File $resfile was deleted"
    fi
    fi
done
fi

这对我来说很好用。当用户键入 sh Trash.sh 时,脚本将正常运行,将显示每个文件并询问用户是否删除它。但是,我想添加的是用户键入 sh Trash.sh -a 的选项,目录中的所有文件无需确认即可自动删除。

我对如何实现这一点有点困惑。有什么想法吗?

ps - 我正在使用 Mac OS X 10.6.4 并通过终端执行所有操作

最佳答案

我建议使用 getopts 捕获 -a 选项。然后稍后对其进行测试并使用 rm -f (强制执行,请参见手册页)。 Mac OS 上的 shell 与我习惯的有点不同,但在 Linux 上处理 bash 中的选项看起来像这样:

force_all='f';
while getopts "ahv" arg
do
    case $arg in
        a) force_all='t';;
        v) echo "$SCRIPT: $VERSION"; exit;;
        h|*) echo "$SCRIPT: $HELP"; exit;;
    esac
done

这个例子展示了如何实现 -v 版本和 -h 帮助。

关于Linux删除脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4154573/

相关文章:

linux - 为什么 EAGAIN 在 pthread_key_create 发生?

linux - Windows 和 Linux 中的 QtMultimedia 包含

objective-c - 如何获取最近打开的文件列表?

php - 如何使用 AMPPS 和 Mac OS 10.9.4 在 php 中安装 imagick 作为扩展

bash - 如何使用 shell 验证 IPv6 地址格式?

linux - 在 ubuntu bash 脚本中,当我尝试转换错误的十六进制值时不会抛出任何错误

c - ld.so 中是否有任何宏或指针可以给我所有 plt 部分的地址范围?

ruby-on-rails - 尝试使用 vagrant 安装预先配置的虚拟盒。初始化失败

string - 读取文件,并将每一行提取为它自己的变量 [Bash]

bash - 按年求和并用 0 插入缺失的条目