Copy file to backup directory preserving folder st

2019-05-11 06:46发布

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

3条回答
Lonely孤独者°
2楼-- · 2019-05-11 06:59

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

查看更多
别忘想泡老子
3楼-- · 2019-05-11 07:12

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.

查看更多
姐就是有狂的资本
4楼-- · 2019-05-11 07:20

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.

查看更多
登录 后发表回答