557

So I was going to back up my home folder by copying it to an external drive as follows:

sudo cp -r /home/my_home /media/backup/my_home

With the result that all folders on the external drives are now owned by root:root. How can I have cp keep the ownership and permissions from the original?

Braiam
  • 35,991

12 Answers12

684
sudo cp -rp /home/my_home /media/backup/my_home

From cp manpage:

 -p     same as --preserve=mode,ownership,timestamps

 --preserve[=ATTR_LIST]
          preserve the specified attributes (default: mode,ownership,timestamps),
          if possible additional attributes: context, links, xattr, all
guido
  • 8,649
  • 221
    Much better to use cp -a. This also includes the -recursive flag, but it does more than that—it preserves everything about the file; SELinux attributes, links, xattr, everything. It's "archive mode." There are better tools for making a backup, but if you're using cp for a backup, don't use anything other than cp -a. – Wildcard Oct 14 '15 at 03:54
  • 37
    It works, but Patience is Good here. The command will only set everything right when it finishes: While it's still copying a directory, and you're running cp as root, the directory will be owned by root. It will only set it to the right permissions when it finishes with this directory. – Paul Nov 18 '15 at 17:01
  • 8
    cp -a doesn't work on some systems: e.g. OS X, where (in some versions at least) one needed to use cp -pR. On my current OS X system though (10.10.15), cp -a seems to be honored. – dubiousjim Sep 30 '17 at 16:30
  • 2
    If I use cp -a to copy a folder structure then use diff <(getfacl -R folder1) <(getfacl -R folder2) i sill seem to get different access control lists :( – philx_x May 29 '19 at 18:20
  • why do you right "cp -rp", not " cp -p" ? – Eugene Kaurov Aug 13 '19 at 14:23
  • 2
    @EugeneKaurov -r is recursive. Without it you can't copy directories. – Henno Sep 12 '19 at 06:08
  • AFAIK, do note that this does not preserve setcap/getcap. I recently had a problem where ping would return operation not permitted. Now I wonder what other binaries are missing setcap. – Gizmo Jan 04 '21 at 08:27
  • @philx_x sudo is needed to preserve user ownership, unless you're already the root user. See @telCom's comment. – jabbascript Feb 08 '22 at 16:28
  • Just tested on Ubuntu and that command copies the folder named my_home into /media/backup/my_home which means you end up with /media/backup/my_home/my_home – LoneSpawn Aug 03 '23 at 14:26
  • @LoneSpawn only if /media/backup/my_home already exists, it does so of course – guido Aug 03 '23 at 18:03
130

You can also use rsync.

sudo rsync -a /home/my_home/ /media/backup/my_home/

From the rsync manpage:

 -a, --archive
              This  is  equivalent  to  -rlptgoD.  It  is a quick way of saying you want
              recursion and want to preserve almost everything (with -H being a  notable
              omission).    The   only  exception  to  the  above  equivalence  is  when
              --files-from is specified, in which case -r is not implied.

              Note that -a does not preserve hardlinks, because finding  multiply-linked
              files is expensive.  You must separately specify -H.

See this question for a comparison between cp and rsync: https://stackoverflow.com/q/6339287/406686

Note the trailing slashes (see manpage for details).

student
  • 18,305
  • 8
    +1, cp -p is nice, but I like rsync's output so much more in general that I've aliased pcp to time rsync --progress -ah. Stands for "progress copy" in my mind. And both accept -r, so it works well for general terminal usage - but unfortunately, not in combination with sudo as shown in this question/answer. – Izkata Jul 20 '12 at 17:59
  • 24
    NB: rsync -a, does not preserve extended attributes (-X) and no ACLs (-A) - the short description says archive mode; equals -rlptgoD (no -H,-A,-X). E.g. SELinux contexts will not be preserverd without -X. For many use cases this is fine, but if you make a backup of your system partition, missing -X might break quite a lot. As far as I know, cp -a really preserves all file attributes. – Perseids Sep 23 '14 at 06:44
  • 3
    Just tested this, while sudo cp -a preserves ownership and groups, sudo rsync -a changes them into root. So, @Perseids is correct. – John Hamilton Mar 16 '18 at 11:59
  • 3
    @JohnHamilton Under Mint, this works perfectly... it only changes ownership and groups later on (I can't tell when). I've just copied my whole /home folder with rsync -aX /home /mnt/sdd/ and it worked like a charm. – Olivier Pons Oct 18 '18 at 07:04
  • 2
    @JohnHamilton that's not what Perseides said at all. – user643011 Aug 24 '19 at 15:30
  • @user643011 I was really referring to this part: "For many use cases this is fine, but if you make a backup of your system partition, missing -X might break quite a lot. As far as I know, cp -a really preserves all file attributes." – John Hamilton Aug 25 '19 at 09:17
94
cp -a

Where -a is short for --archive — basically it copies a directory exactly as it is; the files retain all their attributes, and symlinks are not dereferenced (-d).

From man cp:

   -a, --archive
          same as -dR --preserve=all
Zaz
  • 2,589
27

I use cp -pdRx which will -p preserve mode, ownership & timestamps, -d preserve links (so you get symlinks instead the file contents copied), -R do it recursively and -x stay on one file system (only really useful if you're copying / or something with an active mount point).

PS: -R instead of -r is just habit from using ls -lR.

StarNamer
  • 3,162
  • 5
    cp -ax is a slightly shorter version of the same thing. This worked great - thank you! – EM0 Mar 25 '15 at 12:27
  • Actually there is a difference between -r and -R. Check the man page (even the particular part too long to be quoted here). – geckon Jul 08 '15 at 13:23
  • 5
    I don't think there is (although there may once have been and may still be on some versions of Unix). See http://man7.org/linux/man-pages/man1/cp.1.html It simply says -R, -r, --recursive copy directories recursively. – StarNamer Jul 08 '15 at 16:09
  • Warning regarding cp -ax: With sym-src-dir being a symlink to real-src-dir, when I executed cp -ax sym-src-dir dest-dir, all it did was create a symlink dest-dir pointing to real-src-dir; it did not copy anything from inside real-src-dir/* to ``dest-dir/`. – Abdull Aug 06 '23 at 11:58
  • 1
    @Abdull - that is expected behavior with the -a switch. -a infers -d (which preserves links as links - rather than following them). If you want to follow all symlinks and include them as files/directories (instead of just symlinks) use -r --preserve=all. Please note that as per your example, it will include real-src-dir (but dir will be named sym-src-dir) – Jeremy Davis Aug 30 '23 at 21:37
19

You can do something like this:

tar cf - my_home | (cd /media/backup; sudo tar xf - )

tar keeps permissions, ownership and directory structure intact, but converts everything into a stream of bytes. You run a "subshell" (the parenthesized commands) that change directory, and then get tar to reverse the conversion. A steam of bytes becomes directories and files with correct ownership and permissions.

  • Is there a difference between using tar and using cp -rp as other answers suggest? – lucidbrot Apr 01 '20 at 15:18
  • 1
    @lucidbrot - I would think tar and cp -rp would differ only in corner cases - how they handle symbolic links or other special files, handling extended attributes of some filesystems, or dealing with sparse files. –  Apr 02 '20 at 13:40
  • 1
    +1 This is a very UNIX way of doing this. It also copies symbolic links as symbolic links. – j4nd3r53n Jul 13 '23 at 09:31
  • This should be the correct answer – Daniel Feb 08 '24 at 12:46
16

cp has an option to preserve file ownership. From the manual page of cp:

-p    Cause cp to preserve the following attributes of each source file in the copy: modification
      time, access time, file flags, file mode, user ID, and group ID, as allowed by permissions.
      Access Control Lists (ACLs) and Extended Attributes (EAs), including resource forks, will also
      be preserved.
Matteo
  • 9,796
  • 4
  • 51
  • 66
10

The answer is simple: cp has a -p option that preserves permissions (here's a fish).

But as Wojtek says in his comment, man cp (reading the fine manual) would be a good starting point (want to learn how to fish?).

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
buckdeer
  • 109
4

you can use preserve=all, then your copy will keep all attributes like owner, group and timestamp of your files. So, do your backup safely with the following command.

cp -r --preserve=all /home/my_home /media/backup/my_home
Ario
  • 141
3

rsync is good for copying terabytes of data. it adds resumability. And there are flags now to also copy extended attributes which is main issue in other comments.

rsync -aHAXS --info=progress2 --partial SOURCE_DIR DESTINATION_DIR

--hard-links, -H         preserve hard links
--acls, -A               preserve ACLs (implies --perms)
--xattrs, -X             preserve extended attributes
--sparse, -S             turn sequences of nulls into sparse blocks
--info=progress2         progress bar

source https://wiki.archlinux.org/title/rsync.

  • 1
    Good suggestion with Progress & Stats flags that cp does not offer e.g: sudo rsync -aHAXS \ --filter='-x security.selinux' \ --no-compress \ --no-inc-recursive \ --stats \ --numeric-ids \ --info=progress2 \ /media/disk/ \ / – social Oct 22 '23 at 23:47
1

I had a similar problem that I wanted to copy a large folder from one hard drive to a new one but took a while for me to consider the different partition formats.

The original was on an ext4 formatted partition on the extraction location was an external drive formatted as exFat. Once I realized this I formatted the external hard drive to ext4 and it worked, but I also used the -h flag for de-refenrencing symlinks.

tar -cf myfolder.tar myfolder
cd /path/to/new/harddrive
tar -xhf myfolder.tar

I was using Ubuntu 22.04, for additional details.

Wanted to share this experience in case someone else finds it helpful.

-2

The answer is

cp -rp /source/ /dest
AdminBee
  • 22,803
Alex
  • 540
  • 2
    This answer seems to be exactly like the accepted answer (save the for sudo call, which however the OP seemes to be necessary ...) – AdminBee Jun 02 '20 at 09:46
  • 3
    Also, you cannot preserve ownerships while copying unless you are root. Otherwise on systems with a per-user disk quota, it would allow an user to fill up other users' disk quota by making copies of their files, as a form of a local denial-of-service attack. – telcoM Jun 03 '20 at 06:41
-2

well ive using Linux Zorin and my issue was trying to copy over my home folder to an external drive while my computer is booted on a iso ( bootable usb drive ) as ive messed up my sdd and it now doest bootup properly so im doing a new install, this time i hope to install windows 7 then zorin OZ successfully or just Zorin OS, im not sure if i should dual boot or do linux with virtual machine.

what i did :

install caja ( through command line or software store )

run caja as root ( i used command line and run it as ROOT )

copy and paste my files i wanted, skipped the stuff that didnt want to copy and hopefully the ones i dont care about )

DONE.

for me 20gb of my home folder is taking forever, the few minutes it has been feels like an internity right now.

Hope this helps anyone even with all my rambling here.

Abbir
  • 1