簡體   English   中英

僅在沒有文件時才刪除目錄的 bash shell 腳本

[英]bash shell script to delete directory only if there are no files

好的,所以我正在編寫一個 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
        ;;

您無需檢查; 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

在更實際的設置中,您可以使用帶有if語句的rmdir命令來詢問用戶是否要刪除所有內容。

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

感覺就像您在使用的語法中混合了一些語言。 對腳本進行最小的更改,您可以使用 bash globing 來查看它是否已滿(也可以創建一個數組,但看不到一個很好的理由),盡管我可能仍會使用類似於chepner 的腳本並讓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/*)類的操作來使其成為一個數組
  • ! 如果您有選項,將嘗試在雙引號中執行歷史擴展。

如果目錄不為空, rmdir將引發錯誤,如果您之前運行set -e ,您的腳本將停止。 您可以簡單地檢查ls輸出以查看目錄是否為空,然后再刪除該目錄:

[ "$(ls -A "$directory")" ] || rmdir "$directory"

它不容易出現競爭條件,因為如果在第一個命令之后和第二個命令之前將文件添加到目錄中,它將引發錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM