Copy a File by Preserving its Parent Directories in Linux Command Line

Let’s say we want to copy a file sample.txt located at ~/Work/Team to another directory ~/Personal. But we don’t want to copy the file alone, but the parent directories too.

In this case, use:

cd ~
cp --parents Work/Team/sample.txt ~/Personal

The result will be, the file sample.txt will be placed as ~/Personal/Work/Team/sample.txt.

Similarly, if we give the location as:

cp --parents ~/Work/Team/sample.txt ~/Personal

Where, ~/ means /home/$USER/.

The sample.txt will be placed as ~/Personal/home/team/Work/Team/sample.txt

This does not mean all the home directory contents are copied.

2 Likes