LoginSignup
10

More than 5 years have passed since last update.

cronでログファイル名を実行日時に設定するときの注意

Last updated at Posted at 2017-04-03

cronでバッチを実行し標準出力(エラーも含む)を 2017-01-01-12-00-00.log のような形式で出力を試みた。
/var/log/cron のログ的にはバッチは実行されているが、ログファイルは出力されていなくてハマった。

確認環境

  • AmazonLinux

ダメな設定

/etc/crontab
0 * * * * user-name /path/to/command arg >> /var/log/test-`date +%Y-%m-%d-%H-%M-%S`.log 2>&1

shell上から /path/to 以下を実行した際は、問題なくログファイルが出力されていたが、cronで実行した際はログファイルが出力されていない。
実際、/var/log/cronのログを見ると、動的に生成されたファイル名の箇所が batch_`date +)と、意図しない形式になっていた。

正しい設定

crontab(5) によると、% は区切り文字として認識されていて、それ以降は実行されず、標準入力として扱われていたようだ。

The entire command portion of the line, up to a newline or % char-
acter, 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.

エスケープする必要があるようだ。

/etc/crontab
0 * * * * user-name /path/to/command arg >> /var/log/test-`date +\%Y-\%m-\%d-\%H-\%M-\%S`.log 2>&1

参考

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10