I currently backup a MySQL docker container using a shell script, it dumps the mysql file into a relative directory, such as..


TODAY=`date +"%d%b%Y"`

mysqldump -uroot -p"$MYSQL_ROOT_PASSWORD" -h $MYSQL_HOST --all-databases | gzip > /data/mysqldb/$TODAY/all-databases-$TODAY.sql.gz

I need to create a restore script that will read the $TODAY and determine which is most recent. How do I do this? :S

  • If you're going to want to sort textual timestamps, better to use a format that is lexically ordered like %Y%m%d or numerically ordered like %s - or at least include delimiters so that you can use GNU sort's M month sort option for the %b. Aug 28 '19 at 15:06

This is the approach i used. I have a working backup script with it.

CD into the backup DIR.

cd backup_dir && ls -t | head -n 2

-t -> sort by modification time, newest first

In a script:

LAST_2_BACKUPS=$(ls -t | head -n 2)
  • Thanks! I was looking at this too but I was concerned if someone/thing modified something (renamed it for example) it might throw off the automated restore script.
    – jamesvree
    Aug 28 '19 at 14:01
  • why would you modify a backup? backups are supposed to be stored in a backup dir or s3 somewhere?
    – saviour123
    Aug 28 '19 at 14:05
  • you have atime and mtime as options too. cyberciti.biz/faq/howto-finding-files-by-date
    – saviour123
    Aug 28 '19 at 14:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.