Retrieve File Permission In Octal Representation – Shell Scripting
June25
In most of the linux flavors, you will be having a command called ‘stat’
Using the stat command, we can easily retrieve the permission of a file in octal representation
1 | stat -c '%a' filename.txt |
Octal digit | Text equivalent | Binary value | Meaning |
---|---|---|---|
0 | --- | 000 | All types of access are denied |
1 | --x | 001 | Execute access is allowed only |
2 | -w- | 010 | Write access is allowed only |
3 | -wx | 011 | Write and execute access are allowed |
4 | r-- | 100 | Read access is allowed only |
5 | r-x | 101 | Read and execute access are allowed |
6 | rw- | 110 | Read and write access are allowed |
7 | rwx | 111 | Everything is allowed |
we can write a awk function to calculate the permission in octal representation
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | $cat permission.awk function cal(str) { a=0; if(str~/r/) { a+=4; } if(str~/w/) { a+=2; } if(str~/x/) { a+=1; } } { for(i=2;<=length($1);i=i+3) { cal(substr($1,i,3)) octal=octal""a; } print octal } |
1 2 3 4 5 6 7 8 9 10 11 | $ chmod 000 a.txt $ ls -l a.txt | awk -f permission.awk 000 $ chmod 001 a.txt $ ls -l a.txt | awk -f permission.awk 001 $ chmod 031 a.txt $ ls -l a.txt | awk -f permission.awk 031 |
One more function from ctsgnb
1 2 3 4 5 6 7 8 9 10 11 12 13 | #!/bin/bash function conv_perm(){ binary1=`echo "$1" | cut -c4,7,10|tr xstST- 011110` binary2=`echo "$1" | cut -c2-10 | tr rwsxtST- 11111000` octal=`echo "obase=8;ibase=2;${binary1}${binary2}"|bc` echo "$octal" } #Call the function conv_perm "-rwxrwxrwx" conv_perm "-r-x-wx-wx" conv_perm "-r-x--x-w-" |
Recent Comments