This question already has an answer here:

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

marked as duplicate by Stéphane Chazelas, Thomas Nyman, jasonwryan, Anthon, Hauke Laging Apr 23 '14 at 8:49

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 3
    Please Do not parse ls output – Kiwy Apr 23 '14 at 0:08
  • 2
    @Kiwy I suspect that this is a homework exercise and the whole point is to parse a string like drwxr----x. The serious this-is-how-you-should-do-it-in-practice answers nicely illustrate how trying to disguise homework exercises can backfire. – Gilles Apr 23 '14 at 0:47
  • I dont see a question... – mikeserv Apr 23 '14 at 2:07
  • @StephaneChazelas OK, if I had ever given such an answer I would remember that question, too... – Hauke Laging Apr 23 '14 at 8:49

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"

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

stat -c'%a %n' *

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 ""; }'


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

  • 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 0:28

Not the answer you're looking for? Browse other questions tagged or ask your own question.