Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

How can I copy files and directories from one user to another user on a unix system so that the file permissions don't change? The recipient is not the owner, but I have root permissions.

Thanks.

share|improve this question

migrated from stackoverflow.com Apr 16 '11 at 14:39

This question came from our site for professional and enthusiast programmers.

    
What programming language do you want to use to do this? –  Cody Gray Apr 16 '11 at 12:30
    
cp -a <src> <dst>... Cody is right, this belongs in another forum unless you are using a programming language. Judging from the question, I think this is just a basic file copy operation... Not programming. –  Mike Pennington Apr 16 '11 at 12:35
1  
Cody, Mike I'm asking about basic file copy operation using shell where there are more than one users within the same unix environment. Copying files from one user's directory to another user's directory. Sorry if this was not the right place. –  Aniket Apr 16 '11 at 12:46
    
@Akinet, my response has the command you need –  Mike Pennington Apr 16 '11 at 12:54
    
@Mike Got it. Thanks –  Aniket Apr 16 '11 at 13:06

1 Answer 1

The POSIX 'cp' command provides 'cp -pPR source-dir target-dir' to copy file hierarchies around. This preserves most of the meta-data. If run by root, then the copy will have the owner and group of the original owner. If run by mere mortals (not root), then the person running the script will own the files, and generally, the group for the files will be the effective group of the person running the script. (The exception there would be if the target directory has the SGID bit set - or you are running on MacOS X.)

The other way of doing it, which can be beneficial, is to use tar or cpio. The primary benefit of these is that they handle hard links better. The cp command treats each file name as a separate file, even if it is a hard link to another file already copied. By contrast, the archivers recognize the commonality and preserve the hard links, reducing the amount of data to be transferred. One other advantage of the archivers is that you can move the files between machines.

You'll need to check that your machine's copy of tar is capable of doing what you need, but with GNU tar (and BSD/MacOS tar), you can do:

cd source-dir
tar -cf - . | tar -xf - -C target-dir

And with cpio you can do:

cd source-dir
find . | cpio -pdmuB target-dir

Note that 'find | cpio' could run into issues with exotic file names with newlines in the file names (other characters don't cause trouble AFAIK).

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.