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