views:

156

answers:

1

I want to loop over a series of files in a directory in batches and then exit when the directory is empty.

At $work 'myprog' is actually a program which processes (and archives) incoming email in a Maildir in batches of 100.

I am after something simple I can put into 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

Any ideas?

+1  A: 

I suppose you can do:

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

If nothing matches foo/* (if no visible files are in directory foo), ls will fail. &> /dev/null keeps ls quiet.

Joey Adams
That was quick! It seems odd to me that `ls foo` will return true but `ls foo/*` will fail - but now I know!I added an ` ls foo/ | wc -l;` in the while loop to watch the items decrease.
CoffeeMonster
The subshell isn't needed in the `while` statement.
Dennis Williamson