2011-05-04 18 views
2

我在寫一個shell腳本。我的腳本進入一個目錄,但我希望它只能繼續執行下一個命令,如果目錄包含任何數據(該目錄不是空的)。否則,它不應該進一步。我如何在shell腳本中指定這樣的條件?如何在ash shell腳本中指定「if directory not empty」?

+0

可能重複[檢查目錄是否包含文件](http://stackoverflow.com/questions/91368/checking-if-a-directory-contains-files) – 2013-09-11 19:00:11

回答

0
if [ "$(ls -A $DIR)" ]; then 
    echo "Take action $DIR is not Empty" 
else 
    echo "$DIR is Empty" 
fi 
1
if [ `find dir -type f | wc -l` = "0" ] 
then 
    echo no files 
else 
    echo files 
fi 

這會檢查dir和子目錄。 find dir -maxdepth 1 -type f將只檢查dir

如果要計算子目錄和文件:

find dir -mindepth 1 -maxdepth 1 
+1

而不是管道到wc -l,它使用grep更清潔:如果找到dir -type f | grep -q。;然後 ...; fi – 2011-05-05 03:15:24

3

使用測試以 「$(LS-A $ DIR)」,如:

if [ "$(ls -A $DIR)" ]; then 
    echo "directory is not empty" 
else 
    echo "directory is Empty" 
fi 
+0

+1請注意,'-A'不是POSIX,但在GNU下也支持BSD引入的擴展。 – pilcrow 2013-05-24 14:24:40