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 ( 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.

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

To run the script from the same directory use:

./ 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: