LoginSignup
79
76

More than 5 years have passed since last update.

dateコマンドでバックアップファイル作成時にファイル名に日付_時間を付ける (LinuxとWindows用)

Last updated at Posted at 2015-01-22

dateコマンドでバックアップファイル名末尾に日付_時間を付ける

LinuxとWindowsでcpコマンドによりファイルのバックアップを作成する場合、バックアップファイル名の末尾に日付_時間を付けるコマンドです。

(1) Linux版のコマンド

$ cp -p バックアップ対象ファイル名 バックアップファイル名.`date "+%Y%m%d_%H%M%S"`

(2) Windows版のコマンド

D:\> copy バックアップ対象ファイル名 バックアップファイル名.%date:~0,4%%date:~5,2%%date:~8,2%_%time:~0,2%%time:~3,2%%time:~6,2%

コマンド実行した環境

・CentOS release 6.6 (2.6.32-504.3.3.el6.x86_64)

・Windows 7 Professional (32bit版)

コマンド実行例(Linuxの場合)

例えばLinuxの/etc/fstabのバックアップを作成する場合、以下のように実行すると、バックアップファイル名末尾に日付_時間を付ける事が出来ます。

# date
Fri Jan 23 02:48:40 JST 2015
# date "+%Y%m%d_%H%M%S"
20150123_024843
# cp -p /etc/fstab /etc/fstab.`date "+%Y%m%d_%H%M%S"`
#

バックアップファイル名は /etc/fstab.20150123_024858 のような形で作成されます。

# ll /etc/fstab.20150123_024858
-rw-r--r--. 1 root root 584 Oct  3 01:59 /etc/fstab.20150123_024858
#
# ll /etc/fstab
-rw-r--r--. 1 root root 584 Oct  3 01:59 /etc/fstab
#
# diff /etc/fstab /etc/fstab.20150123_024858
#

コマンド実行例(Windowsの場合)

例えばWindowsのexample.txtというファイルのバックアップを作成する場合、以下のように実行すると、バックアップファイル名末尾に日付_時間を付ける事が出来ます。

まず、Windowsではデフォルトのdate環境変数で日付、time環境変数で時刻が取得可能です。

D:\tools>echo %date%
2018/12/24

D:\tools>echo %time%
19:06:28.93

D:\tools>

以下のコマンドを実行すると、20181224_190612といった形式で日付と時刻を取得出来ます。

D:\tools>echo %date:~0,4%%date:~5,2%%date:~8,2%_%time:~0,2%%time:~3,2%%time:~6,2%
20181224_190612

D:\tools>

以下のように実行すると、バックアップファイル名末尾に日付_時間を付ける事が出来ます。

D:\tools>copy example.txt example.txt.%date:~0,4%%date:~5,2%%date:~8,2%_%time:~0,2%%time:~3,2%%time:~6,2%
        1 個のファイルをコピーしました。

D:\tools>

バックアップファイル名は example.txt.20181224_190922 のような形で作成されます。

D:\tools>dir

 (中略)

 D:\tools のディレクトリ

2018/12/24  19:09    <DIR>          .
2018/12/24  19:09    <DIR>          ..
2018/12/24  19:01                 4 example.txt
2018/12/24  19:01                 4 example.txt.20181224_190922

 (中略)

以上です。

79
76
3

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
79
76