LJ Archive

Listing 1. mailrm.sh Script

#! /bin/bash
# mailrm.sh - purge all mail more than $1 days old
age=$1
MAILDIR=/var/spool/mail
FORMAIL=/usr/bin/formail
MAILAGE=/usr/local/bin/mailage.sh
MAILDATE=/usr/local/bin/maildate.sh
clear
set `whoami`
if [ "$1" != "root" ]
  then
  echo
  echo " # The mailrm script must be executed "\
   "by root #"
  echo
  exit
fi
echo;echo "  Removing old Mail";echo

#  Get a list of the mail files in $MAILDIR
lst=`ls -1A $MAILDIR`

#  Get the current date from the system
#  Calculate the date $age days ago
today=`date +'%b %d %Y'`
todayint=`$MAILDATE $today`
keepdate=$[ todayint - age ]

echo "Removing all mail messages more than $age"
echo "days older than $today"
# Check every mail file for presence of old mail
for fil in $lst
do
  flb="$MAILDIR/tmp$$"

#  If file exists and has data in it
  if [ -s $MAILDIR/"$fil" ]
  then
    $FORMAIL -d -z -s $MAILAGE $keepdate \
   < $MAILDIR/$fil > $flb
    oldlines=`wc -l $MAILDIR/$fil | \
   awk '{print $1}'`
    newlines=`wc -l $flb | awk '{print $1}'`
    if [ $oldlines -ne $newlines ]
    then

#  Get the user's account and full name
#  and report as mail is deleted from mail file
      nou=`grep $fil /etc/passwd | cut -d: -f5`
      echo
      echo " for user $fil - $nou"
      echo
      mv $flb $MAILDIR/$fil
    else
      rm $flb
    fi
    chown $fil $MAILDIR/$fil > /dev/null 2>&1
    chgrp mail $MAILDIR/$fil > /dev/null
    chmod 660 $MAILDIR/$fil > /dev/null
  else

#  If file exists and is zero length, remove it
    if [ -a $MAILDIR/"$fil" ]
    then
      echo " $fil is empty. Removing."
      rm $MAILDIR/"$fil"
    fi
  fi
done
#   End of script
LJ Archive