Standard way to duplicate a file's permissions

I am trying to find a standard POSIX way to duplicate one file's permissions to another file. On a GNU system this is easy:

[alexmchale@bullfrog ~]$ ls -l hardcopy.*
-rw-r--r-- 1 alexmchale users 2972 Jul  8 20:40 hardcopy.1
---------- 1 alexmchale users 2824 May 14 13:45 hardcopy.4
[alexmchale@bullfrog ~]$ chmod --reference=hardcopy.1 hardcopy.4
[alexmchale@bullfrog ~]$ ls -l hardcopy.*
-rw-r--r-- 1 alexmchale users 2972 Jul  8 20:40 hardcopy.1
-rw-r--r-- 1 alexmchale users 2824 May 14 13:45 hardcopy.4

Unfortunately, the --reference flag to chmod is a non-standard option. So that is out for my purposes. I would prefer it to be a one-liner, but that's not necessary. Ultimately, it does need to be in POSIX sh syntax.


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

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.