Convert UNIX rights in a number in a sh script

Hello,

i'm trying to write a script sh to convert the rights of a folder or file in a number.
Explain:

ls -l = rwxrwxrwx

so i must display 777.

Do you known where i can find so convert script

Thanks

What have you tried so far?

Hello,

thanks . I tried the command stat -c "%a %n" but it didn't work.

So i'm checking

Thanks

hi

firstly what is your system ? (if unix ? - > which platform or linux ?)
this info required for more help :slight_smile:

if your linux variants maybe try

ls -l |awk 'NR>1{j=10;for(i=1;i<=10;i++){j--;if(substr($1,i,1)~"[rwx]")o+=2^j;};printf "%o",o;o=0;$1="";}1' OFS='\t'

if your system is unix which platform and which shell ?

regards,
ygemici

Hello,

thanks for your feedback.

I'm working on Unix on AIX on an sh script.

Thanks

chek this maybe its helpful for u.:slight_smile:

http://www.unix.com/shell-programming-and-scripting/169068-aix-hp-ux-equivalent-linux-stat-command.html

regards
ygemici

Hello,

the istat command didn't work the result is the same rwx.......

Also the Solaris script didn't work on my AIX sh script (with changes to AIX)

Thanks

did you try my code (awk) ? or

perl code from specified url.

perl -le'printf "%o", 07777 & (stat)[2] for @ARGV' <file>

Try also

ls -l file | awk '{split ($1, X, ""); for (i=2; i<=10; i++) PERM+=2^(10-i)*(X=="-"?0:1) ; printf "%o\n", PERM}'
644

So you can get the textual value from ls -l so could you do the following:-

  • Trim off the first character and dispose (object type flag, e.g. pipe, directory, link, file etc)
  • For each of the nine remaining characters, look at the character and see if it is a hyphen - . Replace it with a zero if it is or a one if it is not.
  • You have a nine digit binary number so take each set of three digits and convert the number from binary to octal (or even decimal as it happens)

Would that logic help?

Is this what RudiC has suggested? I can't quite decipher it.

Kind regards,
Robin

Yes. See here:

ls -l file | 
awk     '{split ($1, X, "")             # split the mode in $1 into single chars
          for (i=2; i<=10; i++)         # run across 9 chars starting from 2
                 PERM+=2^(10-i)*        # sum binary weight of position times
                        (X=="-"?0:1) # 0 if char is a dash else 1
          printf "%o\n", PERM}'         # print octal value
1 Like

You could try something like this is bash/ksh

mode="-rwxr-x---"
v=${mode#?}
v=${v//-/0}
v=${v//[rwx]/1}
printf "%03o\n" $((2#$v))

Output:

750

Have you considered special file permissions (sticky bit, suid and sgid)? Perhaps you will need somthing like this:

#!/bin/sh
mode="-rwsr-x--x"
spec=$(echo $mode | sed 's/^...\(.\)..\(.\)..\(.\)/\1\2\3/')
spec=${spec//[x-]/0}
spec=${spec//[sStT]/1}
v=${mode#?}
v=${v//[-ST]/0}
v=${v//[rwxst]/1}
if [ $spec -gt 0 ]
then
   printf "%o%03o\n" $((2#$spec)) $((2#$v))
else
    printf "%03o\n" $((2#$v))
fi

output:

4751
1 Like