Convert file permissions from character to octal.

Found this great script today which was very useful to identify the permissions of files copied from another server in octal so I could apply them easily using chmod.

Copied here for easy access…

#!/bin/ksh 
# char2oct-perms 
# Returns the octal permissions of the given file. 
if [ $# -ne 1 -o ! -r "$1" ]; then 
    print "Usage: char2oct-perms filename" >&2 
    exit 1 
fi 
typeset -i OCTAL=0 STICKY=0 
set -- $(ls -dl $1) 
SYM_PERM=$1 
for I in 2 3 4 5 6 7 8 9 10; do 
    P=$(echo $SYM_PERM | cut -c$I) 
    case $I in 2|5|8) OCTAL=0 ;; esac 
    case $P in 
        x) OCTAL=$((OCTAL+1)) ;; # execute 
        w) OCTAL=$((OCTAL+2)) ;; # write 
        r) OCTAL=$((OCTAL+4)) ;; # read 
        s|S) case $P in s) 
                OCTAL=$((OCTAL+1)) ;; # execute 
             esac 
             case $I in 
                  4) STICKY=$((STICKY+4)) ;; # set-uid 
                  7) STICKY=$((STICKY+2)) ;; # set-gid 
             esac ;; 
        t) STICKY=$((STICKY+1)) # sticky 
           OCTAL=$((OCTAL+1)) ;; # execute 
        T) STICKY=$((STICKY+1)) ;; # sticky 
    esac 
    case $I in 4|7|10) OCT_PERM="$OCT_PERM$OCTAL" ;; esac 
done 
echo $STICKY$OCT_PERM 
exit 0

From here thanks to GROG.

About

I'm a freelance UNIX engineer working in the UK. I'm married to Tina and between us we have six children. I'm a bit of an Apple fan boy, and all the Windows machines in the house are a thing of the past now.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: