FreeBSD find the chmod numerical value for a file or directory

I

need to find out the numerical value of a file on a FreeBSD system. For example, get 644 instead of -rw-r–r– for the /etc/resolv.conf file. Is there is a way to get this value in my bash shell script?

 

You need to use the stat command to see information about the file.

Usage

The basic syntax is:

stat file

stat [options] file

Examples

To see info about /etc/resolv.conf, enter:

$ stat /etc/resolv.conf

 

Sample outputs:

1314290432 258051 -rw-r–r– 1 root wheel 4294967295 57  Jan 24 01:02:44 2016   Oct 12 16:30:41 2015   Oct 12 16:30:41 2015   Oct 12 16:30:41 2015  4096 1 0x800 /etc/resolv.conf

To see verbose output (just like Linux) pass the -x option to stat, enter:

$ stat -x /etc/resolv.conf

 

Sample outputs:

Fig.01: FreeBSD stat command output

Get the chmod numerical value for a file with stat command

Pass the -f format option to display information using the specified format as follows:

stat -f  %OLp  /path/to/file

stat -f  %OLp  /etc/resolv.conf

perm=$(stat -f  %OLp  /etc/resolv.conf)

echo  $perm

Sample outputs:

Fig.02: Get the value directly using a stat command

 

Where,

-f  Format  – Display info about file using given format.

% – Format strings are similar to printf formats in that they start with %, are then followed by a sequence of formatting characters.

O – Sets the fill character for left padding to the ‘0’ character, instead of a space.

L – Select bits for permissions from the string form of p (last or below option).

p – Display the mode of file (numercial value for file permission as in ls -lTd).

Use raw information to extract numerical value for a file

Run the following command:

$ stat -r /etc/resolv.conf | awk  { print $3}

 

Sample outputs:

0100644

You can use as follows to get last four digits:

x=$(stat -r /etc/resolv.conf  | awk  { print $3} )

cut -c 4-8 <<< $x

Sample outputs:

0644

A note about Linux user

Try the following command on Linux for the same purpose:

Linux stat syntax ##

stat -c  %a  /etc/resolv.conf

 

Or use find command, may work on unix-like system. See find man page. ##

find /etc/ -name resolv.conf -printf  %m\n

Sample outputs:

644

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *