Copy file to backup directory preserving folder st

2019-05-11 06:37发布

问题:

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).