Tuesday, August 30, 2011

Unix File Permissions



When ever I discussed some issue related to file access, most people didn't have a clear understanding what it means, when u see file permissions as -rw-r--r--. Or how it is different from drw-r--r-x

As a developer, I always need to know this when I have to look and debug issues on dev/qa/prod servers running on linux. Based on my experience, in this tutorial, I'll clarify the concepts involved.

ls -l
total 160
-rwxrwxrwx   1 ashishsharma3  staff   1040 May  5 13:10 deploy.sh
drwxrwxrwx   5 ashishsharma3  staff    170 May  5 13:04 hcmscripts
-rw-r--r--   1 ashishsharma3  staff  50267 Aug 24 13:11 pom.xml
-rwxrwxrwx   1 ashishsharma3  staff    211 May  5 13:06 realestate-fe-test.recipe


Understanding Position
In say -rw-r--r--, what is at what position

1	directory flag, 'd' if a directory, '-' if a normal file
2,3,4	read, write, execute permission for User (Owner) of file
5,6,7	read, write, execute permission for Group
8,9,10	read, write, execute permission for Other

Understanding values

-	in any position means that flag is not set
r	file is readable by owner, group or other
w	file is writeable. On a directory, write access means you can add or delete files
x	file is executable (only for programs and shell scripts - not useful for data files). Execute permission on a directory means you can list the files in that directory
s	in the place where 'x' would normally go is called the set-UID or set-groupID flag.

For a directory, the set-groupID flag means that all files & subdirectories created inside that directory will inherit the group of the directory. 
Otherwise, a file takes on the primary group of the user creating the file. 

Octal Text Binary 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

Easiest way to remember - It is always in order rwx

r = 100 = 4
w = 010 = 2
x = 001 = 1

Triplet for u: rwx => 4 + 2 + 1 = 7
Triplet for g: r-x => 4 + 0 + 1 = 5
Tripler for o: r-x => 4 + 0 + 1 = 5
Which makes -rwxr-xr-x: 755

chmod [options] mode file(s)

chmod -R 777 mydir

-R = recursive, affects the subdirectories and files as well.

chmod 100 myfile

chmod g+rwxs mydir
give full group read/write access to directory "mydir", also setting the set-groupID flag so that directories created inside it inherit the group 


chmod g-rw myfile
remove read and write access to "myfile", leaving all other permission flags alone 

chmod -R g+rw .
give group read write access to this directory, and everything inside of it (-R = recursive) 



1 comment: