简体   繁体   English

使用 xargs 编写 Bash 脚本来备份文件

[英]Bash Scripting with xargs to BACK UP files

I need to copy a file from multiple locations to the BACK UP directory by retaining its directory structure.我需要通过保留其目录结构将文件从多个位置复制到 BACK UP 目录。 For example, I have a file "a.txt" at the following locations /a/b/a.txt /a/c/a.txt a/d/a.txt a/e/a.txt, I now need to copy this file from multiple locations to the backup directory /tmp/backup.例如,我在以下位置有一个文件“a.txt”/a/b/a.txt /a/c/a.txt a/d/a.txt a/e/a.txt,我现在需要将此文件从多个位置复制到备份目录 /tmp/backup。 The end result should be:最终结果应该是:

when i list /tmp/backup/a --> it should contain /b/a.txt /c/a.txt /d/a.txt & /e/a.txt.当我列出 /tmp/backup/a --> 它应该包含 /b/a.txt /c/a.txt /d/a.txt & /e/a.txt。

For this, I had used the command: echo /a/*/a.txt |为此,我使用了命令:echo /a/*/a.txt | xargs -I {} -n 1 sudo cp --parent -vp {} /tmp/backup. xargs -I {} -n 1 sudo cp --parent -vp {} /tmp/backup. This is throwing the error "cp: cannot stat '/a/b/a.txt /a/c/a.txt a/d/a.txt a/e/a.txt': No such file or directory"这是抛出错误“cp:无法统计'/a/b/a.txt /a/c/a.txt a/d/a.txt a/e/a.txt':没有这样的文件或目录”

-I option is taking the complete input from echo instead of individual values (like -n 1 does). -I 选项是从 echo 获取完整输入而不是单个值(就像 -n 1 那样)。 If someone can help debug this issue that would be very helpful instead of providing an alternative command.如果有人可以帮助调试这个问题,那将非常有帮助,而不是提供替代命令。

Use rsync with the --relative ( -R ) option to keep (parts of) the source paths.rsync--relative ( -R ) 选项一起使用以保留(部分)源路径。

I've used a wildcard for the source to match your example command rather than the explicit list of directories mentioned in your question.我使用通配符作为源来匹配您的示例命令,而不是您的问题中提到的明确目录列表。

rsync -avR /a/*/a.txt /tmp/backup/

Do the backups need to be exactly the same as the originals?备份是否需要与原始文件完全相同? In most cases, I'd prefer a little compression.在大多数情况下,我更喜欢一点点压缩。 [tar](https://man7.org/linux/man-pages/man1/tar.1.html) does a great job of bundling things including the directory structure. [tar](https://man7.org/linux/man-pages/man1/tar.1.html)在捆绑包括目录结构在内的东西方面做得很好。

tar cvzf /path/to/backup/tarball.tgz /source/path/

tar can't update compressed archives, so you can skip the compression tar无法更新压缩档案,因此您可以跳过压缩

tar uf /path/to/backup/tarball.tar /source/path/

This gives you versioning of a sort, as if only updates changed files, but keeps the before and after versions, both.这为您提供了某种版本控制,好像只更新更改的文件,但保留之前和之后的版本。

If you have time and cycles and still want the compression, you can decompress before and recompress after.如果您有时间和周期,但仍需要压缩,则可以先解压缩,然后再重新压缩。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM