How Can I Get Binary File Permissions from Command Line?

How Can I Get Binary File Permissions from Command Line?

By using stat -c "%a %n" * I'm getting file permissions in octal mode (such as 755), Is there any way to see the file permissions in binary mode (such as 111 101 101)?

4 Answers

For a single file:

stat -c "%a" filename.txt | xargs -I PERM echo "obase=2; ibase=8; PERM" | bc

And as a more clear script for more that of one file:

#!/bin/bash
for file in *
do
  perm=$(stat -c "%a" "$file")
  bin=$(echo "obase=2; ibase=8; $perm" | bc)
  echo "$bin $file"
done

the output:

110110100 baz
110110100 foo
110110101 bar

Notes

  • First we loop into all files and directories using for file in *.
  • With stat -c "%a we gather the file permission in octal, then
  • Using echo we add other necessary details to permission and pip it to bc.
  • Finally bc does the conversion and then we printout the result and file name.
  • obase=2; means output should be in binary, ibase=8 means our input is in octal and $perm is the file permission in octal like 664.
0

You can do this using the perl stat module e.g. given

$ stat -c '%a %n' *
600 other file
775 somedir
664 somefile

then

$ perl -MFile::stat -e 'printf "%b %s\n", (stat $_)->[2] & 07777, $_ for @ARGV' *
110000000 other file
111111101 somedir
110110100 somefile

If you just want to visualize file permissions in binary, you could use the first column of ls -l:

$ ls -ld /bin
drwxr-xr-x 2 root root 4096 mai 18 05:38 /bin

Here you can see that rwxr-xr-x corresponds to 111101101

Python

$ python -c 'import sys,os;[ sys.stdout.write( " ".join([bin(os.stat( i ).st_mode)[-9:],i,"\n"]) ) for i in sys.argv[1:] ]' /etc/passwd
110100100 /etc/passwd 

The job is done via os.stat() function, which returns a tuple of file attributes, among which isst_mode in decimal format. We then convert it to binary, and extract last 9 digits.

Everything is performed within list comprehension to operate on all files given on command-line (so you can provide multiple files or use globstar).

As a script

#!/usr/bin/env python2

import sys, os

for filename in sys.argv[1:]:
    perms = os.stat(filename).st_mode
    print bin(perms)[-9:], filename
5

Your Answer

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

Robert Thorne
Author

Robert Thorne

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.