Sticky bit

There may be situation where you wanted all users to store files in a certain folder but might want to restrict users from deleting other users file. For this scenario, you can set the sticky bit of the folder which will serve our purpose.

For example we have created a folder inside /tmp directory called “user”

root@dev:/tmp# ls -l | tail -1
drwxr-xrwx 2 root root 4096 2009-07-13 11:39 user
root@dev:/tmp# cd user

Now create a file called a.txt (you are currently with root privileges)
root@dev:/tmp/user# touch a.txt

Now change to the user with normal privileges (i have created a user called ‘usr100’ for this purpose)
usr100@dev:/tmp/user$ su usr100
password:
usr100@dev:/tmp/user$ whoami
usr100

usr100@dev:/tmp/user# touch b.txt
usr100@dev:/tmp/user$ ls -ltr

total 4
-rw-r–r– 1 root root 0 2009-07-13 11:42 a.txt
-rw-r–r– 1 usr100 usr100 0 2009-07-13 11:42 b.txt
usr100@dev:/tmp/user$ rm -i a.txt

usr100@dev:/tmp/user$ ls -ltr
total 4
-rw-r–r– 1 usr100 usr100 0 2009-07-13 11:42 b.txt

The file created by root user got deleted by usr100.

In order to prevent this, set the sticky bit for the folder ‘user’

usr100@dev:/tmp/user$ su root
root@dev:/tmp# chmod +t user
root@dev:/tmp# cd usr
root@dev:/tmp/usr# touch a.txt
root@dev:/tmp/usr# su usr100

usr100@dev:/tmp$ ls -ltr | tail -1
drwxr-xrwt 2 root root 4096 2009-07-13 12:07 user

Notice “t” at the end of the permission settings which denote that the folder /user has been set with the sticky bit.

usr100@dev:/tmp/user$ ls -ltr
total 0
-rw-r–r– 1 usr100 usr100 0 2009-07-13 11:42 c.txt
-rw-r–r– 1 root root 0 2009-07-13 12:07 a.txt

Now try deleting the file a.txt created by root user
usr100@dev:/tmp/user$ rm -i a.txt
rm: remove write-protected regular empty file `a.txt’? y
rm: cannot remove `a.txt’: Operation not permitted

As the sticky bit is set for the folder ‘user’, usr100 is prevented from deleting the file created by ‘root’ user