cron(crontab)で設定した標準出力の出力先を、日付の入ったファイル名で指定する方法。
#まぁ、manを読めって話なんですが。。。
解決策:
crontabへの設定を以下のように"%"を"\%"とバックスラッシュでエスケープする8 0 * * * /home/hoge/backup.sh >/home/hoge/`date +\%Y\%m\%d\%H\%M`_backup.log 2>&1
物語:
先日、会社で簡単なバックアップ処理をcronで実行させる必要があり、スクリプトを書きました。
(仮にbackup.shとしておきます)
シェルスクリプトをそのまま実行したら、標準出力で実行結果がとれるので、
その内容をそのままログとして残したいと思ったとします。
(えぇ、そう思いました。)
で、コマンドラインで下記コマンドで動作確認をして、
/home/hoge/backup.sh >/home/hoge/`date +%Y%m%d%H%M`_backup.log
crontabにも以下のように設定。
8 0 * * * /home/hoge/backup.sh >/home/hoge/`date +%Y%m%d%H%M`_backup.log 2>&1
だが、しかし。。。実行された気配なし。。。。
syslogを確認すると、こんなつれないメッセージが。。。
Jan 01 00:01:01 User CRON[4975]: (root) CMD (/home/hoge/backup.sh > /home/backups/`date +)
Jan 01 00:01:01 User CRON[4974]: (CRON) info (No MTA installed, discarding output)
で、ネットを検索したら、manpageに記述があるよ、と。
で、自分のローカルのmanpege確認したら、しっかり書いてある。
(しかし、なんで日本語のmanページが表示されないんだろう。。。)
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
crontab file. Percent-signs (%) in the command, unless escaped with back‐
slash (\), will be changed into newline characters, and all data after the
first % will be sent to the command as standard input. There is no way to
split a single command line onto multiple lines, like the shell's trailing
"\".
(意訳です:
6番目のフィールドは実行するコマンドを指定します。
指定したコマンドは、”行末か%文字まで”が/bin/shかcrontabのSHELL変数で設定したシェルで実行されます。
コマンドの%記号は、”バックスラッシュ(\)でエスケープされない限り、改行文字に置き換えられ、最初の%記号以降は標準入力としてコマンドに送られます。
シェルの"\"での分割のような、1つのコマンドを複数のコマンドに分割する方法は、(crontabには)ありません。)
あぁぁ、そうなのね。
ならば、逆にいえば、バックスラッシュでエスケープすればいいのね。
そうなのね。
manは大事。
そりゃ、公式マニュアルだもの。
そうりゃそうだよね。
すみませんでした。
という、お話。
参考URL:
keigoiの日記(dateコマンド と crontab の コマンドライン中の %(パーセント)記号)http://d.hatena.ne.jp/keigoi/20090204/1233715870
ひだまりソケットは壊れない(cron 設定ファイル (crontab ファイル) の置き場所と書式について)
http://vividcode.hatenablog.com/entry/man-cron-and-crontab