What is happening here?
- The ls command lists the files in a directory.
Using the “-t” option, the files are sorted according to their modification date. The oldest files are at the bottom of the list.
We use the search pattern “* .bak” for the data source. This is a common file extension for backup files. This also serves as a protection so that you don’t accidentally delete important files when you open it.
We pipe the file list to the Linux tail command.
- Using the Linux tail command without specifying options, we will read the last ten files from the list. The output filenames are the oldest files in the directory.
- The xargs command takes a list of files and the name of a command. The command is executed when the files are passed as arguments.
In our example, the Linux tail command returns text with several lines. Each line contains the name of a file to be deleted. The file names are separated from the lines via “xargs” and passed as arguments to the rm command.
- To delete files in Linux, we use the rm command which deletes the file that has been passed as arguments.
Note that deleted files will not be moved to the recycling bin but will be deleted immediately.
Beware when deleting files using the Linux command line. To try the example below, it’s best to first create a directory of test files. To do this, run the following code on the command line: