I've already found a mistake, the MAX_BYTES calculation is wrong by 1000. But even with that change the script still operates even if the file has just 1000 bytes.

I also found another neat command which is part of the moreutils package: sponge. It keeps the inode.
Code: Select all
~/bin$ ls -i test.log
3014673 test.log
~/bin$ tail -n 1000 test.log | sponge test.log
~/bin$ ls -i test.log
3014673 test.log
ls -i test.log
3014673 test.log
~/bin$ sed -e :a -e '$q;N;1000,$D;ba' test.log | sponge test.log
~/bin$ ls -i test.log
3014673 test.log
Code: Select all
#!/bin/bash
# Backup .xsession-errors if larger than n MB (MAX_MB)
# Leave last n lines in original (LEAVE_LINES: set to 0 to skip backup)
# Check every n minutes (INTERVAL_MIN)
MAX_MB=1
LEAVE_LINES=10000
INTERVAL_MIN=5
# LOG='test.log'
LOG='/var/home/.xsession-errors'
# LOG='$HOME/.xsession-errors'
while true; do
LOG_BYTES=$(stat --printf=%s "$LOG")
MAX_BYTES=$((MAX_MB*1000000))
if (( $LOG_BYTES > $MAX_BYTES )); then
tail -n $LEAVE_LINES "$LOG" | sponge "$LOG"
fi
sleep $((INTERVAL_MIN*60))
done