Remove the oldest file of a directory

Need help with C, C++, perl, python, etc?

Remove the oldest file of a directory

Postby aleix » 2006-09-07 16:31

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...
User avatar
Posts: 32
Joined: 2006-07-12 09:10
Location: Girona

Postby Daylung » 2006-09-07 18:56

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:
Posts: 103
Joined: 2005-12-24 04:44

Return to Programming

Who is online

Users browsing this forum: No registered users and 5 guests