Delete Files Not in Use

Delete files not in use
Sometimes you need to clear out a directory of files but don’t want to delete any files in use by a program or user. This little script is the answer to those problems.

There are two interesting items in this script. The first is that this directory had grown so large that the rm -rf * command was not able to process it, which is the reason I dump the listing to a temporary file. The second item is the $? within the test command. I am testing the return of the last command that was executed. By Unix convention a 0 is returned upon successful completion, any other value implies failure. That line could also have been written:

if fuser /var/spool/filter/$I >/dev/null 2>&1
then
code...
fi

Regardless, here is the script.

#!/bin/bash
#  2007-08-28  Jud Bishop
#  Released under the GPLv2.
#  This little script checks to makes sure that a file is not in
#  use before it deletes the file or directory, which is why I 
#  use an -rf, to delete the directory.  The reason I have to
#  write the directory listing to a file is because the directory 
#  gets too large to be handled by the rm command.

ls /var/spool/filter >/tmp/purge-filter

for I in `cat /tmp/purge-filter`
do
     fuser /var/spool/filter/$I >/dev/null 2>&1
     if [ $? -ne 0 ]
     then
          #echo "Deleting /var/spool/filter/$I"
          rm -rf /var/spool/filter/$I
     fi
done
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s