How to Preserve Directory Path with “cp” Command

In this tutorial, we will learn How to Preserve the Directory Path with the “cp” Command?

The “cp” command is used to copy files from one directory to another directory. Sometimes you are required to copy a file with its parent directory structure.

You can use -r option to copy files recursively. But if we need to copy a single file with the full directory structure. Use the cp command with --parents the option to use the full source file name under the directory and create a similar directory structure on the destination.

cp --parents ./dir1/dir2/myfile.txt /opt/

Now list the file on the destination directory. You can see that the same directory structure is created in the destination directory.

ls -l /opt/dir1/dir2/myfile.txt


-rwxr-xr-x 1 root root 7077777 Jan 20 11:09 /opt/dir1/dir2/myfile.txt

Leave a Comment