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

时间:2014-04-16 23:08:29

标签: bash shell unix

好的,所以我正在编写一个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
        ;;

2 个答案:

答案 0 :(得分:6)

你不需要检查; 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

在更实际的设置中,您可以使用带有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

答案 1 :(得分:1)

感觉就像你在使用的语法中混合了一些语言。对脚本进行微小的更改,你可以使用bash globing来查看它是否已经完整(也可以创建一个数组,但是看不太合理),尽管我可能仍会使用与{{3}类似的东西并让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/*)
  • 之类的方式将其设为一个数组 如果您有选项,
  • !将尝试使用双引号执行历史记录扩展。