Skip to content

How to Preserve Directory Path with CP Command

The cp command is used to copy files from one directory to another directory. Some times 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 cp command with --parents option to use 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 4864094 Jan 15 11:09 /opt/dir1/dir2/myfile.txt

Rahul

Rahul Kumar is the founder and chief editor of TecAdmin.net. A Red Hat Certified Engineer (RHCE), he has worked in IT since 2009, with hands-on experience in Linux system administration, DevOps, web hosting, cloud platforms and automation. He started TecAdmin in 2013 to share practical, step-by-step guides, and leads its editorial work with one aim: making technical learning clear and useful for sysadmins, developers and beginners alike.

Leave a Reply

Your email address will not be published. Required fields are marked *


Back to top