0

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

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

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

4

2 回答 2

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.

于 2012-03-22T14:46:23.863 回答
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"

高温高压

于 2012-03-22T15:09:17.080 回答