2010-03-25 71 views
1

我想循環遍歷目錄中的一系列文件,然後在目錄爲空時退出。如何使用ls退出bash循環?

在$工作「MYPROG」實際上是一個程序,處理(和檔案)傳入的電子郵件中的Maildir中的100

批我簡單的東西,我可以投入的cron後。

#!/bin/bash 

# Setup 
mkdir -p foo && touch foo/file_{1,2,3,4}.txt 
alias myprog='f=`ls foo/file_*.txt | head -n1`; rm -v $f' 

# Loop and then exit ?! 
# This line to go into cron. 
while (ls foo); do ls foo/ | wc -l; myprog; sleep 1; done 

任何想法?

+0

你可以在大括號擴展中做範圍:'{1..4}' –

+0

甚至更​​好,你可以是PORTABLE並使用適當的通配符'file_ [1234]'。 :) – vladr

回答

2

我想你可以這樣做:

#!/bin/bash 
# ... 
while (ls foo/* &> /dev/null); do myprog; sleep 1; done 

如果沒有匹配foo/*(如果沒有可見的文件目錄中富),ls將失敗。 &>/dev/null保持ls安靜。

+0

這很快!我覺得'ls foo'會返回true,但'ls foo/*'會失敗 - 但現在我知道了! 我加了'ls foo/| wc -l;'在while循環中觀察項目減少。 – CoffeeMonster

+1

'while'語句中不需要subshel​​l。 –