Get the chmod numerical value for a file

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.

Asked By: stefan.at.wpf

||

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.

Answered By: PersianGulf

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>
Answered By: teppic

Some additional information on stat:

$ stat -c %a file.txt

777  

$ stat -c %A file.txt

-rwxrwxrwx
Answered By: Mateen Ulhaq

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

stat --format "%a  %n" -- *
Answered By: Hatem Badawi
Categories: Answers Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.