0

I have some folders on an ext4 file system on my Ubuntu machine that I don't want to accidentally delete during normal course of operation as a non-root user. I should be able to move or create or delete folders/files within the folder

(Root should of course be able to do whatever he wants, so this is needed for a non-root user only)

I can perform operations as root if needed to achieve this.

terdon
  • 242,166
Jus12
  • 109

2 Answers2

1

You just need to make sure that your regular user doesn't have write access to the parent directory of the ones you don't want to be able to delete and that your user does have write access to the directories themselves. Like this:

$ tree -pu
.
└── [drwxr-xr-x root    ]  testDir
    └── [drwxrwxrwx user    ]  subDir

As you can see above, the testDir directory belongs to root and only root has write access to it. The testDir/subDir directory belongs to my user, and everyone has full access to it. This means that I can freely create and delete files in there:

$ touch testDir/subDir/file
$ echo "hello World" > testDir/subDir/file2
$ ls -l testDir/subDir/
total 4
-rw-r--r-- 1 terdon terdon  0 May  1 17:56 file
-rw-r--r-- 1 terdon terdon 12 May  1 17:57 file2
$ rm testDir/subDir/file
$ ls -l testDir/subDir/
total 4
-rw-r--r-- 1 terdon terdon 12 May  1 17:57 file2

I cannot, however, delete the directory itself:

$ rm -r testDir/subDir
rm: cannot remove 'testDir/subDir': Permission denied

Not even if it is empty:

$ rm testDir/subDir/*
$ rmdir testDir/subDir/
rmdir: failed to remove 'testDir/subDir/': Permission denied
bey0nd
  • 937
terdon
  • 242,166
1

You can mark the directory append-only with chattr +a <dir> which means new files can be created therein, but not deleted.

LustreOne
  • 1,774