Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get file mode in octal with stat (BSD vs GNU)

I am trying to get the file bits in octal, to assess whether a path is a regular file or a directory.

This works pretty well in BSD stat which is part of my macOS:

$ stat -f %Op /tmp/test.txt 
100644

How can I get the same (or similar) result in stat from GNU. The best I got is:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$ stat -c "%a" /tmp/test.txt
644
$ stat -c "%A" /tmp/test.txt
-rw-r--r--

Right now, the only way I am seeing is parsing the string result and check whether first character is - or is d.

>Solution :

GNU stat has the %f format code for this. Unfortunately, it displays the raw mode in hex, so you have to use e.g. the shell’s facilities to convert it.

Notice also that the format is specified with -c.

printf '%06o\n' 0x$(stat -c '%f' /tmp/test.txt)

For more details, refer to the man page.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading