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