What is a simple standard command line way of getting 'ls' to produce file permission in octal?

1

Any know a standard way, other than 'stat' to produce octal output for file permission from 'ls'? Standard way of using stat (on OSX) is:

stat -f '%A %a %N' *

where * can be any file pattern that you'd normally use with ls.

I'm thinking of creating an ls based alias to use for shorthand.

Is there another/better way to do this?

ashr

Posted 2011-11-21T22:00:18.670

Reputation: 111

Answers

4

Do not create a "ls-based" alias. ls just does not do what you are asking for. This is the job of stat.

If you don't like the stat command, you can call the stat() function directly:

#include <stdio.h>
#include <sys/stat.h>
int main(int argc, char *argv[]) {
    int i;
    struct stat st;
    for (i = 1; i < argc; i++) {
        if (stat(argv[i], &st) < 0)
            perror("stat");
        else
            printf("%06o %s\n", st.st_mode, argv[i]);
    }
    return 0;
}
#!/usr/bin/env perl
printf("%06o %s\n", (stat($_))[2], $_) for @ARGV
#!/usr/bin/env ruby
ARGV.each do |f|
    printf "%06o %s\n", File::stat(f).mode, f
end
#!/usr/bin/env python
import os, sys
for f in sys.argv[1:]:
    sys.stdout.write("%06o %s\n" % (os.stat(f).st_mode, f))
#!/usr/bin/env php
<?php
for ($i = 1; $i < $argc; $i++)
    printf("%06o %s\n", fileperms($argv[$i]), $argv[$i]);
#!/usr/bin/env tclsh
foreach file $argv {
    file stat $file st
    puts [format "%06o %s" $st(mode) $file]
}

user1686

Posted 2011-11-21T22:00:18.670

Reputation: 283 655

Well, that's pretty thorough. I guess I was hoping to find an easy way to reproduce the output of ls -la with only 1 difference: print permissions in octal instead of the rwxr--r-- format. – ashr – 2011-11-22T05:13:32.773

@ashr: Then that's what you should have written in your post. – user1686 – 2011-11-22T07:51:15.857

2

Use stat instead or together with ls. You can change stat output format if you want to look like ls output. For example:

find directory -maxdepth 1 -print0 | xargs -0 stat --format='%a %n'

If you would like to see it exactly as ls output then it should be some script already (awk, perl, etc). It can be defined as a function in your shell or saved as a script in some directory in your PATH and you could use this as a ls command replacement. It depends on your needs how similar to the ls it will be (command line option processing etc)

Cougar

Posted 2011-11-21T22:00:18.670

Reputation: 533