如何检查rmdir是否返回EEXIST或ENOTEMPTY?

时间:2012-03-22 13:40:37

标签: linux bash return-value errno rmdir

我正在尝试编写一个请求目录的bash脚本,然后在确认后删除该目录。我还需要它告诉用户目录是否为空,并询问他们是否要删除它。

我想我会使用rmdir并检查返回值以确保删除目录,如果不是为什么,但到目前为止我不知道返回值等于EEXIST或ENOTEMPTY。到目前为止,我唯一的错误值是1。

如果目录中有文件,返回值应该是多少?

2 个答案:

答案 0 :(得分:2)

单独检查。不完美,但一个开始

if [ ! -e "$DIR" ]
then
    echo "ERROR: $DIR does not exist" >&2
elif [ ! -d "$DIR" ]
then
    echo "ERROR: $DIR is not a directory" >&2
elif [ ! -r "$DIR" ]
then
    echo "ERROR: $DIR cannot be read" >&2
elif [ $(ls -a $DIR | wc -l) -gt 2 ]
then
    echo "ERROR: $DIR is not  empty" >&2
else
    rmdir $DIR
fi

注意:rmdir仍可能失败。我想到的是您对$DIR的父目录没有写权限。

答案 1 :(得分:0)

您可以尝试使用此代码:

#!/bin/bash

check_path() {
        if [ "x$1" = "x" ]
        then
                echo "ERROR: You have to specify a valid path."
                exit 1
        fi

        if ! [ -d "$1" ]
        then
                echo "ERROR: The specified path does not exists or it's not a directory"
                exit 1
        fi

        X="`find \"$1\"  -maxdepth 1 | tail -n 2 | wc -l`"
        if [ $X -gt 1 ]
        then
                X="R"
        else
                X=""
        fi

        while [[ "x$X" != "x" && ("x$X" != "xs" && "x$X" != "xn") ]]
        do
                echo "The specified path ($1) is not empty. Are you sure you want to delete it anyway? (S/n)"
                stty -echo
                read X
                stty echo
        done
        if [ "x$X" == "xn" ]
        then
                echo "Operation interrupted by the user."
                exit 0
        fi
}

echo -n "Please insert the path to delete: "
stty -echo
read DIRNAME
stty echo
echo

check_path "$DIRNAME"

echo "Removing path $1"
echo rm -fr "$DIRNAME"

HTH