Scheduled Maintenance: We are aware of an issue with Google, AOL, and Yahoo services as email providers which are blocking new registrations. We are trying to fix the issue and we have several internal and external support tickets in process to resolve the issue. Please see: viewtopic.php?t=158230

 

 

 

Remove the oldest file of a directory

Programming languages, Coding, Executables, Package Creation, and Scripting.
Post Reply
Message
Author
User avatar
aleix
Posts: 32
Joined: 2006-07-12 09:10
Location: Girona

Remove the oldest file of a directory

#1 Post by aleix »

Hi everybody,

I've have a shell script called by crontab every week.
This script makes a tar file of different files, and save this tar file into a directory.

This directory contains 4 tar files, one of every week since I started to execute the script.

Now I would like to automatically remove the oldest tar file of the directory every time the script is invoqued again.

How can I do that??
Can anyone help me??
I am still learning the linux OS, so I am just a beginner...

Daylung
Posts: 103
Joined: 2005-12-24 04:44

#2 Post by Daylung »

this command should do it.

Code: Select all

#rm  `ls -t --color=none | tail -n 1`

Code: Select all

`ls -t --color=none | tail -n 1`
with the " ` " (top left of most keyboards) returns the filename of the oldest file. the "-t" option sorts chronologically (--color=none just ot be safe) then pipe the list to "tail -n 1" which ouputs the last line of whatever you give it, and rm removes the resulting file. To put this in a shell script you should add a line to change to the directory you want, if there are other files in that directory you can use wildcards with ls to just look at the files you want.

Code: Select all

ls -t *.tar.bz2
or something like that. Hope this was helpful.

Oh, and you really don't have to post questions in multiple sections :wink:

Post Reply