Включить текущую метку времени в имени файла?

1907
Louis B.

Я должен создать много резервных копий БД вручную mysqldump, например, так:

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

Мне интересно, есть ли простой способ включить текущую дату или метку времени в имя файла, чтобы файл выглядел так: my-db-20150917.sql(или другой формат тоже подойдет, даже метка времени).

0

1 ответ на вопрос

1
bertieb

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.

Похожие вопросы