存档超过 x 天的文件

Adr*_*ian 3 unix bash

当所有文件(到一个 .tar.gz 文件)超过 X 天时,我想将它们归档到一个目录中。

我有一个班轮:

find /home/xml/ -maxdepth 1 -mtime +14 -type f -exec sh -c \ 'tar -czvPf /home/xml/archive/archive_$(date +%F).tar.gz $0' {} \;
Run Code Online (Sandbox Code Playgroud)

当我运行此命令时,我看到在此目录中选择了正确的文件,但存档中只有最后一个文件。有没有办法将所有文件放入一个 tar.gz 存档中?

@Alex 回答后的另一个问题:仍然缺少许多文件,请查看屏幕截图。

在此处输入图片说明 也许冒号 (:) 导致了问题?

Ale*_*sky 5

-exec为每个选定的文件运行命令,因此它会在其中写入一个文件的 tar,然后为每个源文件覆盖它,这解释了为什么您只获得最后一个文件。您可以使用find生成所需的文件列表,然后通过管道将xargs其传递给该列表,就好像它们是您的tar命令的参数一样:

find /home/xml/ -maxdepth 1 -mtime +14 -type f | xargs tar -czvPf /home/xml/archive/archive_$(date +%F).tar.gz
Run Code Online (Sandbox Code Playgroud)

带冒号的文件名对我来说很好用:

% dd if=/dev/urandom of=one:1 count=1
% dd if=/dev/urandom of=two:2 count=1
% dd if=/dev/urandom of=three:3 count=1
% dd if=/dev/urandom of=four:4 count=1
% dd if=/dev/urandom of=five:5 count=1
% find . -type f | xargs tar cvf foo.tar
    ./five:5
    ./four:4
    ./two:2
    ./three:3
    ./one:1
% tar tvf foo.tar
    -rw------- alex/alex       512 2017-07-03 21:08 ./five:5
    -rw------- alex/alex       512 2017-07-03 21:08 ./four:4
    -rw------- alex/alex       512 2017-07-03 21:08 ./two:2
    -rw------- alex/alex       512 2017-07-03 21:08 ./three:3
    -rw------- alex/alex       512 2017-07-03 21:08 ./one:1
Run Code Online (Sandbox Code Playgroud)