Linux permissions and owner being preserved with cp

5

1

I can't understand the following behavior:
I have a file named someFile under /opt/com/internal/someFile
If I do ls -all /opt/com/internal/someFile the permissions are 700 user:userGroup

I am root and I do cp /root/folder/someFile /opt/com/internal/someFile

  1. I don't get a prompt to overwrite. Why not?

  2. The permissions are unchanged. But if I do cp /root/folder/someFile /opt/com/internal/someFile and the file someFile does not exist it is owned by root and not user. Why?

Jim

Posted 2012-04-06T08:20:27.593

Reputation: 521

Answers

10

I don't get a prompt to overwrite. Why not?

Because you're supposed to know what you're doing. Especially as root, you can overwrite pretty much anything, so pay attention to that.

Use the -i option for cp to get a prompt before overwriting existing files. If you always want to be reminded of this, consider creating an alias for cp to cp -i.

The permissions are unchanged. But if […] file someFile does not exist it is owned by root and not user. Why?

Because the file you're copying to is already existing. It's not deleted and re-written. It's still owned by user.

However, check cp's -p option. It will preserve the attributes of the source file, namely the mode, ownership and timestamps. Otherwise, the mode and ownership attributes of the target file will stay (except for the timestamps which will indicate a modification).

If there's no target file, obviously the attributes of the source file need to be copied, since they can't be inherited from a target file. You'll basically just create a new file, and in this case it's owned by root.

slhck

Posted 2012-04-06T08:20:27.593

Reputation: 182 472

5Just a comment on using aliases adding -ito cp/rm: it can be a problem if one gets used to this, and suddenly finds oneself on a system where these non-standard aliases are not set. It is good to not make a habit out of expecting them. "Default is almost always better", as I apparently said just now :-) . – Daniel Andersson – 2012-04-06T09:01:18.243

Absolutely. If you're root you should be aware of that and it's not the first time I've seen someone overwrite important system files being too eager while copying. – slhck – 2012-04-06T09:14:37.860

2

1) cp will not prompt for overwrite unless the -i argument is used, this has been the default behavior since the first unix

2)from wikipedia : The overwriting of a file to an existing file is performed by opening the existing file in update mode, thereby preserving the files inode, which requires write access and results in the target file retaining the permissions it had originally.

Sibster

Posted 2012-04-06T08:20:27.593

Reputation: 784