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.