Domanda

I have no idea how to process cron jobs, however I can explain what I'd like it to do.... Anyone with experience on how to do this, would be very much appriciated....

  1. Delete Oldest Files in a directory
  2. Keep at least 8 of the newst files in a directory

Is it possible? I've been trying to understand documentation on this for a few hours, thought I would ask to save time in learning how to process these things... my host alows me to enter the cron jobs into the control panel backend.

I found this command

(ls -t|head -n 5;ls)|sort|uniq -u|xargs rm

However, it dosent look like it knows which directory I want to delete from... and i have no idea what it does...

È stato utile?

Soluzione

As I already wrote in my comment, the script which does what you want is independent of cron. Here is a possibility to do what you want:

cd /path/to/dir; ls -t | tail -n +9 | xargs rm

Explanation

  • cd /path/to/dir: goto directory
  • ls -t: get a list of all files in the directory, sorted by last modification date, newest first
  • tail -n +9: select all lines (in this case file names), starting with the 9th
  • xargs rm: remove files which were 'selected' by previous commands

By selecting all lines beginning with the 9th, the 8 newest files never get deleted.

I assume that only files are stored in the folder, as the rm command will only remove those. To also remove folders and all of their contents, you will have to use rm -r.

To read a detailed description of a command (e.g. cd, ls, tail, xargs, rm) use man <command>

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top