Struggling with basic scripting

Associate
Joined
17 Jan 2004
Posts
483
I seem to be struggling with what I assume will be quite an elementary task for all but the newest of Linux users (me). Hopefully someone can point out any command misuse and in the process I'll gain a better understanding than I've achieved through google searching.

I'm trying to perform a conditional command if files are found below a specified directory:

Code:
server:~# find /var/lib/amavis/virusmails/ -type f
/var/lib/amavis/virusmails/H/spam-H3pxixtQxEy9.gz


server:~# cat badmailpurge
#!/bin/bash

# Find and remove all 'bad' mail files (banned-* / spam-* / virus-*) from the amavis quarantine.
# Record a conditional log message.

badmaildir=/var/lib/amavis/virusmails/
if [ -f 'find $badmaildir -type f' ]; then
#    find $badmaildir -type f -exec rm {} \;    // will uncomment when message logging is sorted. redundant repetition of previous find command?
    logger -i -p mail.info "badmailpurge: Found and removed file(s) from $badmaildir."
  else
      logger -i -p mail.info "badmailpurge: No file(s) to delete."
fi
server:~#

The syslog and mail.log always show "...No file(s) to delete..." even when spam is present.

Please offer your advice. Bonus cookies if the logger can record how many files were removed. Thanks!
 
Came up with a first working version. The plan is to run the script from /etc/cron.daily

Code:
#!/bin/bash

# Find and remove all 'bad' mail files (banned-* / spam-* / virus-*) from the amavis quarantine.
# Record a conditional log message.

badmaildir=/var/lib/amavis/virusmails/
count=`find $badmaildir -type f | wc -l`

if [ $spamcount = 0 ]; then
    logger -i -p mail.info "badmailpurge: No files to delete."
  else
      find $badmaildir -type f -exec rm {} \;
      logger -i -p mail.info "badmailpurge: Found and removed $count files from $badmaildir."
fi

No, I haven't spent the last five hours on it :)

Feels wasteful using the find command twice. If anyone has an idea for improvement, please feel free.
 
Came up with a first working version. The plan is to run the script from /etc/cron.daily

Code:
#!/bin/bash

# Find and remove all 'bad' mail files (banned-* / spam-* / virus-*) from the amavis quarantine.
# Record a conditional log message.

badmaildir=/var/lib/amavis/virusmails/
count=`find $badmaildir -type f | wc -l`

if [ $spamcount = 0 ]; then
    logger -i -p mail.info "badmailpurge: No files to delete."
  else
      find $badmaildir -type f -exec rm {} \;
      logger -i -p mail.info "badmailpurge: Found and removed $count files from $badmaildir."
fi

No, I haven't spent the last five hours on it :)

Feels wasteful using the find command twice. If anyone has an idea for improvement, please feel free.

Probably just a typo but you use if [ $spamcount ] when it's $count that is declared?
 
Back
Top Bottom