1

I want to recursively copy a directory, preserving file attributes, which contains a directory tree including some files that have permission 200 (i.e. --w-------).

The copy command cp -ar sourcedirectory targetdirectory skips those files, saying, for each one, something like this:

cp: cannot open `sourcedirectory/foo/somefile.bar' for reading: Permission denied` 

My question: without altering their permissions, how can I prevent the copy command from skipping those files?

If you think I ought to use a utility other than cp in my copy command, please explain why.

3 Answers 3

2

You must make the file readable in order to copy it. This is unrelated to the choice of tool: every program will fail to open the file for reading since you do not have the permission to read it.

If ACLs are enabled (with ext2/ext3/ext4, this requires the mount option acl) and you aren't interested in copying them, add an ACL that allows the user doing the copy to read the file.

setfacl -R -m u:username:rX sourcedirectory 

Otherwise, you'll have to either change the file permissions beforehand and restore them (on both sides) afterwards, or do the copy as root.

1

This page gives a variety of ways to copy data, preserving as much metadata as possible. You could try each of these, as root:

  • cp -av /source /dest # don't use -r, its behavior is hard to predict and -a already includes -R
  • cd /source; tar -cf- . | tar -xvpf- -C /dest
  • cd /source; find . -depth -print0 | cpio -pdmv -0 /dest
  • rsync -av --delete --hard-links /source/ /dest

Rsync is a bit tricky about trailing /s in its arguments. As explained in its manpage, both of these are ways to copy the directory /source/foo to /dest/foo:

  • rsync ... /source/foo /dest
  • rsync ... /source/foo/ /dest/foo

Its possible that none of these will work. Make sure you try them while root for the best prospects.

1
  • Any of these methods will work, the key thing is as root. Commented Oct 21, 2012 at 21:55
0

As far as I can think, we can follow these steps to maintain permission as it is and copy all the files also.

$ cd <sourcedirectory> $ tar -cvf <sourcedirectory.tar> . $ cp <sourcedirectory.tar> <destinationdirectory> $ tar -xvf <sourcedirectory.tar> 
2
  • Unfortunately, the second step fails: tar -cf sourcedirectory.tar . gives messages like tar: ./foo/somefile.bar: Cannot open: Permission denied. (I have omitted the -v option to tar, but this should not affect the issue.) Commented Oct 21, 2012 at 13:20
  • 1
    It might work if you try it as root, but be sure to add the -p flag to the fourth line to preserve permissions when expanding, rather than using whatever your current umask is. Commented Oct 21, 2012 at 14:09

You must log in to answer this question.