Wednesday, September 20, 2006

Changing file permissions in UNIX or Linux

Command: chmod

This guide assumes that you already know a thing or two about UNIX and or Linux and basic computing.


  1. The first thing you need to do is determine what permissions the file currently has assigned to it.
    e.g...
    $ ls -l
    total 4
    -rwxr-xr-x 2 owner group size date time filename
    $

    From this, you can determine that you are dealing with an ordinary file (-). The permissions are divided into 3 groups: Owner, Group, Other. So in this case the Owner has Read, Write and Execute permissions. The Group has Read and Execute and the Other has Read and Execute.
  2. The next thing to do is determine what permissions you want the file to have. Let's say we want the Owner to have Read and Write permissions and Group and Other should only have Read permissions.

    That means we want it to look like this:
    -rw-r--r-- 2 owner group size date time filename
  3. The command used to change permissions is "chmod". Here's some sample syntax:

    $ chmod a+rwx filename

    This means we want to add Read, Right and Execute permissions to "All" (All refers to Owner, Group and Other). a=all, g=group, u=owner, o=other, +=add permissions, -= remove permissions. Also for permissions r=read, w=write, x=execute. There are also many files types: -=ordinary, d=directory, p=pipe, etc. Here's another example...

    $ chmod g=rw filename

    This example removes Read and Write permissions on the file. Try some for yourself.
  4. There is an easier way to do this. It involves converting the permissions to a binary format and then to a numeric format. To understand more about binary, check out wikipedia.org.

    Consider these permissions: -rwxr--r--
    Broken down: The first character is a (-) which indicates that it is an ordinary file. We will skip that part for now and focus on the remaining 9 characters (rwxr--r--). Now taking the remaining 9 charcters we can assume that if it has a number it gets a 1 and if it has a (-) then it gets a zero. This is how we translate the rwx values to binary:

    rwx r-- r-- (Break the characters up into three groups)
    111 100 100 (Assign a 1 or a 0)
  5. So now you've got the binary values and need to translate that to numeric. So you simply replace the binary values with their numeric equivalents

    111 100 100
    7 4 4
  6. Now the syntax works like this. You can assign the exact permissions for each type with one 3 digit numeric value. Let's say we want to assign rxw for Owner, r only for Group and r only for other. How can we do that only using numeric values?

    $ chmod 744 filename
  7. And that's pretty much it. Try it yourself to see.

No comments: