22
How to Copy Files and Folders in Linux While Preserving Owners and Permissions
When managing files in Linux, it’s essential to know how to copy directories while keeping their owners and permissions intact. Here’s a quick guide on using the cp
command and rsync
to achieve this.
Using the cp
Command
The cp
command is commonly used for copying files and directories. To copy a folder and preserve its attributes, you’ll want to use the -r
and -p
options:
-r
: Copies directories recursively.-p
: Preserves ownership, permissions, and timestamps.
Example:
cp -rp /source/folder /destination/folder
If you encounter permission issues, prepend sudo
:
sudo cp -rp /source/folder /destination/folder
Using rsync
For more advanced file copying, rsync
is a powerful tool. It’s great for incremental copies and has a lot of options.
To copy while preserving attributes:
rsync -a /source/folder/ /destination/folder/
The -a
option preserves everything, and the trailing slash ensures only the contents are copied.
Using sudo
for Permissions:
If needed, run:
sudo rsync -a /source/folder/ /destination/folder/
Conclusion
Whether you choose cp
or rsync
, both methods allow you to copy directories while maintaining their original properties. This ensures your files stay organized and secure. Happy copying!