Copy file to backup directory preserving folder structure

ⅰ亾dé卋堺 提交于 2020-02-22 06:20:06

问题


I have to copy a file in a directory, to its backup directory, preserving the folder structure. E.g. the file aaa in MyFolder/Test/aaa to .MyFolder.bck/Test/aaa

I tried to use

cp --parents MyFolder/Test/aaa .MyFolder.bck;

But the result is .MyFolder.bck/MyFolder/Test/aaa and not .MyFolder.bck/Test/aaa (which is the one I want).


回答1:


You need to cd to the directory and then copy the file:

(cd MyFolder && cp --parents Test/aaa ../.MyFolder.bck)

The brackets around the command make it run in a subshell, rather than in your current shell. The advantage of this is that it saves you from having to cd back to the original directory afterwards.




回答2:


Why don't you use two commands?

cd MyFolder && cp --parents /Test/aaa .MyFolder.bck;

And there are several synchronization utilities for Linux too, even for backup purposes, e.g. rsync, rdiff-backup, synkron... Not to mention the advantages of a local VCS... You should not reinvent the wheel.




回答3:


I like to use "rsync" for this.

rsync -av MyFolder/ .MyFolder.bck/

Make sure to use the trailing slashes, since they tell rsync that both of these arguments are the "top level" directories (that is, don't create another MyFolder inside of .MyFolder.bck).



来源:https://stackoverflow.com/questions/16209430/copy-file-to-backup-directory-preserving-folder-structure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!