Scenario: with a script run by a normal user I want to copy several files, and replicate the dir structure. For example:

cp --parents /lib/libacl.so /tmp/my_root/
cp --parents /lib/libc.so.6 /tmp/my_root/

Expected result: first cp, creates /tmp/my_root/lib and puts libacl.so in there. Second cp puts libc.so.6 in /tmp/my_root/lib.

The problem is that the first cp creates /tmp/my_root/lib with the following permissions: dr-xr-xr-x., so the second cp fails with Permission denied.

Of course, if I run the script as root everything works fine.

One solution could be create the dir first and then copy the file, so the dir will have the proper permissions, but I was wondering if there was a better way of doing this, maybe some flag of cp? I checked the man but didn't find anything.

  • I suppose that the user who does the cp --parents cannot write in the /lib directory too. The /tmp/myroot/lib directory has the same rights as the /lib directory.
    – Marco
    Aug 31 '15 at 14:29
  • Right, the user cannot write in the /lib. So the solution is create the folder first, and then copy the file. I cannot use cp --parents in this scenario.
    – Nico
    Aug 31 '15 at 14:33

I cannot see a solution with cp. You can use rsync to do the same sort of copies, and it also creates a non-writeable lib dir, but it is capable of then adding new files to the dir. Your commands become:

rsync -LR /lib/libacl.so /tmp/my_root/
rsync -LR /lib/libc.so.6 /tmp/my_root/

The -R preserves the directory structure. I added -L so that symbolic links are followed, as that seems to be what cp does, though usually this is not what is wanted. You can add -a to preserve permissions and timestamps (and owner/group if root).

rsync is often used to copy files over the network, but it is a very versatile command.

If you dont have rsync, some other commands which copy files, but create a writeable dir, are tar and cpio:

tar cf - /lib/libc.so.6 | tar -C /tmp/my_root/ -xf -

Or use chf to follow links. For cpio:

ls /lib/libc.so.6 | cpio -pd /tmp/my_root/

with -L to follow links.

  • The answer is correct and works. However, I cannot use it since in some machines (Solaris) I've found that rsync is not installed. Nevertheless, the solution is correct.
    – Nico
    Aug 31 '15 at 17:36
  • You probably know about tar and cpio, but I added them as alternatives, as they recreate the directory structure, but keep them writeable. Really need to be wrapped into a small shell script, though.
    – meuh
    Aug 31 '15 at 17:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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