Skip to content

Instantly share code, notes, and snippets.

@horner
Last active October 28, 2021 03:55
Show Gist options
  • Save horner/3bf5c104c95854b857e16334e8db52a3 to your computer and use it in GitHub Desktop.
Save horner/3bf5c104c95854b857e16334e8db52a3 to your computer and use it in GitHub Desktop.
Making log files append-able but not overwrite-able

Make a log file the usual way.

# echo `date` this is a log entry >> sample.log
# echo `date` this is a log entry >> sample.log
# echo `date` this is a log entry >> sample.log

See the output:

# cat sample.log
Wed 27 Oct 2021 09:34:15 PM EDT this is a log entry
Wed 27 Oct 2021 09:34:17 PM EDT this is a log entry
Wed 27 Oct 2021 09:34:19 PM EDT this is a log entry
# > sample.log
# cat sample.log

Log file is gone! That's not cool. So use chattr to block it!

# chattr +a sample.log

Remake the log:

# echo `date` this is a log entry >> sample.log

But now you cannot get rid of it!

# > sample.log
bash: sample.log: Operation not permitted
# rm sample.log
rm: cannot remove 'sample.log': Operation not permitted
# mv sample.log /tmp
mv: cannot move 'sample.log' to '/tmp/sample.log': Operation not permitted
# chmod a+rw sample.log
chmod: changing permissions of 'sample.log': Operation not permitted

But you can append

# echo `date` this is a log entry >> sample.log
# echo `date` this is a log entry >> sample.log
# cat sample.log
Wed 27 Oct 2021 09:36:54 PM EDT this is a log entry
Wed 27 Oct 2021 09:36:55 PM EDT this is a log entry
Wed 27 Oct 2021 09:36:56 PM EDT this is a log entry

If you need to clobber, then either unset (only root) or

Only the superuser or a process possessing the CAP_LINUX_IMMUTABLE capability can set or clear this attribute.

# chattr -a sample.log
# > sample.log
# cat sample.log

Adapted from Severfault

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment