20

This must be really simple to do but have completely drawn a blank. I can see the permission of files by using ls -la which can give something like:

-rwxr-xr-x   1 james  staff   68  8 Feb 13:33 basic.sh*
-rw-r--r--   1 james  staff   68  8 Feb 13:33 otherFile.sh*

How do I translate that into a number for use with chmod like chmod 755 otherFile.sh (with out doing the manual conversion).

AJP
  • 26,547
  • 23
  • 88
  • 127
  • 2
    Just a note that may make your research easier: Mac OS X is BSD UNIX and any UNIX way of solving the problem will also do. (As will many Linux ways.) – Jesper Feb 13 '13 at 13:14

2 Answers2

32

stat -f "%Lp" [filename] works for me in OS X 10.8.

Patrick Lewis
  • 2,131
  • 2
  • 17
  • 16
  • Strange, the man page for `stat` in 10.7 makes it look like those options should work the way they do in 10.8. What error are you getting? – Patrick Lewis Feb 13 '13 at 14:07
  • 1
    Hmmm, that's strange, I thought your answer was something like: `stat -c "%a %w" [filename]` which doesn't work. Your answer does work though. – AJP Feb 13 '13 at 14:40
  • 1
    Note: for linux use: `stat -c '%a' [filename]` – AJP Feb 19 '17 at 14:05
2

You should be able to use the stat command instead of ls. From looking at the manpage, this should work to get the file permissions:

for f in dir/*
do
    perms=$(stat -f '0%Hp%Mp%Lp' $f)
    echo "$f has permissions $perms"
done

(although I am not at my Mac at the moment and therefore cannot test it).

trojanfoe
  • 120,358
  • 21
  • 212
  • 242
  • @AJP, from further study of the manpage, I think you need to specify Hp, Mp and Lp to get all the file permissions. Please see my edit. – trojanfoe Feb 13 '13 at 14:22
  • yes my edit was just to show that i only wanted the `755` part so that I could use it with chmod to change the permissions for read, write and execution. But your answer does give the full permissions. – AJP Feb 13 '13 at 14:46
  • @AJP I don't understand how both answers could be correct. Are you saying that `stat -f '%Hp%Mp%Lp'` **and** `stat -f '%Lp'` give identical results? – trojanfoe Feb 13 '13 at 14:48
  • no they give different results and `stat -f '%Lp'` is what I want. – AJP Feb 13 '13 at 18:16
  • @AJP Hmm, that doesn't seem to meet the requirements of your question as it only returns the user part of the file permissions; the example you show in your question has all (user, group and other) file permissions. – trojanfoe Feb 13 '13 at 18:34
  • I wanted to be able to run `chmod NNN aFile` where NNN is the permissions of a different file. `stat -f '%Lp' differentFile` provided 755 which is exactly what I wanted. – AJP Feb 14 '13 at 13:54
  • @AJP Oh OK; when I tested it (finally) last night `'%Lp'` gave me `005`. – trojanfoe Feb 14 '13 at 13:57