I'm trying to keep a directory full of log files manageable. Nightly, I want to delete all but the 10 most recent. How can I do this in a single command?
migrated from stackoverflow.com Apr 8 '11 at 14:36
|
From here:
|
||||
|
bash:
This skips the 10 newest als deletes the rest. logrotate may be better, I just want to correct the wrong shell related answers. |
|||
|
|
|
For a portable and reliable solution, try this:
The And using
If you don't have xargs (old AIX systems, maybe?) you could make it a loop:
This will be a bit slower because it spawns a separate |
|||
|
|
The code you'd want to include in your script is
The -1 (numeric one) option prints each file on a single line, to be safe. The -f option to rm tells it to ignore non-existent files for when ls returns nothing. |
|||||||||||||
|
|
A tool like logrotate does this for you. It makes log management much easier. You can also include additional cleanup routines shuch as halo sugggested. |
|||
|
|
