Linux – File inheriting permission of directory it is copied in

cpfile-copyfileslinuxpermissions

I have files created into my home directory with only user read permission (r-- --- ---). I want to copy this file to another directory /etc/test/ which has the folder permission of 744 (rwx r-- r--). I need to allow for the file I am copying to inherit the permission of the folder it is copied in because so far when I copy it, the files permissions are still the same (r-- --- ---). I have tried setfacl command, but it did not work? Please help.

PS. I can't just chmod -r /etc/test/ because there are many files which will be copied into this folder over time and I don't want to run chmod command every time a file is copied over.

Best Answer

Permissions are generally not propagated by the directory that files are being copied into, rather new permissions are controlled by the user's umask. However when you copy a file from one location to another it's a bit of a special case where the user's umask is essentially ignored and the existing permissions on the file are preserved. Understanding this concept is the key to getting what you want.

So to copy a file but "drop" its current permissions you can tell cp to "not preserve" using the --no-preserve=all switch.

Example

Say I have the following file like you.

$ mkdir -m 744 somedir

$ touch afile
$ chmod 400 afile 

$ ll
total 0
-r--------. 1 saml saml 0 Feb 14 15:20 afile

And as you've confirmed if we just blindly copy it using cp we get this:

$ cp afile somedir/
$ ls -l somedir/
total 0
-r--------. 1 saml saml 0 Feb 14 15:20 afile

Now let's repeat this but this time tell cp to "drop permissions":

$ rm -f somedir/afile 

$ cp --no-preserve=all afile somedir/

$ ls -l somedir/
total 0
-rw-rw-r--. 1 saml saml 0 Feb 14 15:21 afile

So the copied file now has its permissions set to 664, where did it get those?

$ umask
0002

If I changed my umask to something else we can repeat this test a 3rd time and see the effects that umask has on the un-preserved cp:

$ umask 037
$ rm somedir/afile 

$ cp --no-preserve=all afile somedir/
$ ls -l somedir/
total 0
-rw-r-----. 1 saml saml 0 Feb 14 15:29 afile

Notice the permissions are no longer 664, but are 640? That was dictated by the umask. It was telling any commands that create a file to disable the lower 5 bits in the permissions ... these guys: (----wxrwx).

Related Question