Home > other >  bash command inside a function to delete all files except the recent 5
bash command inside a function to delete all files except the recent 5

Time:08-09

I have a delete backup files function which takes in the arguments as a directory name and to backup the files of a specific directory and specific type of file like this delete_old_backup_files $(dirname $$abc) "$abc.*"

The function body is

local fpath=$1
local fexpr=$2

   # delete backup files older than a day
   find $fpath -name "${fexpr##*/}" -mmin  1 -type f | xargs rm -f

Currently deleting files that are older than a day. Now I want to modify the function such that this function should delete all backup files of type $abc.*, except the last 5 backup files created. Tried various commands using stat or -printf but couldn't succeed.

Let me know the correct way of completing this function.

Thanks in Advance.

CodePudding user response:

Assuming the filenames do not contain newline characters, would you please try:

delete_old_backup_files() {
    local fpath=$1
    local fexpr=$2

    find "$fpath" -type f -name "${fexpr##*/}" -printf "%T@\t%p\n" | sort -nr | tail -n  6 | cut -f2- | xargs rm -f --
}
  • -printf "%T@\t%p\n" prints the seconds since epoch (%T@) followed by a tab character (\t) then the filename (%p) and a newline (\n).
  • sort -nr numerically sorts the lines in descending order (newer first, older last).
  • tail -n 6 prints the 6th and following lines.
  • cut -f2- removes the prepended timestamp leaving the filename only.

[Edit]
In case of MacOS, please try instead (not tested):

find "$fpath" -type f -print0 | xargs -0 stat -f "%m%t%N" | sort -nr | tail -n  6 | cut -f2- | xargs rm --

In the stat command, %m is expanded to the modification time (seconds since epoch), %t is replaced with a tab, and %N to be a filename.

CodePudding user response:

I would use sorting instead of find. You can use ls -t

$ touch a b c
$ sleep 3
$ touch d e f
ls -t | tr ' ' '\n' | tail -n  4
a
b
c
$ ls -t | tr ' ' '\n' | tail -n  4 | xargs rm
$ ls
d  e  f

From man ls:

-t     sort by modification time, newest first

Make sure you create backups before you delete stuff :-)

  • Related