Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I need a way (a script) too move all but the last 100 messages from a users mail-spool (/var/spool/mail/theuser) to a file/mbox in the users mail-directory (/home/theuser/mail). Is there an easy way to do this?

share|improve this question
up vote 2 down vote accepted

Here's a quick and dirty head start. No error checking, and it doesn't actually "move" anything as is.

# DIRTY hack to append all but the last 100 messages from each file
# in a dir of mbox files to like named files in /tmp
# if an mbox has less than 101 messages, skip it
# requires formail (from the procmail installation..)

# we're writing in tmp - to write in the user's dir move this 
# inside the for loop and use $USERMAIL to write the base path

for USERMAIL in `ls -1`

MESSAGECOUNT=`cat $USERMAIL | formail -q -s wc | wc -l | sed 's/^[ \t]*//'`
if [ $COPYTHISMANY -gt 0 ]
echo "Copying $COPYTHISMANY messages from $USERMAIL to /tmp/$USERMAIL.allbutlast100"
cat $USERMAIL | formail -$COPYTHISMANY -s cat >> $DESTDIR/$USERMAIL.allbutlast100
# copy the last 100 to a new file
cat $USERMAIL | formail +$COPYTHISMANY -s cat >> $DESTDIR/$USERMAIL.last100
# to replace the original source mbox do something like
# mv /tmp/$USERMAIL.last100 $USERMAIL
share|improve this answer
Thanks! It seemd to work well with a few test mboxes. It gave an error (in norwegian) several times: "wc: standard inn:35: Ugyldig eller ufullstendig multibyte eller bredt tegn" (illegal or incomplete multibyte or "wide" character). But it worked :-) – MyOnlyEye Mar 3 '10 at 16:56

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.