如何将日期附加到备份文件

spu*_*der 76 shell cp date

我需要备份一个文件,我希望将时间戳作为名称的一部分,以便更容易区分。

您如何将当前日期注入复制命令?

[root@mongo-test3 ~]# cp foo.txt {,.backup.`date`}
cp: target `2013}' is not a directory

[root@mongo-test3 ~]# cp foo.txt {,.backup. $((date)) }
cp: target `}' is not a directory  

[root@mongo-test3 ~]# cp foo.txt foo.backup.`date`
cp: target `2013' is not a directory
Run Code Online (Sandbox Code Playgroud)

slm*_*slm 117

这不起作用,因为该命令date返回一个包含空格的字符串。

$ date
Wed Oct 16 19:20:51 EDT 2013
Run Code Online (Sandbox Code Playgroud)

如果您真的想要这样的文件名,则需要将该字符串括在引号中。

$ touch "foo.backup.$(date)"

$ ll foo*
-rw-rw-r-- 1 saml saml 0 Oct 16 19:22 foo.backup.Wed Oct 16 19:22:29 EDT 2013
Run Code Online (Sandbox Code Playgroud)

您可能正在考虑附加一个不同的字符串是我的猜测。我通常使用这样的东西:

$ touch "foo.backup.$(date +%F_%R)"
$ ll foo*
-rw-rw-r-- 1 saml saml 0 Oct 16 19:25 foo.backup.2013-10-16_19:25
Run Code Online (Sandbox Code Playgroud)

有关日期和时间输出的更多格式代码,请参阅日期手册页

附加格式

如果您想在查阅手册页时完全控制,您可以执行以下操作:

$ date +"%Y%m%d"
20131016

$ date +"%Y-%m-%d"
2013-10-16

$ date +"%Y%m%d_%H%M%S"
20131016_193655
Run Code Online (Sandbox Code Playgroud)

注意:您可以使用date -Iordate --iso-8601将产生与date +"%Y-%m-%d. 此开关还可以使用参数来指示各种时间格式

$ date -I=?
date: invalid argument ‘=?’ for ‘--iso-8601’
Valid arguments are:
  - ‘hours’
  - ‘minutes’
  - ‘date’
  - ‘seconds’
  - ‘ns’
Try 'date --help' for more information.
Run Code Online (Sandbox Code Playgroud)

例子:

$ date -Ihours
2019-10-25T01+0000

$ date -Iminutes
2019-10-25T01:21+0000

$ date -Iseconds
2019-10-25T01:21:33+0000
Run Code Online (Sandbox Code Playgroud)


Gil*_*il' 14

cp foo.txt {,.backup.`date`}
Run Code Online (Sandbox Code Playgroud)

这扩展为类似cp foo.txt .backup.Thu Oct 17 01:02:03 GMT 2013. 大括号前的空格开始一个新词。

cp foo.txt {,.backup. $((date)) }
Run Code Online (Sandbox Code Playgroud)

大括号在不同的词中,因此按字面解释。此外,$((…))是算术扩展的语法;的输出与date算术表达式完全不同。命令替换使用一组括号:$(date).

cp foo.txt foo.backup.`date`
Run Code Online (Sandbox Code Playgroud)

更近一点。您可以用大括号将其表示为cp foo.{txt,.backup.`date`}. 仍然存在输出date包含空格的问题,所以需要放在双引号内。这会起作用:

cp foo.{txt,backup."`date`"}
Run Code Online (Sandbox Code Playgroud)

或者

cp foo.{txt,backup."$(date)"}
Run Code Online (Sandbox Code Playgroud)

的默认输出格式date不太适合文件名,如果语言环境使用/默认输出格式中的字符,它甚至可能不起作用。使用 YMD 日期格式,以便文件名的字典顺序是时间顺序(同时避免美国和国际日期格式之间的歧义)。

cp foo.{txt,backup."$(date +%Y%m%d-%H%M%S)"}
Run Code Online (Sandbox Code Playgroud)


小智 11

如果你真的想使用冗长的日期,你应该保护反引号。这种日期格式的特点是它有嵌入的空格,在 Unix shell 中是一个禁忌,除非你把它们放在引号内(或以其他方式转义它们)。

cp foo.txt "foo-`date`.txt"
Run Code Online (Sandbox Code Playgroud)

但是,我更喜欢使用较短的 ISO 格式:

cp foo.txt foo-`date --iso`.txt
Run Code Online (Sandbox Code Playgroud)


gle*_*man 5

使用一个功能,它会让你的生活更轻松。这是我使用的:

backup () { 
    for file in "$@"; do
        local new=${file}.$(date '+%Y%m%d')
        while [[ -f $new ]]; do
            new+="~";
        done;
        printf "copying '%s' to '%s'\n" "$file" "$new";
        \cp -ip "$file" "$new";
    done
}
Run Code Online (Sandbox Code Playgroud)