tkuchikiの日記

新ブログ https://blog.tkuchiki.net

mysqldump したSQLファイルを圧縮するワンライナー

mysqldump -u root DATABASENAME | bzip2 -c > `date +%Y-%m-%d_%H-%M-%S`.sql.bz2


bzip2 を "gzip -9" に置き換えても動作するが、bzip2 の方が圧縮率が高い。

[追記]

上記コマンドをcronで実行したかったのだが、
cronは%をエスケープしないと動かないことを失念していた。。。
あと、cronは、sleepを挟まない限り1分単位未満で実行できないので、
ファイル名に秒を含める必要がないことに気がついた。

以下のように、\をつけるとcronで動作するようになる。

mysqldump -u root DATABASENAME | bzip2 -c > `date +\%Y-\%m-\%d_\%H-\%M`.sql.bz2


ちなみに、%がダメな理由は、
http://crontab.org/
によると、

The  ``sixth''  field (the rest of the line) specifies the
command to be run.  The  entire  command  portion  of  the
line,  up to a newline or % character, will be executed by
/bin/sh or by the shell specified in the SHELL variable of
the  cronfile.   Percent-signs  (%) in the command, unless
escaped with backslash (\), will be changed  into  newline
characters, and all data after the first % will be sent to
the command as standard input.


おそらく、%以降は標準入力として解釈するという意味だと思われる。