How to solve delete file “Operation not permitted” on Linux

Sometimes it is necessary to prevent all users including root from deleting a file. This is often done by changing the file attributes on a Linux file system. The tool used to change file attributes in Linux and other Unix systems is chattr and the tool used to view the newly set attributes is lsattr.

The format of a symbolic mode is +-=[acdeijstuADST]. The format of a symbolic mode is +-=[acdeijstuADST] and they select the new attributes for
the files.

  • The operator ‘+’ causes the selected attributes to be added
    to the existing attributes of the files
  • ‘-’ causes them to be removed
  • ‘=’ causes them to be the only attributes that the files have.

See explanation of all letters used below:

a - append only
c - compressed
d - no  dump
e - extent  format
i -  immutable
j - data journalling
s - secure deletion
t - no tail-merging
u - undeletable
A - no  atime  updates
D - synchronous directory updates
S - synchronous updates
T - top  of  directory  hierarchy

When a directory or a file has immutable attribute set, you will get the error  “Permission denied”  while trying to delete the underlying files. If the attributei (immutable bit) is set on a file, not even root will be able to modify it.

Simulate delete file “Operation not permitted” on Linux

Create a directory under /tmp

mkdir /tmp/testdir

Touch a file in the directory

touch /tmp/testdir/testfile

Set append-only attribute

sudo chattr +a /tmp/testdir/testfile

For a folder and its contents, use -R option for recursive change

sudo chattr -R +a /tmp/testdir/

See file attributes

$ lsattr /tmp/testdir/testfile
-----a---------- testdir/testfile

Try delete the folder

$ rm -f /tmp/testdir/testfile 
rm: cannot remove ‘testfile’: Operation not permitted

Remove append-only attribute

sudo chattr -a /tmp/testdir/testfile

You should now be able to delete the file

rm -f /tmp/testdir/testfile

This works same for the immutable attribute (i).

sudo chattr -i /tmp/testdir/testfile 
rm -f /tmp/testdir/testfile

References
https://computingforgeeks.com/how-to-solve-delete-file-operation-not-permitted-on-linux/