Sorry to disturb you and take your time,

I have a small job to do, it is -

We will be taking back-up's regularly at certain time intervals
according to the non - business hours.

Suppose according to the business logic we scheduled a back-up job
that takes the backup every mid night at 12 o'clock.

After a week days of time we have 7 backup images in a particular
folder where we store out back-up's.

So on eight day when the backup image is taken we want to remove the
oldest back-up image from the folder.

Need to do this by a corn job.

Try this and thanks for your time and this is one of the task almost
all of our consultant who are working for development projects got but
not me.

Note - While sending the code please try to put a comment for every
line and try to explain what it does so that I can understand it as I
am new to Shell Scripting.

Thanks in Advance.

First of all, you need to find the oldest file in the folder, you can do it with some switches in 'ls':

ls -t

This will list the files and sort by time, the newest first, then the oldest. Not put it in reverse:

ls -tr

It will list the oldest file first. Then pipe it to 'head -n 1' so it only list the very fisrt one, i.e. the oldest file:

ls -tr | head -n 1

This will give you the name of the oldest file in the directory. To remove it, pipe it again to xargs for removal:

ls -tr | head -n 1 | xargs rm

And you will probably want to 'cd' to the correct directory, so your entire script should look something like this:

cd "$BACKUP_DIR" && ls -tr | head -n 1 | xargx rm -f

This will attempt to force-remote the oldest file in that directory.

You can add more features to this such as:
1) Check to make sure you have 8 files in the directory
2) Send errors (failed to remove) messages to sys admin email


Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.