Linux commands – chmod

chmod is used to change permissions on files and directories on a linux system.

An example file listing

ls -l
-rw-r--r-- 1 derek managers    0 Oct 10 19:11 myfile
drwxr-xr-x 2 derek managers 4096 Oct 10 19:11 myfolder
-rw-r--r-- 1 derek managers    0 Oct 10 19:11 myprogram

The permissions are indicated in the first column : d rwx rwx rwx

  • 1st letter – indicate whether it is a directory of a file (d means it is a directory)
  • 2nd-4th letters – indicate owner’s permission (e.g. derek can read/write/execute on myprogram)
  • 5th-7th letters – indicate group’s permission (e.g. managers can read/execute but not write on myprogram)
  • 8th-10th letters – indicate other’s permission (e.g. everyone else can read/execute but not write on myprogram)
  • an “x” on a directory means the folder is searchable

Using chmod

Syntax:

  • chmod who=permissions filename

Who:

  • who : can be one of the letter u,g,o,a
  • u = you (owner)
  • g = group
  • o = others (everyone else)
  • a = all the above (ugo)

Permission:

  • permission : can be one of the letter r,w,x
  • r = read
  • w = write (and delete)
  • x = execute (in case of a directory, means searchable)

Example:

  • chmod u=rx myprogram (let derek read/execute myprogram, but not write)
  • chmod a=rwx myprogram (let everybody to read/write/execute myprogram)
  • chmod go= myprogram (remove all permission for managers and other users)
  • chmod g=rw myfile (let managers read/write myfile, but not execute)

Add/subtract permissions

Syntax

  • chmod who +|- permissions filename

Example:

  • chmod go+w myprogram (group and others get write permission)
  • chmod u-w myfile (owner loss write permission)
  • chmod a+rwx myprogram (everybody get all permissions)

Copy permissions

Syntax:

  • chmod to=from filename

Example:

  • chmod go=u myfile
  • means group (g) and others (o) will get the same permissions as owner (u)

chmod using numbers

look at each group of 3 letters rwx, we can convert them into decimal format:

Permission Decimal
0
x 1
w 2
r 4

Example:

  • All permissions = rwx = 4+2+1 = 7
  • Read/Write only = rw- = 4+2+0 = 6

Another way to explain. We can replace the rwx sytle permission with it’s corresponding decimal value

Permission Binary Decimal Explain
000 0 none
–x 001 1
-w- 010 2
-wx 011 3
r– 100 4 read only
r-x 101 5 read and execute
rw- 110 6 read and write
rwx 111 7 all

Example:

  • chmod 777 myfile (means give rwx permission to owner, group and others)
  • chmod 750 myfile (means give rwx to owner, r-x to group and — to others)