'cp' command: preserve group ownership

Hi,

Here is the scenario:

This file exists, with this ownership and group:

       -rw-rw-r--  1 picard starfleet   4 Jan  3 00:33 myfile.txt

Output of the 'id' command for user picard is:

       $ id picard
       uid=6392(picard) gid=723(human) groups=723(human),918(starfleet)

Output of the 'id' command for user worf is:

       $ id worf
       uid=7413(worf) gid=737(klingon) groups=737(klingon),918(starfleet)

When worf runs:

       $ /bin/cp -p myfile.txt mycopy.txt

the ownership and group look like:

       -rw-rw-r--  1 worf   klingon      4 Jan  3 00:33 mycopy.txt 

Both picard and worf belong to starfleet. Even though worf's effective gid isn't "starfleet", worf was expecting to see "starfleet" as the group owner of the mycopy.txt file.

How can worf get the desired results? Is there some other command that should be used instead of 'cp' command to achieve the desired results?
Yes, using "chgrp" to change the group owner works, but is there some single copy-like command (ie: "tar" or "rsync", etc...) that can be used?

Thanks
--Andrew

Since worf is not picard, the attempt (by cp's -p option) to set the user-ID and group-ID (most likely using the chown() system call) will fail. (Note that the -p option attempts to preserve the values of both user-ID and group-ID together; not the two values separately. There shouldn't be any expectation that the group-ID will be preserved if the user-ID can't be preserved.

You can use a pax oneliner perhaps (posistion yourself in working directory)

pax -rw -pe -s /myfile.txt/mycopy.txt/g myfile.txt $PWD/

Hi Andrewkl.

Just to make sure that this question wasn't answer before on the forum I did a search with google with this statement:

use of "cp -p"

The second search result is a post on linuxquestions.org :slight_smile:

http://www.linuxquestions.org/questions/linux-newbie-8/why-doesnt-cp-p-file-copy-file-and-preserve-ownership-169007/

Anyway, the problem has been described by Don Cragun, I'll add that root is the only one that could preserve the GID and UID with cp -p command (I guess).