Unix "cp -p". Can I preserve attributes selectively?

4

I'd like to copy the modification and access times, but not the user ID. If I use

cp -p source target

It will copy everything.

I'm trying to copy files to a different user but keep the original dates intact.

Adam

Posted 2013-10-13T19:52:22.937

Reputation: 161

Answers

6

From the cp manual of GNU coreutils:

-p same as --preserve=mode,ownership,timestamps

So, you are looking for

cp --preserve=mode,timestamps source target

But if you use some non-GNU operating system, you might not be able to use these long option with cp. In that case, you can give rsync a try, where you can specify in details which attributes should be preserved (search the man page for "preserve"):

    -H, --hard-links            preserve hard links
    -p, --perms                 preserve permissions
    -E, --executability         preserve executability
    -A, --acls                  preserve ACLs (implies -p)
    -X, --xattrs                preserve extended attributes
    -o, --owner                 preserve owner (super-user only)
    -g, --group                 preserve group
        --devices               preserve device files (super-user only)
        --specials              preserve special files
    -t, --times                 preserve modification times

So, to resemble the cp command above, use something like

rsync -pEt source target

To test the command beforehand, you can initiate a "dry-run" with -n. Add also the verbose parameter -v to see what's going on:

rsync -nv -pEt source target

However, I'm not sure, if the access time will be copied, too.

mpy

Posted 2013-10-13T19:52:22.937

Reputation: 20 866

Makes sense, but I'm (noobishly) not sure how to use the long options. I've been trying to test with something safer than cp ("ls --all") but I get an "illegal option" error. – Adam – 2013-10-13T20:17:29.177

Are you using some non-GNU Un*x system? BSD for example? Honestly, I didn't paid too much attention to the flags in the question, so my answer applies to cp from the GNU coreutils. ls --all works there, too. – mpy – 2013-10-13T20:31:22.370

I'm on a Mac using the Terminal application. – Adam – 2013-10-13T20:38:48.413

2Then, I think, your cp doesn't offer long options. I'll add an alternative possibility with rsync, perhaps that's an option for you. – mpy – 2013-10-13T20:45:33.107

1Or you could use one of the FOSS package managers for Mac OS and install GNU cp. – David Foerster – 2013-10-13T23:27:59.667

1

I believe the ditto command preserves dates.

ditto src target

Kevin

Posted 2013-10-13T19:52:22.937

Reputation: 61

This is the only solution that worked properly for me to preserve mtimes. When using cp -p..., or cp -p -r..., for some unknown reason, 4 out of 10 files preserved their mtime as expected, but the other 6 showed up with the copy time as the new mtime. – LOlliffe – 2019-08-05T01:24:22.507