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).</p>

From cp command man pages:

--preserve[=ATTR_LIST]
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 tre.sh is having the following details:

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

Lets copy tre.sh to /tmp/tre.sh

$ cp tre.sh /tmp/tre.sh

So the timestamp is changed to the present timestamp

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

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

$ cp --preserve=timestamps tre.sh /tmp/tre.sh.1

The original timestamp is preserved here

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

Now I just switched to root user

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

Copy tre.sh to /tmp/tre.sh.2

$ cp tre.sh /tmp/tre.sh.2

Notice the ownership and timestamp of the /tmp/tre.sh.2

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

You can preserve the ownership like this:
$ cp --preserve=ownership tre.sh /tmp/tre.sh.4

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

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 tre.sh /tmp/tre.sh.5

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

$ ls -l /tmp/tre.sh.5
-rw-r--r-- 1 jk staff 476 2009-01-13 16:20 /tmp/tre.sh.5 </div> </div>

comments powered by Disqus