Protect folder from accidental deletion with `rm`
Solution 1:
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.
Solution 2:
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'