如何檢查資料夾是否為空並在 if-then-else 語句中使用其內容?

如何檢查資料夾是否為空並在 if-then-else 語句中使用其內容?

我需要檢查資料夾是否為空,並根據輸出我需要運行一些其他命令。我正在使用 Ubuntu 18.04.5 LTS。

我的 bash 腳本:

if [ "$(ls -A /mnt/mamdrive/"As Metadata"/)" ] || ["$(ls -A /mnt/mamdrive/"As Video"/)"  ]; then
    echo "copy file"
else
    echo "dont copy"
fi

這種情況有時有效,但有時無效,且很難重現。還有其他方法可以檢查目錄是否為空並執行相應操作嗎?

答案1

我建議一些不依賴字串輸出的東西ls- 例如,測試是否有全域擴展的任何結果:

#!/bin/bash

shopt -s nullglob       # don't return literal glob if matching fails
shopt -s dotglob        # make * match "almost all" like ls -A

set -- /mnt/mamdrive/"As Metadata"/*

if (( $# > 0 )); then
  echo "not empty"
else
  echo "empty"
fi

如果你想測試兩個目錄是否都是空的,你可以簡單地遍歷它們:

set -- /mnt/mamdrive/"As Metadata"/* /mnt/mamdrive/"As Video"/*

答案2

最簡單的方法是在這樣的語句ls -A中使用:if

path=$(ls -A '/whatever/sub directory/more spaces')
if [[ ! -z "$path" ]]; then
    echo "Directory is NOT empty!"
else
    echo "Directory is empty!"
fi

答案3

find與 一起ifne可以作為空複製:

$ find test/ -maxdepth 0 -empty | ifne cp -t test/ a

在 if 語句中使用它可能看起來像這樣:

#!/bin/bash

if find test/ -maxdepth 0 ! -empty | ifne false; then
   echo Directory is empty
else
   echo Directory is not empty
fi

答案4

眾所周知,ls解析很容易出錯,因為它一開始就不是可解析的,因此應該首選其他解決方案。除了@steeldriver的答案之外,還可以使用以下方法來完成find

if [[ "$(find '/mnt/mamdrive/As Metadata' '/mnt/mamdrive/As Video' -maxdepth 1 -mindepth 1 2>/dev/null)" ]]
then
    echo “copy file”
else
    echo "don't copy"
fi

maxdepthmindepth此處使用和選項僅列印和掃描指定目錄的直接子目錄。重定向可確保如果某些參數不存在,則不會列印錯誤訊息。

新增多個目錄將起到「或」的作用,因此如果至少一個測試目錄非空,則會列印「複製檔案」。使用find還允許使用其參數進行更精細的調整,例如檔案名稱、檔案類型等等。

相關內容