Standard way to duplicate a file's permissions

You can use the stat command to get the file permission :

  • Mac OS X (BSD) syntax :

    chmod `stat -f %A fileWithPerm` fileToSetPerm

  • Linux syntax (not sure) :

    chmod `stat -c %a fileWithPerm` fileToSetPerm

The ` symbol is a backquote.


One temptation is to parse ls. Avoid that temptation.

The following seems to work, however it is full of teh Kluge. It relies on cp retaining the permissions of the target file. For this demo, the file "template" must not already exist.

  • Copy the file with the permissions you want to a new file
  • Copy the file that you want to change to the file created in the previous step
  • Remove the original file that you want to change
  • Rename the intermediate file to the name of the file to be changed

Demo:

$ echo "contents of has">has
$ echo "contents of wants">wants
$ chmod ug+x has     # just so it's different - represents the desired permissions
$ cp has template
$ cat has
contents of has
$ cat wants
contents of wants
$ cat template
contents of has
$ ls -l has wants template
-rwxr-xr-- 1 user user 16 2010-07-31 09:22 has
-rwxr-xr-- 1 user user 16 2010-07-31 09:23 template
-rw-r--r-- 1 user user 18 2010-07-31 09:22 wants
$ cp wants template
$ ls -l has wants template
-rwxr-xr-- 1 user user 16 2010-07-31 09:22 has
-rwxr-xr-- 1 user user 18 2010-07-31 09:24 template
-rw-r--r-- 1 user user 18 2010-07-31 09:22 wants
$ cat template
contents of wants
$ rm wants
$ mv template wants
$ ls -l has wants
-rwxr-xr-- 1 user user 16 2010-07-31 09:22 has
-rwxr-xr-- 1 user user 18 2010-07-31 09:24 wants
$ cat has
contents of has
$ cat wants
contents of wants