1. Overview
In this tutorial, we are going to create a bash script that counts the files in a directory, and if there are more files than a specific number, it removes the oldest ones.
2. The Environment
Let’s assume we have a directory that has several files in it:
$ ls
files
$ ls -t ./files
file15.txt file13.txt file11.txt file9.txt file7.txt file5.txt file3.txt file1.txt
file14.txt file12.txt file10.txt file8.txt file6.txt file4.txt file2.txt
The -t option sorts the reported files by modification time, so the newest file is displayed first. As we can see, file15.txt is the newest file, and file1.txt is the oldest one.
3. The Script
Now, let’s create the script. It should receive the limit on the number of files as an argument:
#!/bin/bash
# Print usage if requested.
if [[ $1 == "--help" || $1 == "-h" ]]
then
echo "Usage: $0 [files limit]"
exit 0
fi
# The script receives the limit as an argument.
limit=$1
number_of_files=$(ls ./files | wc -l)
if [ $number_of_files -gt $limit ]
then
# There are more files than the limit
# So we need to remove the older ones.
cd files
ls -t | tail --lines=+$(expr $limit + 1) | xargs -d '\n' rm
fi
In the above code, wc -l counts the files in ./files using the newline character, \n, as a delimiter.
ls -t lists the files by modification time and puts the newest file first.
tail –lines=+$(expr $limit + 1) outputs the files that come right after the limit. Therefore, we now have all the files that we need to delete.
Finally, xargs -d ‘\n’, using the newline character as a delimiter, gives each file to rm as an argument so it will remove them.
4. Executing the Script
After saving the script, we need to make it executable before we can execute it:
$ ls
count_then_remove.sh files
$ chmod u+x count_then_remove.sh
chmod u+x makes the script executable. Let’s run it:
$ ./count_then_remove.sh 5
$ ls -t ./files
file15.txt file14.txt file13.txt file12.txt file11.txt
We can see that the script has deleted the old files. As a result, there are five files remaining.
5. Conclusion
In this short article, we learned how to create a script that keeps the number of files in a directory no more than a predetermined number.