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.

link|improve this question

feedback

migrated from stackoverflow.com Nov 7 '10 at 2:06

This question came from our site for professional and enthusiast programmers.

7 Answers

up vote 4 down vote accepted

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.

link|improve this answer
no good on Mac OSX – ennuikiller Nov 6 '10 at 20:07
@ennuikiller: Edited. – cHao Nov 6 '10 at 20:28
feedback

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

link|improve this answer
+1, hadn't spotted that before! Appears to be specific to GNU chmod. – SimonJ Nov 6 '10 at 20:03
true, it's GNU specific and does not work on BSD or Mac OSX – Michael Nov 6 '10 at 20:07
feedback

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...

link|improve this answer
feedback

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.

link|improve this answer
feedback

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')
link|improve this answer
feedback

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

link|improve this answer
feedback

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}') 
link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.