Bash script to reduce file count to a given number removing the oldest files first FIFO

I needed a simple automated way to remove any number of old backup tar files from a directory leaving only the newest 30 files. As the only thing in this directory was compressed backup files, the script didn’t need to worry about file names or file types, it could just delete the oldest files in the directory (as all the files were effectively the same but just for a different period in time).

So I wrote this bash script (remove_old_files.sh) to handle it for me, it takes two arguments. The first is the number of files to leave (in my case 30), and the second the absolute file path to the directory you want to keep in check.

#!/bin/bash
if [ $# -ne 2 ] ; then
    echo "Not enough arguments.
Please pass the number of files to keep followed by the path"
    exit 1
fi
# First argument is the number of files to keep!
KEEP_NUM=$1
# Second argument is the directory to look under:
DIR=$2
if [ $KEEP_NUM -gt 0 ] ; then
    FILES=(`ls -t1 $DIR`)
    NUM_FILES=${#FILES[@]}
    echo Number of files found: $NUM_FILES
    # Remove all the old files from the array after the required
    # number have been kept!
    FILES_REMOVED=0
    for ((i=KEEP_NUM;i< $NUM_FILES;i++)); do
        echo Removing: $DIR/${FILES[$i]}
        `rm -f $DIR/${FILES[$i]}`
        let FILES_REMOVED++
    done
    echo $FILES_REMOVED 'File(s) removed'
else
    echo 'please specify the number of files to keep: 1 or more'
fi

To run the script from the same directory use:

./remove_old_files.sh 30 /home/myuser/large_file_count_dir
Number of files found: 31
Removing: /home/myuser/large_file_count_dir/file31
1 File(s) removed

To check the file count in the current directory use:

ls -1 | wc -l

This command uses the list directory command to get a line break separated list of the all the files in the current directory, and pipes the output to the wc command which then using the l parameter allows you to just count the total number of lines.

The script can be downloaded from here: remove_old_files.sh