How do I copy a folder keeping owners and permissions intact?

  • 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?

    Yes, it would, be I'm glad he asked because google is still faster than 'man' :-).

    I'm glad he asked too

    @StijnGeukens It's not even that google is faster, it's that even `man` to me is cryptic. In this case, `man` at `-r` says `same as --preserve=mode,ownership,timestamps`. How was I supposed to know that means keep the original permissions!?

    @KolobCanyon you mean at `-p`

    In the context of files and directories, `mode` means permissions. As in `chmod`; it means *change mode*. Nomenclature! Gotta love it.

  • guido

    guido Correct answer

    8 years ago
    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
    

    Much better to use `cp -a`. This also includes the `-r`ecursive 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`.

    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.

    `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.

    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 :(

    why do you right "cp -rp", not " cp -p" ?

    @EugeneKaurov -r is recursive. Without it you can't copy directories.

License under CC-BY-SA with attribution


Content dated before 6/26/2020 9:53 AM