我想寫一個bash腳本,請求一個目錄,然後確認後,刪除該目錄。我也需要它告訴用戶目錄是否爲空,並詢問他們是否想要刪除它。如何檢查rmdir是否返回EEXIST或ENOTEMPTY?
我想我會使用rmdir並檢查返回值以確保該目錄被刪除,如果不是原因,但到目前爲止我不知道什麼返回值等同於EEXIST或ENOTEMPTY。到目前爲止,我得到的唯一錯誤值是1.
如果目錄中有文件,返回值應該是多少?
我想寫一個bash腳本,請求一個目錄,然後確認後,刪除該目錄。我也需要它告訴用戶目錄是否爲空,並詢問他們是否想要刪除它。如何檢查rmdir是否返回EEXIST或ENOTEMPTY?
我想我會使用rmdir並檢查返回值以確保該目錄被刪除,如果不是原因,但到目前爲止我不知道什麼返回值等同於EEXIST或ENOTEMPTY。到目前爲止,我得到的唯一錯誤值是1.
如果目錄中有文件,返回值應該是多少?
單獨進行檢查。不完美,但一開始
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
父目錄的寫入權限。
您可以嘗試使用此代碼:
#!/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
您必須更改「echo rm -fr」行刪除「echo」 – dAm2K 2012-03-22 15:22:49
告訴我們你有什麼到目前爲止已經試過。 2提示:你知道'echo $?'會告訴你從前面的命令返回嗎?你知道'0'返回意味着'真'嗎?祝你好運。 – shellter 2012-03-22 13:50:54