January 30, 2011

Make directory immutable on Linux

Filed under: UNIX & Linux — Tags: , , — martin @ 1:26 pm

Most of you know the immutable flag on Linux filesystems. It marks a given file in a special way that not even root can accidentally delete or modify it:

# touch /tmp/foo
# chattr +i /tmp/foo
# rm /tmp/foo
rm: cannot remove `/tmp/foo': Operation not permitted

Unfortunately it is not possible to apply the same to a directory so it can never be deleted, even when it is empty. At least not, if the directory is supposed to be usable for anything, because immutability means that there can be no files written to it:

# mkdir /tmp/foo
# chattr +i /tmp/foo
# touch /tmp/foo/bar
touch: cannot touch `/tmp/foo/bar': Permission denied

My workaround is to create a hidden file in the directory and make it immutable:

# mkdir /tmp/foo
# touch /tmp/foo/.immutable
# chattr +i /tmp/foo/.immutable
# rm -rf /tmp/foo
rm: cannot remove `/tmp/foo/.immutable': Operation not permitted



  1. you’d have to name it something like .01-immutable wouldn’t you so that it doesn’t start deleting files in that directory, otherwise it might delete all files up to .i* like .bash_history.

    Comment by paulhomebus — January 31, 2011 @ 11:25 am

    • Yeah, that’s my first impulse too. But the purpose is to protect only the directory itself. 🙂

      Comment by martin — January 31, 2011 @ 2:21 pm

    • rm won’t necessarily delete the files sorted by name. They are deleted in the order they are retuned by the file system, which may be arbitrary.

      Comment by feuermurmel — September 22, 2015 @ 4:28 pm

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: