bash shell脚本只有在没有文件的情况下才能删除目录

use*_*030 1 unix bash shell

好的,我正在编写一个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
        ;;
Run Code Online (Sandbox Code Playgroud)

che*_*ner 7

你不需要检查; 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
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

  • `rmdir` 不仅会在目录已满时出错。因此,最好将 stderr 保存在变量中,并在删除之前检查以确保它包含“目录不为空”之类的内容。 (2认同)