2010-03-25 73 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。 –