Firstly yes, there are several versions of this question floating around this site, but I decided to ask because I haven't seen one with the specific caveat my problem has, and despite years of programming experience, I've never really needed bash before, so I don't have the practical knowledge to work this out myself.
I have an incremental backup script on Server A which uses rsync to copy over an SQL file. It syncs these to a folder called sql/
to a file called latest.sql
. This is all cron jobbed and works fine, but I need to implement a rotation on the destination Server B.
The last thing my script on Server A does is call the cleanup script on Server B. The cleanup script should do the following:
- Get the current time using
NOWDT="$(date '+%Y-%m-%d_%H_%M_%S')"
so it is in the form2017-03-27_17_30_00
. - Copy
latest.sql
into${NOWDT}.sql
usingcp
(same dir).
(this is the tricky part I haven't solved yet)
- List the files alphabetically, so the timestamped ones should be above
latest.sql
(I want to keep this). - If there are more than four files (three timestamped and
latest.sql
), delete the top (earlier) ones until there are only three timestamped ones.
Once it's done there should be a maximum of 4 files in there: latest.sql
and up to three timestamped ones.
I've had a look at this question and there's some good stuff there but I just don't have enough knowledge of bash scripting to work out how to effectively modify it to suit my needs. Also I don't know how relevant it is but I'm using the standard bash shell that comes with CentOS 6.