Home > Uncategorized > Shell Script: delete old files and keep latest N files

Shell Script: delete old files and keep latest N files

#!/bin/ksh

#****************************************************************

# SCRIPT: cleanup_BAK.sh

# PARAMETER: ORACLE_SID ($1)

# PURPOSE: cleanup old backup files

# DEPENDENCIES: <None>

#*****************************************************************

BAK_DIR=/oracle/backups/$1

# How many latest BAK files you want to keep

KEEP_HISTORY=3

# Delete the old BAK files

BAK_FILE_COUNT=`ls -ltr $BAK_DIR | grep $1 | grep BAK | wc -l | awk ‘{ print $1 }’ `

if [ $BAK_FILE_COUNT -gt $KEEP_HISTORY ]

then

DELETE_COUNT=`expr $BAK_FILE_COUNT – $KEEP_HISTORY`

echo "`date`: BAK file count : $BAK_FILE_COUNT"

echo "`date`: Delete count : $DELETE_COUNT"

echo

# Delete the old BAK files

for x in `ls -ltr $BAK_DIR | grep $1 | grep BAK | head -$DELETE_COUNT | awk ‘{ print $9 }’ `

do

echo "`date`: Going to delete old BAK file : $BAK_DIR/$x"

rm $BAK_DIR/$x

echo "`date`: File deleted sucessfully"

echo

done

fi

Advertisements
Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

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

%d bloggers like this: