1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

シェルスクリプト リダイレクト先ファイル名に日付文字列

1
Last updated at Posted at 2019-12-21

date コマンドの書式で大文字・小文字を間違えることがあります。

書式 表示
%Y 年(1970年以降の西暦を4桁で表示)
%m 月(01月から12月を2桁で表示)
%d 日(01日から31日を2桁で表示)
%H 時(00時から23時を2桁で表示)
%M 分(00分から59分を2桁で表示)
%S 秒(00秒から59秒を2桁で表示)

年月日-時分秒で出力させたい場合、date +%Y%m%d-%H%M%S と指定する。

log-with-date
# 2019年12月21日 10時20分30秒に実行した場合
$ ls > `date +%Y%m%d-%H%M%S`.log
-> 20191221-102030.log というファイルが作成されます

man date コマンドで書式を見てみると、上記以外にも %I (時間を12時表記) などがある。
また、そのOSにインストールされている date コマンドのバージョンによっても違う場合がある。
少なくとも、上記の表にある書式については、どの環境でも違いなく使用できる。

(追記)
また、crontab 上で指定する場合は、% をエスケープする必要があります。
例)date +\%Y\%m\%d-\%H\%M\%S
crontab(5)のマニュアルに記載されているように、% はエスケープされていないと、改行コードに置き換えられてしまいます。

man-crontab(5)
$ man 5 crontab
...(抜粋)...
Percent-signs (%) in the command, unless escaped with backslash (\), will be changed into newline characters
1
2
0

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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?