0

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:

  1. Get the current time using NOWDT="$(date '+%Y-%m-%d_%H_%M_%S')" so it is in the form 2017-03-27_17_30_00.
  2. Copy latest.sql into ${NOWDT}.sql using cp (same dir).

(this is the tricky part I haven't solved yet)

  1. List the files alphabetically, so the timestamped ones should be above latest.sql (I want to keep this).
  2. 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.

Community
  • 1
  • 1
Leylandski
  • 421
  • 5
  • 8

1 Answers1

1
ls [0-9]*.sql | sort | head -n -3 | xargs -r rm -f
  1. list all files what started with digit and has extention .sql
  2. sort it
  3. remove first 3 lines (file what we want to keep)
  4. remove all files what left. xargs -r get file names from input and run rm -f <filenames>. -r mean "not run if there is no input"
komar
  • 861
  • 5
  • 8
  • The form of `head -n -3` is GNU head only. Posix does not have that. You can use `tail -n 4` instead that will work on Posix and Linux / GNU – dawg Mar 27 '17 at 17:21
  • @komar : `sort` is not necessary. `ls` outputs the entries by default in a sorted way. Also, I would replace `ls` by echo. BTW, this would also yield the entries already sorted, because this is also the default for wildcard expansion. – user1934428 Mar 28 '17 at 04:34
  • What advantages does `echo` have over `ls`? Is there any technical reason one is better? – Leylandski Mar 28 '17 at 09:32