【问题标题】:bash shell script to delete directory only if there are no files仅在没有文件时才删除目录的 bash shell 脚本
【发布时间】:2014-04-16 23:08:29
【问题描述】:

好的,所以我正在编写一个 shell 脚本来删除一个目录,但前提是里面没有文件。

我想要做的是有一个 if 语句,它将检查目录中是否有文件,如果有文件,则询问用户是否要先删除文件,然后再删除目录。

我对此进行了相当多的研究,并找到了一种方法来检查目录中是否存在文件,但我无法通过那个阶段。

这是我目前创建的用于检查目录中是否存在文件的 if 语句:

echo "Please type the name of the directory you wish to remove "

                read dName
        shopt -s nullglob
        shopt -s dotglob
        directory=$Dname

        if [ ${#directory[@]} -gt 0 ];
        then
                echo "There are files in this directory! ";
        else
                echo "This directory is ok to delete! "
        fi
        ;;

【问题讨论】:

  • rmdir 默认情况下已经这样做了。
  • 顺便说一句,对于 shell 脚本,通过 $@$n 变量而不是(或至少补充)键盘交互来接受参数更方便。

标签: bash shell unix


【解决方案1】:

你不需要检查; rmdir 只会删除空目录。

$ mkdir foo
$ touch foo/bar
$ rmdir foo
rmdir: foo: Directory not empty
$ rm foo/bar
$ rmdir foo
$ ls foo
ls: foo: No such file or directory

在更实际的设置中,您可以使用带有if 语句的rmdir 命令来询问用户是否要删除所有内容。

if ! rmdir foo 2> /dev/null; then
    echo "foo contains the following files:"
    ls foo/
    read -p "Delete them all? [y/n]" answer
    if [[ $answer = [yY] ]]; then
        rm -rf foo
    fi
fi

【讨论】:

  • rmdir 不仅会在目录已满时出错。因此,将 stderr 保存在变量中可能会更好,并在删除之前检查以确保它包含类似 Directory not empty 的内容。
【解决方案2】:

感觉就像您在使用的语法中混合了一些语言。对您的脚本进行最小的更改,您可以使用 bash globing 来查看它是否已满(也可以创建一个数组,但看不到一个很好的理由),尽管我可能仍会使用类似于 chepner's script 和让rmdir 处理错误检查。

#!/bin/bash

echo "Please type the name of the directory you wish to remove "

read dName
[[ ! -d $dName ]] && echo "$dName is not a directory" >&2 && exit 1 
shopt -s nullglob
shopt -s dotglob

found=
for i in "$dName"/*; do
  found=: && break
done

[[ -n $found ]] && echo 'There are files in this directory!' || echo 'This directory is ok to delete!'

请注意原始语法中的几个错误:

  • 变量名区分大小写,$dName 不等于 $Dname(如果变量名包含空格或其他特殊字符,您应该真正引用它们)
  • directory 不是一个数组,你可以通过像 directory=($Dname/*) 这样的操作来实现它
  • ! 将尝试在双引号中执行历史扩展,如果您可以选择的话。

【讨论】:

    猜你喜欢
    • 2015-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-28
    • 2020-09-25
    • 2018-08-24
    • 2011-04-06
    • 2019-04-26
    相关资源
    最近更新 更多