Include current timestamp in filename?

1

1

I have to create a lot of DB backups manually using mysqldump, for example like this:

mysqldump -uroot -proot my-db > my-db.sql

I'm wondering if there's an easy way to include the current date or timestamp into the filename, so that the file would look like this: my-db-20150917.sql (or another format is fine as well, even a timestamp).

Louis B.

Posted 2015-09-17T07:44:41.913

Reputation: 113

Answers

3

How can I datestamp my file names?

To include the current time/date in a filename, use a combination of date, and command substitution:

mysqldump -uroot -proot my-db > my-db-`date +%Y%m%d`.sql

The man page for date explains the other options you can use; but in this context you might also be interested in including time:

mysqldump -uroot -proot my-db > my-db-`date +%Y%m%d-%H%M`.sql

Wait, what's this 'command substitution'?

Quoting from the bash hackers wiki on command substitution:

The command substitution expands to the output of commands. These commands are executed in a subshell, and their stdout data is what the substitution syntax expands to.

Basically, date -%Y%m%d outputs 20150917, and we use the backtick (`) form of command substitution to include that output in the command you supplied for backing up your database. We could equally have used:

mysqldump -uroot -proot my-db > my-db-$(date +%Y%m%d).sql

to achieve the same result.

bertieb

Posted 2015-09-17T07:44:41.913

Reputation: 6 181