96

In FreeBSD and also in Linux, how can I get the numerical chmod value of a file? For example, 644 instead of -rw-r--r--? I need an automatic way for a Bash script.

155

You can get the value directly using a stat output format, e.g. BSD/OS X:

stat -f "%OLp" <file>

or in Linux

stat --format '%a' <file>
  • thanks, selected as answer because it was the first one and also seems to be the simplest one :-) @seg_fault: stat -x YOUR_FILE gives me more than just the mode value. – stefan.at.wpf Sep 1 '12 at 21:06
  • 4
    in busybox use stat -c '%a' <file> – Stuart Cardall Aug 8 '16 at 23:49
  • 1
    single quotes are not needed, and --format can be abbreviated -c. This works: stat -c %a <file> – johny why Sep 23 '16 at 17:53
  • I needed the busybox answer on Ubuntu, otherwise 'stat: cannot read file system information for '%OLp': No such file or directory' – tofutim Mar 11 '18 at 13:34
7

use stat YOUR_FILE unless write script that calculate :

rwx rwx rwx ==> ( r = 4 ) if set + ( w = 2) if set + (x = 1) if set , for example:
You have :
-rw-wxrw- => (4+2+0)(0+2+1)(4+2+) = 0636 
First argument before 9 permissions is one of :
- = regular file
d =  directory
b = block device
c = character device
s = socket
p = pipe
f = fifo

By the way , I use stat command on Linux box, not freebsd, because it investigate HFS probably work with UFS.

  • Yes, i found it under FreeBSD box, use stat -x YOUR_FILE under FreeBSD box – PersianGulf Sep 1 '12 at 19:02
  • stat -r YOUR_FILE |awk '{print $3}' gives your permission. – PersianGulf Sep 1 '12 at 19:09
  • command to show friendly? not only a number like 666 or codes -rw-wxrw- but a text with explanations about each permission. – Peter Krauss Dec 3 '18 at 19:18
  • @PeterKrauss , It's better to write an awk to retrive numerical result. – PersianGulf Dec 6 '18 at 16:07
  • Thanks @PersianGulf. Hum... No plug-and-play standard way.... – Peter Krauss Dec 6 '18 at 23:04
2

Some additional information on stat:

$ stat -c %a file.txt

777  

$ stat -c %A file.txt

-rwxrwxrwx
  • it is stat -f %A file.txt under mac, it would return 644 or some other 3 digital number. – Weijing Jay Lin Jun 15 '17 at 7:11
2

try this to list all

stat --format "%a  %n" *

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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