Shell Script to Generate Daily/Weekly AWR reports (Email)

Posted by Sagar Patil

Create  .run_awr with following details  :

"TNS-connect-string : recipient-list : hrs of AWR snapshot"
[oracle@ ~]$ cat .run_awr
prod:root@oracledbasupport.co.uk:11
I added this script in my crontab for a daily emails:
########## Daily Export of AWR reports
02 18 * * * /home/oracle/.awr_daily.sh  >> /home/oracle/awr.log 2>&1
[oracle@awr_reports]$ ls -lrt
-rw-r--r-- 1 oracle oracle 315104 Oct 26 10:02 AWR_26102010_1002_prod.HTML
-rw-r--r-- 1 oracle oracle 343839 Oct 26 18:02 AWR_26102010_1802_prod.HTML
-rw-r--r-- 1 oracle oracle 342611 Oct 27 18:02 AWR_27102010_1802_prod.HTML
-rw-r--r-- 1 oracle oracle 282057 Oct 28 18:02 AWR_28102010_1802_prod.HTML
  1. Create AWR report between sysdate  and sysdate – hours (download)

#       The file “.run_awr” in the “$HOME” directory contains one or more
#       lines with the following format, three fields delimited by “semicolon”:
#
#               TNS-connect-string : recipient-list : hrs

    2.Create AWR report between sysdate-days  and sysdate – hours  (download)

#       The file “.run_awr” in the “$HOME” directory contains one or more
#       lines with the following format, three fields delimited by “semicolon”:
#
#               TNS-connect-string : recipient-list : daysInPast : hrs

#!/usr/bin/ksh

 #==============================================================================
# File:         run_awr.sh
# Type:         korn shell script
#
# Description:
#       UNIX Korn-shell script to run under the UNIX "cron" utility to
#       automatically generate and email Oracle "AWR" reports in HTML against
#       the database accessed via the specified TNS connect-string, to a
#       specified list of email addresses.
#
# Parameters:
#       Zero, one, or more parameters may be passed.  These parameters
#       are TNS connect-strings, each of which refer to entries in the
#       script's configuration file (named ".run_awr", described below).
#
#       If no parameters are specified, then the script processes all of
#       the lines in the configuration file.
#
#       For each of the parameters specified, the script will process
#       each of the corresponding lines in the configuration file.
#
#       Each TNS connect-string should be separated by whitespace.
#
# Configuration file:
#       The file ".run_awr" in the "$HOME" directory contains one or more
#       lines with the following format, three fields delimited by "commas":
#
#               TNS-connect-string : recipient-list : hrs
#
#       where:
#
#               TNS-connect-string      Oracle TNS connect-string for the db
#               recipient-list          comma-separated list of email addresses
#               hrs                     "sysdate - <hrs>" is the beginning
#                                       time of the AWR report and "sysdate"
#                                       is the ending time of the AWR report
#
# Modification history:
#==============================================================================
#
#------------------------------------------------------------------------------
# Set up Oracle environment variables...
#------------------------------------------------------------------------------
export ORACLE_SID=prod
export ORAENV_ASK=NO
. /usr/local/bin/oraenv > /dev/null 2>&1
unset ORAENV_ASK
#
#------------------------------------------------------------------------------
# Verify that the Oracle environment variables and directories are set up...
#------------------------------------------------------------------------------
if [[ "${ORACLE_HOME}" = "" ]]
then
 echo "ORACLE_HOME not set; aborting..."
 exit 1
fi
if [ ! -d ${ORACLE_HOME} ]
then
 echo "Directory \"${ORACLE_HOME}\" not found; aborting..."
 exit 1
fi
if [ ! -d ${ORACLE_HOME}/bin ]
then
 echo "Directory \"${ORACLE_HOME}/bin\" not found; aborting..."
 exit 1
fi
if [ ! -x ${ORACLE_HOME}/bin/sqlplus ]
then
 echo "Executable \"${ORACLE_HOME}/bin/sqlplus\" not found; aborting..."
 exit 1
fi
if [ ! -x ${ORACLE_HOME}/bin/tnsping ]
then
 echo "Executable \"${ORACLE_HOME}/bin/tnsping\" not found; aborting..."
 exit 1
fi
#
#------------------------------------------------------------------------------
# Set shell variables used by the shell script...
#------------------------------------------------------------------------------
_Pgm=AWR_`date '+%d%m%Y_%H%M'`
_RunAwrListFile=${HOME}/.run_awr
if [ ! -r ${_RunAwrListFile} ]
then
 echo "Script configuration file \"${_RunAwrListFile}\" not found;
aborting..."
 exit 1
fi
#
#------------------------------------------------------------------------------
# ...loop through the list of database instances specified in the ".run_awr"
# list file...
#
# Entries in this file have the format:
#
#       dbname:rcpt-list:hrs
#
# where:
#       dbname          - is the TNS connect-string of the database instance
#       rcpt-list       - is a comma-separated list of email addresses
#       hrs             - is the number of hours (from the present time)
#                         marking the starting point of the AWR report
#------------------------------------------------------------------------------
grep -v "^#" ${_RunAwrListFile} | awk -F: '{print $1" "$2" "$3}' | \
while read _ListDb _ListRcpts _ListHrs
do
 #----------------------------------------------------------------------
 # If command-line parameters were specified for this script, then they
 # must be a list of databases...
 #----------------------------------------------------------------------
 if (( $# > 0 ))
 then
 #
 #---------------------------------------------------------------
 # If a list of databases was specified on the command-line of
 # this script, then find that database's entry in the ".run_awr"
 # configuration file and retrieve the list of email recipients
 # as well as the #-hrs for the AWR report...
 #---------------------------------------------------------------
 _Db=""
 _Rcpts=""
 _Hrs=""
 for _SpecifiedDb in $*
 do
 #
 if [[ "${_ListDb}" = "${_SpecifiedDb}" ]]
 then
 _Db=${_ListDb}
 _Rcpts=${_ListRcpts}
 _Hrs=${_ListHrs}
 fi
 #
 done
 #
 #---------------------------------------------------------------
 # if the listed DB is not specified on the command-line, then
 # go onto the next listed DB...
 #---------------------------------------------------------------
 if [[ "${_Db}" = "" ]]
 then
 continue
 fi
 #---------------------------------------------------------------
 else    # ...else, if no command-line parameters were specified, then
 # just use the information in the ".run_awr" configuration file...
 #---------------------------------------------------------------
 _Db=${_ListDb}
 _Rcpts=${_ListRcpts}
 _Hrs=${_ListHrs}
 #
 fi
 #
 #----------------------------------------------------------------------
 # Verify that the name of the database is a valid TNS connect-string...
 #----------------------------------------------------------------------
 ${ORACLE_HOME}/bin/tnsping ${_Db} > /dev/null 2>&1
 if (( $? != 0 ))
 then
 echo "\"tnsping ${_Db}\" failed; aborting..."
 exit 1
 fi
 #
 #----------------------------------------------------------------------
 # Create script variables for the output files...
 #----------------------------------------------------------------------
 _TmpSpoolFile="/home/oracle/awr_reports/${_Pgm}_${_Db}.HTML"
 _AwrReportFile="${_Pgm}_${_Db}.html"
 #
 #----------------------------------------------------------------------
 # Call SQL*Plus, retrieve some database instance information, and then
 # call the AWR report as specified...
 #----------------------------------------------------------------------
 ${ORACLE_HOME}/bin/sqlplus -s /nolog << __EOF__ > /dev/null 2>&1
set echo off feedback off timing off pagesize 0 linesize 300 trimspool on
verify off heading off
connect / as sysdba

col dbid new_value V_DBID noprint
select  dbid from v\$database;

col instance_number new_value V_INST noprint
select  instance_number from v\$instance;

col snap_id new_value V_BID
select  min(snap_id) snap_id
from    dba_hist_snapshot
where   end_interval_time >= (sysdate-(${_Hrs}/24))
and     startup_time <= begin_interval_time
and     dbid = &&V_DBID
and     instance_number = &&V_INST;

col snap_id new_value V_EID
select  max(snap_id) snap_id
from    dba_hist_snapshot
where   dbid = &&V_DBID
and     instance_number = &&V_INST;

spool ${_TmpSpoolFile}
select  'BEGIN='||trim(to_char(begin_interval_time, 'HH24:MI')) snap_time
from    dba_hist_snapshot
where   dbid = &&V_DBID
and     instance_number = &&V_INST
and     snap_id = &&V_BID ;
select  'END='||trim(to_char(end_interval_time, 'HH24:MI')) snap_time
from    dba_hist_snapshot
where   dbid = &&V_DBID
and     instance_number = &&V_INST
and     snap_id = &&V_EID ;
spool off

select output from table(dbms_workload_repository.awr_report_html(&&V_DBID,
&&V_INST, &&V_BID, &&V_EID, 0))

spool /tmp/${_AwrReportFile}
/
exit success
__EOF__
 #
 #----------------------------------------------------------------------
 # Determine if the "start time" and "end time" of the AWR report was
 # spooled out...
 #----------------------------------------------------------------------
 if [ -f ${_TmpSpoolFile} ]
 then
 _BTstamp=`grep '^BEGIN=' ${_TmpSpoolFile} | awk -F= '{print
$2}'`
 _ETstamp=`grep '^END=' ${_TmpSpoolFile} | awk -F= '{print $2}'`
 fi
 #
 #----------------------------------------------------------------------
 # Determine if an AWR report was spooled out...
 #----------------------------------------------------------------------
#                if [ -f /tmp/${_AwrReportFile} ]
#                then
#
#                        uuencode /tmp/${_AwrReportFile} ${_AwrReportFile} | \
#                                mailx -s "AWR Report for ${_Db}
#        (${_BTstamp}-${_ETstamp} GMT)" ${_Rcpts}
#
#                fi
#
mv /tmp/${_AwrReportFile} ${_TmpSpoolFile}
done
#
#------------------------------------------------------------------------------
# Finish up...
#------------------------------------------------------------------------------
exit 0

Compare and Display difference between 2 Files

Posted by Sagar Patil

Comparing Files is one of very common task as a DBA, System Administrator. There are tonnes of Oracle,Websphere,linux configuration files. Often I have to compare one server to another and locate changes between environments.

Recently one of my websphere server broke down. Despite my good efforts I couldn’t revive it so I had to restore it from a backup.  Then came the task to compare the websphere confiuration between good and bad. When I looked at $WAS_HOME/bin/backupconfig , it backed up more than 400 files and carrying one to one comparison is no way possible.  I used following script to locate the difference.

#!/usr/bin/perl
# file_compare.pl
# Purpose: compare two files and show differences
# usage: file_compare.pl filename1 filename2

use strict;
use warnings;

my $file1 = shift or die “filename missing \n”;
my $file2 = shift or die “filename missing \n”;

open (FILE1, “< $file1”) or die “Can not read file $file1: $! \n”;
my @file1_contents = <FILE1>; # read entire contents of file
close (FILE1);

open (FILE2, “< $file2”) or die “Can not read file $file2: $! \n”;
my @file2_contents = <FILE2>; # read entire contents of file
close (FILE2);

my $length1 = $#file1_contents; # number of lines in first file
my $length2 = $#file2_contents; # number of lines in second file

if ($length1 > $length2) {
# first file contains more lines than second file
my $counter2 = 0;
foreach my $line_file1 (@file1_contents) {
chomp ($line_file1);

if (defined ($file2_contents[$counter2])) {
# line exists in second file
chomp (my $line_file2 = $file2_contents[$counter2]);

if ($line_file1 ne $line_file2) {
print “\nline ” . ($counter2 + 1) . ” \n”;
print “< $line_file1 \n” if ($line_file1 ne “”);
print “— \n”;
print “> $line_file2 \n\n” if ($line_file2 ne “”);
}
}
else {
# there is no line in second file
print “\nline ” . ($counter2 + 1) . ” \n”;
print “< $line_file1 \n” if ($line_file1 ne “”);
print “— \n”;
print “> \n”; # this line does not exist in file2
}
$counter2++; # point to the next line in file2
}
}
else {
# second file contains more lines than first file
# or both have equal number of lines
my $counter1 = 0;
foreach my $line_file2 (@file2_contents) {
chomp ($line_file2);

if (defined ($file1_contents[$counter1])) {
# line exists in first file
chomp (my $line_file1 = $file1_contents[$counter1]);

if ($line_file1 ne $line_file2) {
print “\nline ” . ($counter1 + 1) . ” \n”;
print “< $line_file1 \n” if ($line_file1 ne “”);
print “— \n”;
print “> $line_file2 \n” if ($line_file2 ne “”);
}
}
else {
# there is no line in first file
print “\nline ” . ($counter1 + 1) . ” \n”;
print “< \n”; # this line does not exist in file1
print “— \n”;
print “> $line_file2 \n” if ($line_file2 ne “”);
}
$counter1++; # point to next line in file1
}
}

Output

$perl compare_files.pl notworking.lst working.lst  | more

line 1
< 4     notworking/Cell/pmirm.xml

> 4     working/Cell/pmirm.xml
line 2
< 4     notworking/Cell/resources-pme.xml

> 4     working/Cell/resources-pme.xml
line 3
< 32    notworking/Cell/resources.xml

> 32    working/Cell/resources.xml

Oracle 10g script for User/Role/Object Privileges

Posted by Sagar Patil

Imagine you have to drop an Oracle user and create it with all privs/roles again.  This often happens in test cycle of 3rd party products. The privs are sent to user on ad hoc basis to get around the installation errors and then comes requirement to replicate it on another server.  How do you do it?  Attached script will create a spool file for user granted roles, object Privileges

set serveroutput on
set feedback off
set verify off
declare
test varchar2(10000);
h number;
j number := 0;
begin
dbms_output.enable(10000);
–prompt enter the user name accept user
dbms_output.put_line(‘***********************************************************************’);
dbms_output.put_line(‘The Roles granted to the users are ‘);
dbms_output.put_line(‘***********************************************************************’);
select DBMS_METADATA.GET_GRANTED_DDL(‘ROLE_GRANT’,upper(‘&&USER’)) into test from dual;
for i in 1..ceil(length(test)/255)
loop
dbms_output.put_line(substr(test,j,255));
j := j+255;
end loop;
dbms_output.put_line(‘***********************************************************************’);
j := 0;
dbms_output.put_line(‘The System privileges are ‘);
dbms_output.put_line(‘***********************************************************************’);
select DBMS_METADATA.GET_GRANTED_DDL(‘SYSTEM_GRANT’,upper(‘&&USER’)) into test from dual;
for i in 1..ceil(length(test)/255)
loop
dbms_output.put_line(substr(test,j,255));
j := j+255;
end loop;
dbms_output.put_line(‘************************************************************************’);
j := 0;
dbms_output.put_line(‘The Object level privileges are ‘);
dbms_output.put_line(‘***********************************************************************’);
select DBMS_METADATA.GET_GRANTED_DDL(‘OBJECT_GRANT’,upper(‘&&USER’)) into test from dual;
for i in 1..ceil(length(test)/255)
loop
dbms_output.put_line(substr(test,j,255));
j := j+255;
end loop;
dbms_output.put_line(‘*************************************************************************’);
end;


Sample OUTPUT produced

Enter value for user: SYSTEM
***********************************************************************
The Roles granted to the users are
***********************************************************************
GRANT “DBA” TO “SYSTEM” WITH ADMIN OPTION
GRANT “AQ_ADMINISTRATOR_ROLE” TO “SYSTEM” WITH ADMIN OPTION
GRANT “MGMT_USER” TO “SYSTEM”

***********************************************************************
The System privileges are
***********************************************************************
GRANT GLOBAL QUERY REWRITE TO “SYSTEM”
GRANT CREATE MATERIALIZED VIEW TO “SYSTEM”
GRANT SELECT ANY TABLE TO “SYSTEM”
GRANT CREATE TABLE TO “SYSTEM”
GRANT UNLIMITED TABLESPACE TO”SYSTEM” WITH ADMIN OPTION

************************************************************************
The Object level privileges are
***********************************************************************
GRANT ALTER ON “SYS”.”INCEXP” TO “SYSTEM”
GRANT DELETE ON “SYS”.”INCEXP” TO “SYSTEM”
GRANT INDEX ON “SYS”.”INCEXP” TO “SYSTEM”
GRANT INSERT ON “SYS”.”INCEXP” TO “SYSTEM”
GRANT SELECT ON “SYS”.”INCEXP” TO “SYSTEM”
GRANT UPDATE ON “SYS”.”INCEXP” TO “SYSTEM”
GRANT REFERENCES ON “SYS”.”INCEXP” TO “SYSTEM”
GRANT ON COMMIT REFRESH ON “SYS”.”INCEXP” TO “SYSTEM”
GRANT QUERY REWRITE ON “SYS”.”INCEXP” TO “SYSTEM”
GRANT DEBUG ON “SYS”.”INCEXP” TO “SYSTEM”
GRANT FLASHBACK ON “SYS”.”INCEXP” TO “SYSTEM”
GRANT ALTER ON “SYS”.”INCVID” TO “SYSTEM”
GRANT DELETE ON”SYS”.”INCVID” TO “SYSTEM”
GRANT INDEX ON “SYS”.”INCVID” TO “SYSTEM”
GRANT INSERT ON”SYS”.”INCVID” TO “SYSTEM”
GRANT SELECT ON “SYS”.”INCVID” TO “SYSTEM”
GRANT UPDATE ON “SYS”.”INCVID” TO “SYSTEM”
GRANT REFERENCES ON “SYS”.”INCVID” TO “SYSTEM”
GRANT ON COMMIT REFRESH ON “SYS”.”INCVID” TO “SYSTEM”
GRANT QUERY REWRITE ON “SYS”.”INCVID” TO “SYSTEM”
GRANT DEBUG ON “SYS”.”INCVID” TO “SYSTEM”
GRANT FLASHBACK ON “SYS”.”INCVID” TO “SYSTEM”
GRANT ALTER ON “SYS”.”INCFIL” TO”SYSTEM”
GRANT DELETE ON “SYS”.”INCFIL” TO “SYSTEM”
GRANT INDEX ON “SYS”.”INCFIL” TO “SYSTEM”
GRANT INSERT ON “SYS”.”INCFIL” TO “SYSTEM”
GRANT SELECT ON “SYS”.”INCFIL” TO “SYSTEM”
GRANT UPDATE ON “SYS”.”INCFIL” TO “SYSTEM”
GRANT REFERENCES ON “SYS”.”INCFIL” TO “SYSTEM”
GRANT ON COMMIT REFRESH ON “SYS”.”INCFIL” TO “SYSTEM”
GRANT QUERY REWRITE ON “SYS”.”INCFIL” TO “SYSTEM”
GRANT DEBUG ON “SYS”.”INCFIL” TO “SYSTEM”
GRANT FLASHBACK ON “SYS”.”INCFIL” TO “SYSTEM”
GRANT EXECUTE ON “SYS”.”DBMS_ALERT” TO “SYSTEM”
GRANT EXECUTE ON “SYS”.”DBMS_SYS_ERROR” TO “SYSTEM”
GRANT EXECUTE ON “SYS”.”DBMS_RULE_EXIMP” TO “SYSTEM” WITH GRANT OPTION
GRANT EXECUTE ON “SYS”.”DBMS_AQ” TO “SYSTEM” WITH GRANT OPTION
GRANT EXECUTE ON “SYS”.”DBMS_AQADM” TO “SYSTEM” WITH GRANT OPTION
GRANT EXECUTE ON “SYS”.”DBMS_AQ_IMPORT_INTERNAL” TO “SYSTEM” WITH GRANT OPTION
GRANT EXECUTE ON “SYS”.”DBMS_AQELM” TO “SYSTEM” WITH GRANT OPTION
GRANT EXECUTE ON “SYS”.”DBMS_TRANSFORM_EXIMP” TO “SYSTEM” WITH GRANT OPTION
GRANT EXECUTE ON “SYS”.”SYS_GROUP” TO “SYSTEM”
GRANT EXECUTE ON “SYS”.”DBMS_DEFER_IMPORT_INTERNAL” TO “SYSTEM”
GRANT EXECUTE ON “SYS”.”DBMS_REPCAT” TO “SYSTEM”
GRANT EXECUTE ON “SYS”.”SET_TABLESPACE” TO”SYSTEM”
GRANT EXECUTE ON “SYS”.”CHECK_UPGRADE” TO “SYSTEM”
*************************************************************************

Shell Script to Delete / Copy/ Zip files older than X hours

Posted by Sagar Patil

#!/bin/bash
# Delete files older than X hours.
# This script will delete files older than 3 days from $GLOBALSHARE/current/Server01
# 14 days from $GLOBALSHARE/archive/Server01 & 14 days from /backup

CurrentPath=”/globalshare/current/Server01″
ArchivePath=”/globalshare/archive/Server01″
LocalPath=”/backup”

log=/home/oracle/scripts/delete_old_files.log
err=/home/oracle/scripts/delete_old_files.err

# Use mmin variable for file modified timestamp & cmin for file creation

# Delete from Archive Directory
# 14 days = 336 hours = 336*60 = 20160
find $ArchivePath -type f -mmin +20160 -exec rm -f {} \; 1>>${log} 2>>${err}
echo “Archive File Deletion (Files Older than 14 days) finished on : ” `date` >>${log}

# Delete from Current Directory
# 36 hours = 36*60 = 2160
find $CurrentPath -type f -mmin +2160 -exec rm -f {} \; 1>>${log} 2>>${err}
echo “Current File Deletion (Files Older than 3 days) finished on : ” `date` >>${log}
exit

Shell Script : Copy files from local folder to a Samba/NFS share

Posted by Sagar Patil

#!/bin/bash
source=”/backup”
remotePath=”/globalbackup/current”
archivePath=”/globalbackup/archive”
log=/home/oracle/scripts/cp_to_share.log
err=/home/oracle/scripts/cp_to_share.err

# I am going to rename files with timestamp so old shell files are preserved for future reference
timestamp=`date +%Y-%m-%d-%H%M`

#Move the shell file cp_to_share.sh
mv -f /home/oracle/scripts/cp_to_share.sh /home/oracle/scripts/cp_to_share.sh$timestamp
mv $log $log$timestamp
mv $err $err$timestamp

echo “### Let’s Move files copied y’day from remotePath to archivePath” >> /home/oracle/scripts/cp_to_share.sh

# Let’s Move files copied y’day from remotePath to archivePath
list=`find $remotePath -mtime -1 -type f`

for i in $list
do
echo “mv -f $i $archivePath” >> /home/oracle/scripts/cp_to_share.sh
done

echo “” >> /home/oracle/scripts/cp_to_share.sh
echo “” >> /home/oracle/scripts/cp_to_share.sh

echo “### Let’s start copying files at the global share” >> /home/oracle/scripts/cp_to_share.sh

# Copy files at the global share
list=`find /backup/ablxpora01/rman -mtime -1 -type f`
timestamp=`date +%Y-%m-%d-%H%M`

for i in $list
do
echo “cp $i $remotePath” >> /home/oracle/scripts/cp_to_share.sh
done
chmod +x /home/oracle/scripts/cp_to_share.sh
sh /home/oracle/scripts/cp_to_share.sh 1>>${log} 2>>${err}

SQL server Simplest data loading script

Posted by Sagar Patil

T-SQL script to add a server load . I have used this script to test backup timings, replication latency. One run of following procedure incerased log fie to 8GB and datafile to 6GB

use subscriber_A
go

if exists (select * from sysobjects where name = ‘Load_Data’)
drop table Load_Data
go
create table Load_Data (
x int not null,
y char(896) not null default (”),
z char(120) not null default(”)
)
go
insert Load_Data (x)
select r
from
(
select row_number() over (order by (select 1)) r
from master..spt_values a, master..spt_values b
) p
where r <= 4000000
go
create clustered index ix_x on Load_Data (x, y)
with fillfactor=51
go

Compare and copy files remotely using SCP

Posted by Sagar Patil

Following script will only work if your servers were enabled with password less login ( How to for linux /HP UNIX)

For TRUE64 Unix , I am using cksum here instead of linux md5sum. To use same script for linux just change cksum to md5sum or un comment lines in script.

Usage :

1. Your Archive Space filled up and database is stuck until you make space available. Rman backup runs every night and you don’t have access to netbackup scheduler. You want to keep on pushing archive files to a secure directory ASAP.

2. Your trace dump (udump/bdump) is filling up and you want to save trace files for future use by copying files at different location.

3. You have a dataguard standby server . Standby was down for couple of days and somehow MRP has not copied files and complaining about archives in an apply process.

How this script works? : This script will compare md5sum with local & remote files , and only copy files not available at remote site.It will also spool script “remove-$timeStamp.sh.old” to delete files once copied. I have not integrated delete functionality in script but you can delete files by running this script manually.

Parameters :

Name of Instance/File Name  : My archive files are named as “INSTANCE_NAME_%%Sequence%%.arc” like CVD_LIVE_00100.arc so I will run as “<script_name> CVD_LIVE”

Delete Days : If you pass  “<script_name> delete 5” it will delete files older than 5 days excluding today

#!/bin/bash

# Define the target host
host=”%backup_server%”

# Define the remote storage path
remotePath=”/backup2/oracle/CPI_L2_A”

# Command to use for removing files
rmCommand=”rm -f” # -f recommended, to prevent missing files breaking the script

#define the pattern to use when removing old files
# this removes old backups
removePattern=”*.[Aa][Rr][Cc]”
#this removes old remove scripts
#removePattern=”remove-*.sh”

# make sure to get a parameter
if [ “${1}” = “” ]; then
echo “Parameter required”
exit
fi

# if the parameter is delete, act specially
if [ “${1}” = “delete” ]; then
# delete needs an numeric augment
if [ “${2}” = “” ]; then
echo “delete requires an argument”
exit
fi
# remove all matching files modified in the last few days
# excluding those modified today
#    touch -t $(date +%m%d)0000 .tmp.$$
find $removePattern -mtime -${2} -and ! -newer .tmp.$$ -exec echo {} \;
rm .tmp.$$
exit
fi

# otherwise, act as if its the first part of a .arc file
list=`ls ${1}_*.[aA][rR][cC]`

timeStamp=`date +%Y-%m-%d-%H%M`

for i in $list
do
#    remoteres=`ssh $host md5sum $remotePath/$i 2>&1`
remoteres=`ssh $host cksum $remotePath/$i 2>&1`

#  localres=`md5sum $i 2>&1`
localres=`cksum $i 2>&1`

remoteMD5=`echo $remoteres | awk ‘{ print $1; }’`
localMD5=`echo $localres | awk ‘{ print $1; }’`

# these show the md5’s being returned above, just disable them not to see it
echo $i $remoteMD5
echo $i $localMD5

if [ “$remoteMD5” != “$localMD5” ]; then
# the files dont match, or the remote doesn’t have the file …
echo “$rmCommand $i” >> remove-$timeStamp.sh.old
scp $i $host:$remotePath/$i
fi
done

# make sure you can run the remove script …
if [ -f remove-$timeStamp.sh ]; then
chmod +x remove-$timeStamp.sh.old
fi

Top of Page

Top menu