6

I want to convert the output of ls to octal permission bits.

I think of the shortest and clearest way to implement that excerise: Let's say that we have as input:

total 1
drwxr----x 1 user2 workers 1024 May 26 22:22 dir
-rwx-wxrw- 2 user2 workers 1024 May 26 22:22 file.txt

our output should be:

741 dir
736 file.txt
Joseph R.
  • 39,549

3 Answers3

9

You could use GNU find:

find . -type f -printf "%m\t%f\n"

In order to obtain the complete path of the file, use the directive p instead of f:

find . -type f -printf "%m\t%p\n"

In order to restrict the results to the current directory, specify -maxdepth:

find . -maxdepth 1 -type f -printf "%m\t%f\n"

If you want results both files and directories, remove the -type predicate:

find . -printf "%m\t%p\n"
devnull
  • 10,691
7

You don't want to use ls for this. On a GNU system, you could use:

stat -c'%a %n' *
Joseph R.
  • 39,549
2

This may not be the clearest code but from the output quite easy to understand:

echo drwxr----x | 
awk '{chars=substr($1,2); print chars; gsub("-","0",chars); 
gsub("r","4",chars); gsub("w","2",chars); gsub("x","1",chars); 
print chars; for(i=1;i<10;i++) { sum+=substr(chars,i,1); 
if (i%3 == 0) { printf "%d",sum;sum=0; }; } print ""; }'

rwxr----x
421400001
741

(here assuming only the first 9 bits of the permissions are set)

Hauke Laging
  • 90,279
  • 3
    @JosephR. The special bits would by a tiny adaption. In any case: Not the answer would be unjustified but the question. And of course we love to do others' homework... – Hauke Laging Apr 23 '14 at 00:28