When you want to delete file/folder having immutable flag set, you will encounter with an error:
rm: cannot remove ‘file-name’: Operation not permitted.
Making file write protected in Linux
Syntax:
To set this flag on files you can use the following command:
chattr +i filename
To unset or remove the attribute you can use the following command:
chattr -i filename
To set this flag on directories only you need to specify the directory name:
chattr +i directory name
chattr -i directory name
How to search files having immutable flag set?
To accomplish this we use lsattr command pipe with the grep command.
lsattr -R | grep +i
Example:
Creating file having name san.txt and setting flag on it.
[oracle@orahow ~]$ vi san.txt
Initially check the file permission:
[oracle@orahow ~]$ ls -l san.txt
-rw-r–r– 1 oracle dba 19 Nov 18 05:56 san.txt
[oracle@orahow ~]$ chattr +i san.txt
chattr: Operation not permitted while setting flags on san.txt
To set this flag you need to login as a root user:
[root@orahow oracle]# chattr +i san.txt
[root@orahow oracle]# lsattr san.txt
----i-------- san.txt
Now try to delete the file having immutable flag set:
[root@orahow oracle]# rm san.txt
rm: remove write-protected regular file `san.txt'? y
rm: cannot remove `san.txt': Operation not permitted
To remove this file you need to unset this flag:
[root@orahow oracle]# chattr -i san.txt
[root@orahow oracle]# lsattr san.txt
------------- san.txt
[root@orahow oracle]# rm san.txt
rm: remove regular file `san.txt’? y
[root@orahow oracle]# cat san.txt
cat: san.txt: No such file or directory
Making a directory write protected in Linux:
[root@orahow oracle]# mkdir san
[root@orahow oracle]# ls -ldr san
drwxr-xr-x 2 root root 4096 Nov 18 07:36 san
[root@orahow oracle]# chattr +i san
Now if you try to remove the directory it will throw a message: operation not permitted. Before deleting this folder you need to unset this flag.
[root@orahow oracle]# rmdir san
rmdir: san: Operation not permitted
[root@orahow oracle]# chattr -i san
[root@orahow oracle]# rmdir san
[root@orahow oracle]# ls -ldr san
ls: san: No such file or directory