Keep Six months worth of data

I often have things that back themselves up often, or syslogs that roll over daily. Sometimes I want to keep six months worth of data. Here are two scripts to accomplish that.. one for Windows and one for bash:

In bash, I define my glob (wildcard list of files) that I want to only save 180 days worth of stuff. In this case, the FortiAuthenticator backup files, which the device pushes to the backup server via sftp every day. You could customize it for anything though, just by changing the “glob” environment variable.

#!/bin/bash

files_to_save=180
glob=FortiAuthenticator*

num_of_files=`ls -1 $glob | wc -l`

if [ $num_of_files -le $files_to_save ]; then
 exit
else
 count=$(($num_of_files-$files_to_save))
 for i in `ls -1t $glob | tail -$count`; do
  rm -f $i
 done
fi

It's a little trickier in Windows, because you don't have the tail command that UNIX derivatives supply, so you have to be creative with the best command available for batch files: the for command. I usually cheat and use the GNU UNIX tools (like head, tail, grep, awk, sed, etc), but I can’t count on having those on somebody else’s computer. Someday I’ll sit down and learn PowerShell, but until then, I have to lean on my batch-file crutch...
@echo off

set files_to_save=180
for /f "tokens=1,2 delims=:" %%a in ('dir/a-d/b/o-d ^| findstr /n ".*"') do if %%a GTR %files_to_save% del "%%b"
 

No comments:

Post a Comment

Previous working directory in Windows Command Prompt

Using bash in *nix has a handy feature: If you are in one directory and you switch to another one, you can use   cd -  to go back to the pr...