Skip to main content
Bash ScriptingScripting

BASH script to delete files once they have been read

I needed this script, or at least a variant of it for a project I was working on for automatic deployments of XenServer using PXE. The XenServers would be set to PXE boot and they would collect their configuration and install, but of course on subsequent boots we would not want to run the install again. To achieve the result a script runs and deletes the configuration file for each server as it is read.  To start we must understand the last access time for a file. This changes when a file is read and we can access it with:

stat -c %X filename

or:

stat -c -%x filename

The former shows the number of seconds that has passed since the Linux epoch (1 am on the 1st January 1970) and the latter, with the date in the more traditional format. Of course, to us, it is more easy to read the latter but if we wish to run calculations then the raw value of seconds is easy to see if one date is greater or less than another. We can use this technique to prove and verify the Linux epoch:

cat filename ; date --date "$(stat -c %X filename) seconds ago"

As we can see then, we access the file with the cat command and immediately retrieve the last accessed time and delete it from the current date; we see 1 am on the 1st Jan 1970. See, I don’t lie to you :).

Now that we now how to retrieve a usable date format and run calculations on those dates we can move on with the script. The script will create a reference file at the start of the process. We read the access time for the reference file, and file accessed after that date and time then has been read and we can delete it. The script can be run it the background or from cron what ever matches your needs. For this demonstration script we will run it in the background and the script will look for log files that have been accessed and then they are deleted.

#!/bin/bash
ref="$HOME/files/ref"
touch $ref
reftime=$(stat -c %X $ref)
while ls $HOME/files/*.log > /dev/null 2>&1
do
 for f in $(ls $HOME/files/*.log)
  do
    fileref=$(stat -c %X $f)
    if (( fileref > reftime )) ; then
      rm -f $f
    fi
  done
 sleep 60
done
rm -f $ref
echo -e "All files have been read and now deletedn"
exit 0

This is just a demo script but gives the idea of what is happening. For this to work create the files directory in your home directory and add some dummy files with a .log extension. Once the script is started in the background, using the &, then cat out the log files as required. The script will finish within 60 seconds of the last log file being read.