How to prevent users from deleting a directory?

I tried “chattr +i DIRNAME”, it’s great, but I cannot create files in the DIR after chattr. What else are there to prevent users from deleting a Directory?

root@HOST ~] mkdir test
[root@HOST ~] chattr +i test
[root@HOST ~] cd test
[root@HOST ~/test] touch sth
touch: cannot touch `sth': Permission denied
[root@HOST ~/test] cd ..
[root@HOST ~] chattr -i test
[root@HOST ~] cd test
[root@HOST ~/test] touch sth
[root@HOST ~/test] 

UPDATE: only the directory deletion is important, so I still need the files to be deleted in it

Asked By: gasko peter

chattr +a

should do the job. You can create files inside but you won’t be able to delete them.

Answered By: Laurentiu Roescu

So what is wrong with a simple chown/chmod?:

cd /tmp
mkdir question
sudo chown root:root question
[sudo] password for user: 
chmod 777 ./question
touch sth
rm sth
cd ..
rm question -rf
rm: cannot remove `question': Operation not permitted

OK, let me tell you what is wrong with this: every user has all access to every file in the question directory due to the 777 permissions. It is better to

  • create a new group groupadd question
  • mkdir question
  • chown root:question ./question
  • chmod 770 ./question
  • add the users that must have access to the files to the new group: usermod -G group user

The important trick here is that the directory has a different owner than any of the users that will try to delete it.

Answered By: jippie

Create a file “.protected” and do as root

chattr +i .protected

You can then delete all files except .protected within this directory,
thus the directory can’t be deleted by any other user.

Answered By: Magnus
Categories: Answers Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.