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" | bcAnd 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"
donethe output:
110110100 baz
110110100 foo
110110101 barNotes
- First we loop into all files and directories using
for file in *. - With
stat -c "%awe gather the file permission in octal, then - Using
echowe add other necessary details topermissionand pip it tobc. - Finally
bcdoes 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.
You can do this using the perl stat module e.g. given
$ stat -c '%a %n' *
600 other file
775 somedir
664 somefilethen
$ 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 /binHere 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