2

Is there any way to make file A has exactly same file permission as file B without specify permission like 777. For example, usually I ls file B and check its permission setting. Then 'chmod ??? fileA'. However, I am looking for a command like

chmod --argument_to_copy_file_permission fileA fileB

Please advise.

EDIT: By the way, is there any command to see file permission in digit mode (like 777), thanks.

7 Answers 7

5

This works in Linux; i'm not sure whether the programs or options are POSIX.

chmod `stat -c '%a' fileB` fileA

On Mac OSX, the following works about the same, but using options that work. :)

chmod `stat -f '%Op' fileB` fileA

(That's an uppercase "o", not a zero.)

Again, i don't know whether that's POSIX. I do know it won't work on Linux; the -f option means something totally different there.

Either way, both commands work by taking the output of the stat command on fileB, specifically the octal-formatted file modes, and uses that as the mode to set on fileA. This means the stuff in between the backquotes will give you the file modes.

2
  • no good on Mac OSX Nov 6, 2010 at 20:07
  • @ennuikiller: Edited.
    – cHao
    Nov 6, 2010 at 20:28
5

chmod --reference=fileA fileB should do it according to the manpage.

2
  • 1
    +1, hadn't spotted that before! Appears to be specific to GNU chmod.
    – SimonJ
    Nov 6, 2010 at 20:03
  • true, it's GNU specific and does not work on BSD or Mac OSX
    – Michael
    Nov 6, 2010 at 20:07
2

It's a pretty short perl script:

my ($dev, $ino, $mode, @junk) = stat "fileA";
$mode &= 07777;  # mode includes type information in higher bits
printf "%o\n", $mode;
chmod $mode, "fileB";

Making it take arguments and options left as an exercise for the reader...

1

Sort Of

$ chmod ugo=rwxrwxrwx filename

This way you can just type in what ls(1) reports, or write a simple script to do it.

This will work on all versions of Unix including Linux and the Mac.

0

It’s also a pretty short Python script:

import os
os.chmod('fileA', os.stat('fileB').st_mode)

And Ruby:

File.chmod(File.stat('fileA').mode, 'fileB')
0

I little longer than the perl script:

chmod $(ls -l file.whose.permissions.you.want.to.copy | awk '{k=0;for(i=0;i<=8;i++)k+=((substr($1,i+2,1)~/[rwx]/)*2^(8-i));if(k)printf("%0o ",k);print}' | awk '{print $1}') 
0

You can pipe the output of stat, modify it, and then use that to change the permissions of fileB:

stat fileA | grep "Access: (" | cut -c 10-13 | xargs -i  chmod {} fileB

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .