4

I have some folder ~/foo which I'd like to protect from accidental deletion, that is I'd like to protect it from deleting with rm -r ~/foo or rmdir ~/foo.

I realized you can do that using chmod a-w ~/foo or chattr -i ~/foo but this has the drawback that you cannot change anything inside that folder. I however would still like to be able to create/move/delete files and folders inside ~/foo.

Is it somehow possible to do so?

flawr
  • 369
  • 4
  • 17
  • Why don't maintain a backup of the folder in question, so you can easily restore after accidental deletion? – mook765 May 28 '21 at 10:07
  • @mook765 I do have a backup, but if I can prevent deleting it in the first place it would save me a little bit of hassle. It is not really a problem but I just did it twice in a row (d'oh:). – flawr May 28 '21 at 11:05

2 Answers2

8

Create a hidden file inside the folder and do (.foo as an example) as "root":

touch ~/foo/.foo
chattr +i ~/foo/.foo

You can now delete all files except .foo in this directory, and the directory can not be deleted by another user. You can still move the directory though and you can stop that with the sticky bit...

sudo chmod +t ~/foo

And that should cover your problem. BUT I do agree: making a backup is always the better option. A somewhat more difficult option: put a directory watcher on ~/foo and create a timestamped backup of every file touched and before it is altered in a directory users can not reach would be a safer method.

Rinzwind
  • 299,756
5

I would suggest adding the following "safetynets" to your .bashrc (or config file for another shell) to prevent the most obvious mistakes.

Ask for confirmation before removing 3 or more files, or any directory recursively. Also prevents removal of / recursively: (the -I parameter is less intrusive than -i which prompts on every file, but still prevents most mistakes by a single confirmation prompt)

alias rm='rm -I --preserve-root'

Prevent changing permissions and ownership on / recursively: (not your question, but still a nice safety feature to include)

alias chmod='chmod --preserve-root'
alias chown='chown --preserve-root'
alias chgrp='chgrp --preserve-root'
Artur Meinild
  • 26,018