Thursday, February 5, 2009

Linux - copy file and preserve timestamp, ownership, mode

If you want to copy files in Linux and also want to keep or preserve the original mode or timestamp or ownership (or all) , cp command gives an option (--preserve).

From cp command man pages:

preserve the specified attributes (default: mode,ownership,timestamps) and security contexts, if possible additional attributes: links, all

Lets discuss this with some small examples.

I am logged in as user 'jk'

$ id
uid=32321(jk) gid=700(staff)

The example file is having the following details:

$ ls -l
-rw-r--r-- 1 jk staff 476 2009-01-13 16:20

Lets copy to /tmp/

$ cp /tmp/

So the timestamp is changed to the present timestamp

$ ls -l /tmp/
-rw-r--r-- 1 jk staff 476 2009-02-05 15:10 /tmp/

Now copy using "--preserve=timestamps" option.

$ cp --preserve=timestamps /tmp/

The original timestamp is preserved here

$ ls -l /tmp/
-rw-r--r-- 1 jk staff 476 2009-01-13 16:20 /tmp/

Now I just switched to root user

$ id
uid=0(root) gid=0(root) groups=0(root)

Copy to /tmp/

$ cp /tmp/

Notice the ownership and timestamp of the /tmp/

$ ls -l /tmp/
-rw-r--r-- 1 root root 476 2009-02-05 15:13 /tmp/

You can preserve the ownership like this:
$ cp --preserve=ownership /tmp/

So /tmp/ is still owned by user jk" (copied by root though)
$ ls -l /tmp/
-rw-r--r-- 1 jk staff 476 2009-02-05 15:14 /tmp/

Also we can specify "--preserve=ownership,timestamps" and also preserve the mode(permission) of the file with "--preserve=mode"

The cp command -p option is equivalent to --preserve=mode,ownership,timestamps

I am still 'root'; now copy using -p option

$ cp -p /tmp/

All the original attributes (mode,permission,ownership) of is preserved.

$ ls -l /tmp/
-rw-r--r-- 1 jk staff 476 2009-01-13 16:20 /tmp/


rattus said...

I was wondering how to best copy only the permissions and ownership of one file to another. Any ideas?

Hashid said...

Hi is there any way to copy files preserving only the Timestamps ?
I did preserve=timestamps, but then I cannot edit the copied file, it says permission denied.

© Jadu Saikia