Simple Bash log backup script I have developed the following script to zip and then remove all files with "*.log" extension in the file name that were modified yesterday. It's definitely not 100% at the moment. For example, it misses files from yesterday that have a modified time of 00:00.

#!/bin/bash

yest=$(date --date="yesterday" +"%m_%d_%Y")

find /path/to/dir/ -daystart -name "*.log" -type f -mtime 1 -print | zip /path/to/dir/"logbackup-$yest.zip" -@
if [ $? -eq 0 ]; then
    find /path/to/dir/ -daystart -name "*.log" -type f -mtime 1 -exec rm -f {} \;
fi


It seems that using -daystart OR using mtime exclusively are not returning the correct results for me. Only files "c" and "a" should be returned.




[user@computer log]$ ls -lart
drwxr-xr-x 23 user user     4096 Sep  5 22:27 ..
-rw-rw-r--  1 user user        0 Nov 18 14:00 d
-rw-rw-r--  1 user user        0 Nov 19 00:00 c
-rw-rw-r--  1 user user        0 Nov 19 12:30 a
-rw-rw-r--  1 user user        0 Nov 20 12:30 b
drwxr-xr-x  2 user user    16384 Nov 20 12:32 .
[user@computer log]$ find . -mtime 1 -type f | xargs ls -lart
-rw-rw-r-- 1 user user 0 Nov 18 14:00 ./d
-rw-rw-r-- 1 user user 0 Nov 19 00:00 ./c
-rw-rw-r-- 1 user user 0 Nov 19 12:30 ./a
[user@computer log]$ find . -daystart -mtime 1 -type f | xargs ls -lart
-rw-rw-r-- 1 user user 0 Nov 19 12:30 ./a
Put /path/to/dir/ in a variable to avoid writing it repeatedly.

Instead of running the command and checking $? after,
you can put the command inside an if.

The script would become shorter, for example:

path=/path/to/dir

if find $path -daystart -type f -mtime 1 -name "*.log" -print | zip $path/"logbackup-$yest.zip" -@
then
    find $path -daystart -type f -mtime 1 -name "*.log" -exec rm -f {} \;
fi


In my tests, it seems that simply dropping -daystart will have the desired effect of matching the right files. For example:

touch -d yesterday a
touch -d '2014-11-19 00:00:00' b
touch -d '2014-11-18 00:00:00' c
touch -d '2 days ago' d
ls -l


Gives:


-rw-r--r-- 1 janos users 0 Nov 19 12:35 a
-rw-r--r-- 1 janos users 0 Nov 19 00:00 b
-rw-r--r-- 1 janos users 0 Nov 18 00:00 c
-rw-r--r-- 1 janos users 0 Nov 18 12:38 d



And then:


$ find . -daystart -mtime 1 -type f
./a
$ find . -mtime 1 -type f
./a
./b