163

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.

Michael Mrozek
  • 91,316
  • 38
  • 238
  • 232
stefan.at.kotlin
  • 3,007
  • 7
  • 32
  • 35

4 Answers4

255

You can get the value directly using a stat output format, e.g.

Linux:

stat --format '%a' <file>

BSD/OS X:

stat -f "%OLp" <file>

Busybox:

 stat -c '%a' <file>
Peter
  • 115
  • 6
teppic
  • 4,535
  • 1
  • 17
  • 17
  • 2
    single quotes are not needed, and `--format` can be abbreviated `-c`. This works: `stat -c %a ` – 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
  • I use `lubuntu`, have `busybox` and `stat -c` gives the result, but `-f` spits out error and prints blocks and inodes info, similar to tofutim. – Timo May 14 '21 at 19:32
13

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+0) = 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.

PersianGulf
  • 10,728
  • 8
  • 51
  • 78
11

Some additional information on stat:

$ stat -c %a file.txt

777  

$ stat -c %A file.txt

-rwxrwxrwx
Mateen Ulhaq
  • 681
  • 7
  • 13
5

With GNU stat, try this to get the value for all non-hidden files in the current working directory.

stat --format "%a  %n" -- *
Stéphane Chazelas
  • 522,931
  • 91
  • 1,010
  • 1,501
Hatem Badawi
  • 197
  • 1
  • 5