пятница, 6 марта 2009 г.

Unix Shell Scripts

Перенос данных в Solaris:

cd /dir; tar cfvE - .| (cd /new_dir; tar xfBp -)
 
например из /opt/oracle в /oradata

cd /opt/oracle; tar  cfvE  -  . | ( cd /oradata;  tar xfBp - )


Deletion of trace files older than some days.

DAYS=2
find /u02/app/oracle/admin -name "*.log" -ctime ${DAYS} -exec rm {} \;
find /u02/app/oracle/admin -name "*.trc" -ctime ${DAYS} -exec rm {} \;
find /u02/app/oracle/admin -name "*.trw" -ctime ${DAYS} -exec rm {} \;
find /u02/app/oracle/admin/*/cdump -ctime ${DAYS} -exec rm -r {} \;


Удаление всех символических ссылок в каталоге:

for FILE in *
do
if [ -l $FILE ]
then
rm $FILE
fi
done

или так

for FILE in *
do
[ -l $FILE ] && rm $FILE
done

или так

for i in *; do [ -l $i ] && rm $i; done


пример создания десяти файлов от 1.txt до 10.txt:

for i in $(seq 1 10); do touch $i.txt; done


чтобы вывести все файлы в вашем домашнем каталоге,
которые были модифицированы за последние два дня, выполните:

find ~/ -mtime -2

чтобы найти файлы, которые не менялись последние два дня

find ~/ -mtime +2


Нет "-mmin" опции в "find" команде для Solaris

GNU find (Findutils) from:
http://sunfreeware.com/

Можно использовать (newer)

old = ! -newer

find / ! -newer filename

touch -t [YY]MMDDhhmm filename

Например
Чтобы вывести все файлы в Вашем домашнем каталоге, модифицированные
после 4 мая текущего года, введите:

$ touch -t 05040000 /tmp/timestamp
$ find ~ -newer /tmp/timestamp


"touch +find":

touch -t 200411042000 dummyfile
find /path -newer dummyfile -print


touch -t 200807152100 min30
touch -t 200807152130 min60
find /path/to/files -type f \( -newer min60 -a ! -newer min30 \)


Shell Script - Restart Process if not found running
A script to Check if process is running and if not running
then start the process.

You can run this as a cron job in a 5/10 mins interval :

cat chk_if_process_running.sh
_______________________
# check daemon
ps -ef | grep -v grep | grep daemon
# if not found - equals to 1, start it
if [ $? -eq 1 ]
then
/sbin/init.d/daemon start
else
echo "eq 0 - daemon found - do nothing"
fi
____


Replace .htm with .html in 100's of files inside a dir
I needed to replace {.htm} files with {.html} extensions in
100's of files in a directory :

Heres what I did :

# ls
file1.htm file2.htm file3.htm

# for list in `ls -1t *.htm*`
> do
> prefix=`echo $list | awk -F"\." '{print $1}'`
> mv $list ${prefix}.html
> done


# ls
file1.html file2.html file3.html


One more way of doing this :

# ls
file1.html file2.html file3.html

# ls *.html | awk -F '.'
'{print "mv "$1".html "$1".htm"}'| csh

# ls
file1.htm file2.htm file3.htm



Search and replace Shell Script
Had to parse 100's of files in a loop and replace a word
called Bombay with a new word Mumbai

cat file1.dat
city name is Bombay and country is INDIA.

To:
cat file1.dat
city name is Mumbai and country is INDIA.

for file in /tmp/a /tmp/c /tmp/b ; do
sed 's/Bombay/MUMBAI/g' ${file} > ${file}.new
done


Delete Files older than two Months from the Latest File
This script should Identify the Latest date file and delete files
which are older than 2 Months from latest date.


bash-3.00$ cat delet_old.sh

#!/bin/bash
touch -d "$(date -d "$(ls -lt | awk 'NR==2{print $6,$7}') 2 months ago")" FILE_MARK &&
find . ! -newer FILE_MARK -exec rm -f {} \;




Finding Large Files

This command will print the number of blocks used by each directory

find . -type d -exec du -s {} \;

du -sk * | sort -nk 1 | pg

Will print names of all files over 5,000 blocks (2,560,000) bytes.

find / -size +2000 -exec ls -s {} \; | sort -nr | more

find big files (more than 20000 blocks, ie about 10MB ) find . -size +20000

find files or directories modified in last day
find . -mtime -1

find files not accessed (read) in 45 days
find /tmp -atime +45

Add -ls to the end of any of the above commands to see a full ls -l listing of the files found.

You can combine multiple options , e.g look for which big files have filled up a filesystem recently
find . -size +20000 -mtime -1 -ls

Or combine options using an "OR" syntax, e.g. find files which were modified either less than 1 week ago or more than 2 weeks ago
find . \( -mtime +14 -o -mtime -7 \) -ls

You can send the ouput of find to another command : the xargs command is ideal for this: e.g. interactively delete all core files under your $HOME

find ~ -type f -name core |xargs rm –i

or look for a particular word in all your .c files:
find . -name "*.c" |xargs grep -l libsocket

find /usr/lib -name "*socket*"

find . -type f -exec egrep 400 {} \; -print



primary:

$more .env
#
. ${HOME}/.bash_profile
# Setup Host Specific Environment Variables:
. ${HOME}/bin/_conf/host.conf


$more host.conf
#############################################################
#############################################################
# UNIX Config File:
#############################################################
#############################################################

export COMPANY_NAME=SUN
export HOST_NAME=primary.sun.com
export HOME_DIR=${HOME}
export BIN_DIR=${HOME_DIR}/bin
export TMP_DIR=/tmp
export ORA_USER=oradb

export BKP_DIR=${BIN_DIR}/_bkp
export LIB_DIR=${BIN_DIR}/_lib
export SQL_DIR=${BIN_DIR}/_sql
export PKG_DIR=${BIN_DIR}/pkg

############################################################
# Mail Section:
############################################################
app_testdb="testdb@sun.com"
app_testdb2="testdb2@sun.com"
app_testdb3="testdb3@sun.com"

sys_app="sysapp@sun.com"
sys_all="sysadmin@sun.com"

dba_all="sysdba@sun.com"

sec_all="sec1@sun.com sec2@sun.com"

export MAIL_DBA="${dba_all}"
export MAIL_SYS="${sys_all}"
export MAIL_APP="${app_testdb}"
export MAIL_SEC="${sec_all}"
export MAIL_DEFAULT="${dba_all}"

############################################################
# Utilities Section:
############################################################
export FIND_UTL=/usr/xpg4/bin/find
export TAR_UTL=/usr/bin/tar
export UTL_SEND=${BIN_DIR}/_lib/utl_send.sh
export UTL_RMAN=/u01/app/oradb/product/11.2.0.3/dbhome_1/bin/rman
export UTL_SQLPLUS=/u01/app/oradb/product/11.2.0.3/dbhome_1/bin/sqlplus
export UTL_ORAPWD=/u01/app/oradb/product/11.2.0.3/dbhome_1/bin/orapwd

############################################################
# Backups Section:
############################################################
export RMAN_BKP=/u09/backups/oradb/rman

$



Пример для тестовой базы:



# Reserv Crontab to text file:
0 03 * * * crontab -l > ${HOME}/bin/crontab_oracle.lst

# Checking filesystem usage:
30    08 * * * ${HOME}/bin/pkg/monitor_fs/_run.sh 80 Warning  > /dev/null 2>> /tmp/crontab_oracle.err
09,39  * * * * ${HOME}/bin/pkg/monitor_fs/_run.sh 90 Error    > /dev/null 2>> /tmp/crontab_oracle.err


# Rman Backups:
00 20 * * * ${HOME}/bin/pkg/rman_backup/_run.sh   testdb     > /dev/null 2>> /tmp/crontab_oracle.err

# ADRCI purge
30 06 * * 0 ${HOME}/bin/pkg/adrci_purge/_run.sh  > /dev/null 2>> /tmp/crontab_oracle.err

# Clean system audit
06 04 * * * ${HOME}/bin/pkg/clean_sys_audit/_run.sh 7 > /dev/null 2>> /tmp/crontab_oracle.err

# MAINTANANCE_STATISTICS:
00 06 * * 0 ${HOME}/bin/pkg/gather_statistics/_run.sh testdb   > /dev/null 2>> /tmp/crontab_oracle.err
:t5:/u01/app/oradb/product/11.2.0.3/dbhome_1/dbs$





:t5:~$more  ~/bin/_conf/.env
#
. ${HOME}/.bash_profile
# Setup Host Specific Environment Variables:
. ${HOME}/bin/_conf/host.conf


:t5:~$more .bash_profile
umask 027
export EDITOR=vi
export TMP=/tmp
export TMPDIR=/tmp
export PATH=/usr/bin:/usr/sbin
export ORACLE_HOSTNAME=t5.sun.com
export ORACLE_BASE=/u01/app/oradb
export ORACLE_HOME=${ORACLE_BASE}/product/11.2.0.3/dbhome_1
export PATH=${ORACLE_HOME}/OPatch:${ORACLE_HOME}/bin:${PATH}
export PS1='${ORACLE_SID}:\h:\w\$'

alias ll="ls -la"
alias dba="sqlplus / as sysdba"
:t5:~$



:t5:~$more  bin/_conf/host.conf
#############################################################
#############################################################
# UNIX Config File:
#############################################################
#############################################################

export COMPANY_NAME=SUN
export HOST_NAME=t5.sun.com
export HOME_DIR=${HOME}
export BIN_DIR=${HOME_DIR}/bin
export TMP_DIR=/tmp
export ORA_USER=oradb

export BKP_DIR=${BIN_DIR}/_bkp
export LIB_DIR=${BIN_DIR}/_lib
export SQL_DIR=${BIN_DIR}/_sql
export PKG_DIR=${BIN_DIR}/pkg

############################################################
# Mail Section:
############################################################
app_dit=""

sys_all="sysadmin@sun.com"

dba_all="sysdba@sun.com"

sec_all="sec@sun.com"

export MAIL_DBA="${dba_all}"
export MAIL_SYS="${sys_all}"
export MAIL_APP="${app_athena}"
export MAIL_SEC="${sec_all}"
export MAIL_DEFAULT="${dba_all}"

############################################################
# Utilities Section:
############################################################
export FIND_UTL=/usr/xpg4/bin/find
export TAR_UTL=/usr/bin/tar
export UTL_SEND=${BIN_DIR}/_lib/utl_send.sh
export UTL_RMAN=/u01/app/oradb/product/11.2.0.3/dbhome_1/bin/rman
export UTL_SQLPLUS=/u01/app/oradb/product/11.2.0.3/dbhome_1/bin/sqlplus
export UTL_ORAPWD=/u01/app/oradb/product/11.2.0.3/dbhome_1/bin/orapwd

############################################################
# Backups Section:
############################################################
export RMAN_BKP=/u09/backups/oradb/rman

:t5:~$




:t5:~/bin$more  /export/home/oradb/bin/_lib/utl_send.sh
#!/bin/bash
# UNIX


# Setup Environment:
. ${HOME}/bin/_conf/.env


# Check for Message Theme:
if [ "$1" ]; then
  priv_mess_theme="$1"
else
  priv_mess_theme="No Theme"
fi



# Check For Message Recipients:
if [ "$2" ]; then
  priv_mail_recipients="$2"
else
  priv_mail_recipients=${MAIL_DEFAULT}
fi


# :
cat - | mailx -s "${priv_mess_theme}" "${priv_mail_recipients}"
:t5:~/bin$










:t5:~$more ${HOME}/bin/pkg/monitor_fs/_run.sh
#!/bin/bash

#
# Package Name:
#

tmp_string="`dirname $0`"
pkg_name="`basename ${tmp_string}`"

if [ "${pkg_name}" = "." ]; then
  tmp_string="`pwd`"
  pkg_name="`basename ${tmp_string}`"
fi


#
# Check Parameter
#

if [ $1 ]; then
  limit_per_free=$1
else
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: Error! (Parameter=1). Call `basename $0` " >&2
  exit 2
fi

if [ $2 ]; then
  mess=$2
else
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: Error! (Parameter=2). Call: `basename $0` " >&2
  exit 2
fi


#
# Setup Environment:
#

pkg_env="${HOME}/bin/_conf/.env"
if [ ! -r "${pkg_env}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Not Found Environment file: ${pkg_env}" >&2
  exit 2
fi

if [ -s "${pkg_env}" ]; then
  . ${pkg_env}
else
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Environment file is empty: ${pkg_env}" >&2
  exit 2
fi



#
# Check Environment:
#


# Check TMP_DIR:
if [ -z "${TMP_DIR}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Environment variable TMP_DIR not defined" >&2
  exit 2
elif [ ! -d "${TMP_DIR}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Directory TMP_DIR not found (${TMP_DIR})" >&2
  exit 2
elif [ ! -w "${TMP_DIR}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Directory TMP_DIR not writeable (${TMP_DIR})" >&2
  exit 2
fi


# Check BIN_DIR:
if [ -z "${BIN_DIR}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Environment variable BIN_DIR not defined" >&2
  exit 2
elif [ ! -d "${BIN_DIR}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Directory BIN_DIR not found (${BIN_DIR})" >&2
  exit 2
fi


# Check COMPANY_NAME:
if [ -z "${COMPANY_NAME}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Environment variable COMPANY_NAME not defined" >&2
  exit 2
fi


# Check HOST_NAME:
if [ -z "${HOST_NAME}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Environment variable HOST_NAME not defined" >&2
  exit 2
fi


# Check MAIL_SYSDBA:
if [ -z "${MAIL_DBA}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Environment variable MAIL_RECIPIENTS not defined" >&2
  exit 2
fi


# Check UTL_SEND:
if [ -z "${UTL_SEND}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Environment variable UTL_SEND not defined" >&2
  exit 2
elif [ ! -f "${UTL_SEND}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. File UTL_SEND not found (${UTL_SEND})" >&2
  exit 2
elif [ ! -x "${UTL_SEND}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. File UTL_SEND not executable (${UTL_SEND})" >&2
  exit 2
fi


# Initialize Package:

pkg_flag="`basename $0 .sh`"
run_in_progress="${TMP_DIR}/${pkg_name}_${mess}.lock"
log_file="${TMP_DIR}/${pkg_name}_${mess}.log"
prefix="${COMPANY_NAME}#${HOST_NAME} ${pkg_name}"
mess_theme="${prefix}: Error! Another process running (${run_in_progress})"

mail_recipients="$MAIL_DBA"
echo $mail_recipients

# Check Another process for running:

if [ -f ${run_in_progress} ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: Error! Another process running. Remove a file ${run_in_progress}" >&2
  echo "Remove a file ${run_in_progress}" | ${BIN_DIR}/_lib/utl_send.sh "${mess_theme}" "${mail_recipients}"
  exit 2
fi



# Prevent Parallel Execution:
touch ${run_in_progress}


# Run Implementation:
${BIN_DIR}/pkg/${pkg_name}/body.sh "${pkg_flag}" "${limit_per_free}" "${mess}" | tee ${log_file}



# Cleanup Stop Flag:
test -r ${run_in_progress} && rm ${run_in_progress}
:t5:~$







:t5:~$more  ${HOME}/bin/pkg/monitor_fs/body.sh
#!/bin/bash


#
# Check Parameters:
#

# Package Name:
tmp_string="`dirname $0`"
pkg_name="`basename ${tmp_string}`"

if [ "${pkg_name}" = "." ]; then
  tmp_string="`pwd`"
  pkg_name="`basename ${tmp_string}`"
fi

# Check for internal call:
if [ ! $1 = '_run' ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: Error! (Parameter=1) Call `basename $0` from ./_run.sh" >&2
  exit 2
fi


# Check For :
if [ $2 ]; then
  limit_per_free=$2
else
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: Error! (Parameter=2) Call `basename $0` With 2-d parameter" >&2
  exit 2
fi

# Check For :
if [ $3 ]; then
 mess=$3
else
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: Error! (Parameter=3) Call `basename $0` With 3-th parameter" >&2
  exit 2
fi

#
# Define local Variables:
#

# Variables:

prefix="${COMPANY_NAME}#${HOST_NAME} ${pkg_name}"
mess_theme="${prefix}: ${mess} Filesystem on server maybe full"
temp_file=${TMP_DIR}/${pkg_name}.tmp
mess_limit="The limit ${limit_per_free}% is exceeded"

mail_recipients="$MAIL_DBA $MAIL_SYS"
echo $mail_recipients

#
# Body Section:
#

# Remove Old Data:
cat /dev/null > ${temp_file}
echo ${mess_limit} > ${temp_file}

n_count=0

${BIN_DIR}/_lib/get_fs_pct_usage.sh | while read stt
do
  # :
  let n_count=n_count+1
  
  # :
  if [ "${n_count}" -gt 1 ]; then

    fs_vol=`echo ${stt} | awk -F% '{print $1}'`
    fs_nam=`echo ${stt} | awk -F% '{print $2}'`

    # :
    if [ "${fs_vol}" -ge ${limit_per_free} ]; then
      echo "filesystem ${fs_nam} used by ${fs_vol} percent" >> ${temp_file}
    fi
  fi
done


# Check For Send Criteria:
#if [ -s ${temp_file} ]; then
grep "filesystem" ${temp_file}
if [ $? -eq 0 ]; then
  cat ${temp_file} | ${BIN_DIR}/_lib/utl_send.sh "${mess_theme}" "${mail_recipients}"
fi
:t5:~$



:t5:~/bin/_lib$more /export/home/oradb/bin/_lib/get_fs_pct_usage.sh
# Get name of the operating system:
fnc_os_name=`uname -s`


# :
if [ ${fnc_os_name} = 'SunOS' ]; then
  df -k |grep -v cdrom|grep -v libc_psr.so|awk '{print $5"    "$6}'
fi


if [ ${fnc_os_name} = 'Linux' ]; then
  df -kP |grep -v cdrom|grep -v libc_psr.so| awk '{print $5"    "$6}'
fi
:t5:~/bin/_lib$





:t5:~/bin/_lib$more  ${HOME}/bin/pkg/rman_backup/_run.sh
#!/bin/bash


#
# Package Name:
#

tmp_string="`dirname $0`"
pkg_name="`basename ${tmp_string}`"

if [ "${pkg_name}" = "." ]; then
  tmp_string="`pwd`"
  pkg_name="`basename ${tmp_string}`"
fi

# Check Parameters:
if [ $1 ]
then
  oracle_sid=`echo ${1} | tr "[A-Z]" "[a-z]"`
else
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: Error! (Parameter=1). Call `basename $0` " >&2
  exit 2
fi

#
# Setup Environment:
#

pkg_env="${HOME}/bin/_conf/.env"
if [ ! -r "${pkg_env}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Not Found Environment file: ${pkg_env}" >&2
  exit 2
fi

if [ -s "${pkg_env}" ]; then
  . ${pkg_env}
else
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Environment file is empty: ${pkg_env}" >&2
  exit 2
fi


#
# Check Environment:
#


# Check ORACLE_USER:
if [ -z "${ORA_USER}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Environment variable ORA_USER not defined" >&2
  exit 2
else
  ora_user=${ORA_USER}
fi

# Check Database Instance:
loc_status=`ps -fu ${ora_user} | grep -w "ora_[a-z]*_${oracle_sid}"`
loc_res=$?

if [ ${loc_res} -eq 0 ]; then
  echo "Database Instance OK"
else
  echo "Error! Not found Database Instance."
  exit
fi


# Check ORACLE_HOME:
if [ -z "${ORACLE_HOME}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Environment variable ORACLE_HOME not defined" >&2
  exit 2
elif [ ! -d "${ORACLE_HOME}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Directory ORACLE_HOME not found (${ORACLE_HOME})" >&2
  exit 2
fi


# Check TMP_DIR:
if [ -z "${TMP_DIR}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Environment variable TMP_DIR not defined" >&2
  exit 2
elif [ ! -d "${TMP_DIR}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Directory TMP_DIR not found (${TMP_DIR})" >&2
  exit 2
elif [ ! -w "${TMP_DIR}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Directory TMP_DIR not writeable (${TMP_DIR})" >&2
  exit 2
fi


# Check BIN_DIR:
if [ -z "${BIN_DIR}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Environment variable BIN_DIR not defined" >&2
  exit 2
elif [ ! -d "${BIN_DIR}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Directory BIN_DIR not found (${BIN_DIR})" >&2
  exit 2
fi


# Check COMPANY_NAME:
if [ -z "${COMPANY_NAME}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Environment variable COMPANY_NAME not defined" >&2
  exit 2
fi


# Check HOST_NAME:
if [ -z "${HOST_NAME}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Environment variable HOST_NAME not defined" >&2
  exit 2
fi


# Check MAIL_RECIPIENTS:
if [ -z "${MAIL_DBA}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Environment variable MAIL_RECIPIENTS not defined" >&2
  exit 2
fi


# Check UTL_SEND:
if [ -z "${UTL_SEND}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Environment variable UTL_SEND not defined" >&2
  exit 2
elif [ ! -f "${UTL_SEND}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. File UTL_SEND not found (${UTL_SEND})" >&2
  exit 2
elif [ ! -x "${UTL_SEND}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. File UTL_SEND not executable (${UTL_SEND})" >&2
  exit 2
fi

# Initialize Package:

pkg_flag="`basename $0 .sh`"
run_in_progress=${TMP_DIR}/${pkg_name}_${oracle_sid}.lock
log_file=${TMP_DIR}/${pkg_name}_${oracle_sid}.log
prefix="${COMPANY_NAME}#${HOST_NAME}(${oracle_sid}) ${pkg_name}"
mess_theme="${prefix}: Error! Another process running (${run_in_progress})"

mail_recipients="$MAIL_DBA"
echo $mail_recipients

# Check Another process for running:
if [ -f ${run_in_progress} ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: Error! Another process running. Remove a file ${run_in_progress}" >&2
  echo "Remove a file ${run_in_progress}" | ${BIN_DIR}/_lib/utl_send.sh "${mess_theme}" "${mail_recipients}"
  exit 2
fi

# Prevent Parallel Execution:
touch ${run_in_progress}

# Run Implementation:
${BIN_DIR}/pkg/${pkg_name}/body.sh "${pkg_flag}" "${oracle_sid}" | tee ${log_file}

# Cleanup Stop Flag:
test -r ${run_in_progress} && rm ${run_in_progress}

:t5:~/bin/_lib$





t5:~/bin/_lib$more  ${HOME}/bin/pkg/rman_backup/body.sh
#!/bin/bash


#
# Check Parameters:
#

# Package Name:
tmp_string="`dirname $0`"
pkg_name="`basename ${tmp_string}`"

if [ "${pkg_name}" = "." ]; then
  tmp_string="`pwd`"
  pkg_name="`basename ${tmp_string}`"
fi

# Check for internal call:
if [ ! $1 = '_run' ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: Error! (Parameter=1) Call `basename $0` from ./_run.sh" >&2
  exit 2
fi


# Check For :
if [ $2 ]
then
  echo " 2=${2} (ORACLE_SID)"
  ORACLE_SID=`echo ${2} | tr "[A-Z]" "[a-z]"`; export ORACLE_SID
else
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: Error! (Parameter=2) Call `basename $0` With 2-d parameter" >&2
  exit 2
fi


#
# Define local variables:
#

# Variables:

prefix="${COMPANY_NAME}#${HOST_NAME}(${ORACLE_SID}) ${pkg_name}"
mess_theme="${prefix}:Rman backup"
rman_cmdfile=${BIN_DIR}/_sql/backup_${ORACLE_SID}.rman
log_file=${TMP_DIR}/${pkg_name}_${ORACLE_SID}.log
orapwd_filename="${ORACLE_HOME}/dbs/orapw${ORACLE_SID}"


mail_recipients="$MAIL_DBA"
###echo $mail_recipients

start_secs=$(/usr/xpg4/bin/awk 'BEGIN{srand();print srand()}')
begin_backup="`date +%Y.%m.%d" "%H:%M:%S`"

sqlplus '/ as sysdba' << EOF > /dev/null
alter database backup controlfile to trace as '$RMAN_BKP/$ORACLE_SID/ctrl_trace_${ORACLE_SID}' reuse;
create pfile='$RMAN_BKP/$ORACLE_SID/init${ORACLE_SID}.bkp' from spfile;
exit;
EOF

cp -pr ${orapwd_filename} $RMAN_BKP/$ORACLE_SID/orapw${ORACLE_SID}

$UTL_RMAN target / catalog 'rman/pass@catdb.sun.com'  cmdfile ${rman_cmdfile}  log=${log_file}
###$UTL_RMAN target /  cmdfile ${rman_cmdfile}  log=${log_file}

finish_secs=$(/usr/xpg4/bin/awk 'BEGIN{srand();print srand()}')
end_backup="`date +%Y.%m.%d" "%H:%M:%S`"

let diff_secs=($finish_secs - $start_secs)

let days=$diff_secs/86400
let remainder=$diff_secs%86400
let hours=$remainder/3600
let remainder=$remainder%3600
let minutes=$remainder/60
let seconds=$remainder%60

size=$(du -sh /u09/backups/oradb/rman/${ORACLE_SID}/oradata/ | awk '{print $1}')
echo "Begin backup:     $begin_backup" >> ${log_file}
echo "End backup:       $end_backup" >> ${log_file}
echo "Duration: Days = $days, Hours = $hours, Minutes = $minutes, Seconds = $seconds" >>${log_file}
echo "Size:             $size" >>${log_file}

cat  ${log_file}  | ${BIN_DIR}/_lib/utl_send.sh "${mess_theme}" "${mail_recipients}"
:t5:~/bin/_lib$



:t5:~/bin/_sql$more /export/home/oradb/bin/_sql/backup_testdb.rman
# Clear Parameters:
CONFIGURE RETENTION POLICY CLEAR;
CONFIGURE BACKUP OPTIMIZATION CLEAR;
CONFIGURE DEFAULT DEVICE TYPE CLEAR;
CONFIGURE CONTROLFILE AUTOBACKUP CLEAR;
CONFIGURE CONTROLFILE AUTOBACKUP FORMAT FOR DEVICE TYPE DISK CLEAR;
CONFIGURE CONTROLFILE AUTOBACKUP FORMAT FOR DEVICE TYPE SBT CLEAR;
CONFIGURE DEVICE TYPE DISK CLEAR;
CONFIGURE DATAFILE BACKUP COPIES FOR DEVICE TYPE DISK CLEAR;
CONFIGURE DATAFILE BACKUP COPIES FOR DEVICE TYPE SBT  CLEAR;
CONFIGURE ARCHIVELOG BACKUP COPIES FOR DEVICE TYPE DISK CLEAR;
CONFIGURE ARCHIVELOG BACKUP COPIES FOR DEVICE TYPE SBT CLEAR;
CONFIGURE ARCHIVELOG DELETION POLICY CLEAR;
CONFIGURE CHANNEL DEVICE TYPE DISK CLEAR;
CONFIGURE CHANNEL DEVICE TYPE SBT CLEAR;
CONFIGURE MAXSETSIZE CLEAR;
CONFIGURE SNAPSHOT CONTROLFILE NAME CLEAR;

CONFIGURE ENCRYPTION FOR DATABASE CLEAR;
CONFIGURE ENCRYPTION ALGORITHM CLEAR;
CONFIGURE COMPRESSION ALGORITHM CLEAR;

CONFIGURE DB_UNIQUE_NAME testdb_P  CLEAR;
CONFIGURE DB_UNIQUE_NAME testdb_S1 CLEAR;
CONFIGURE DB_UNIQUE_NAME testdb_S2 CLEAR;


# Configure Parameters:
CONFIGURE BACKUP OPTIMIZATION ON;
CONFIGURE CONTROLFILE AUTOBACKUP ON;
CONFIGURE CONTROLFILE AUTOBACKUP FORMAT FOR DEVICE TYPE DISK TO '$RMAN_BKP/$ORACLE_SID/oradata/%d-%F';
CONFIGURE CHANNEL DEVICE TYPE DISK FORMAT '$RMAN_BKP/$ORACLE_SID/oradata/db_%d_%s_%p_%t';
CONFIGURE DEVICE TYPE DISK PARALLELISM 4 BACKUP TYPE TO BACKUPSET;

CONFIGURE DB_UNIQUE_NAME testdb_P  CONNECT IDENTIFIER 'testdb_p.sun.com';
CONFIGURE DB_UNIQUE_NAME testdb_S1 CONNECT IDENTIFIER 'testdb_s1.sun.com';
CONFIGURE DB_UNIQUE_NAME testdb_S2 CONNECT IDENTIFIER 'testdb_s2.sun.com';

#CONFIGURE ARCHIVELOG DELETION POLICY TO BACKED UP 1 TIMES TO DISK;
CONFIGURE ARCHIVELOG DELETION POLICY TO APPLIED ON ALL STANDBY;

CONFIGURE ARCHIVELOG DELETION POLICY TO APPLIED ON ALL STANDBY FOR DB_UNIQUE_NAME testdb_P;   # For Catalog Only
CONFIGURE ARCHIVELOG DELETION POLICY TO APPLIED ON ALL STANDBY FOR DB_UNIQUE_NAME testdb_S1;  # For Catalog Only
CONFIGURE ARCHIVELOG DELETION POLICY TO APPLIED ON ALL STANDBY FOR DB_UNIQUE_NAME testdb_S2;  # For Catalog Only

show all;

crosscheck backup;
crosscheck copy;
crosscheck archivelog all;
CROSSCHECK BACKUP OF CONTROLFILE;
CROSSCHECK BACKUP OF SPFILE;
delete noprompt expired backup;
delete noprompt expired copy;
delete noprompt expired archivelog all;


run
{
   backup incremental level 1 for recover of copy with tag 'incr_backup' database;
   recover copy of database with tag 'incr_backup';
}

run
{
 backup archivelog all not backed up;
}

run
{
 crosscheck backup;
 crosscheck copy;
 delete noprompt expired backup;
 delete noprompt expired copy;
 delete noprompt obsolete;
}

backup current controlfile for standby tag 'standby controlfile';
report schema;
list copy;
list backup;
list backup summary;
:t5:~/bin/_sql$



:t5:~/bin/_sql$more ${HOME}/bin/pkg/adrci_purge/_run.sh
#!/bin/bash

#
# Package Name:
#

tmp_string="`dirname $0`"
pkg_name="`basename ${tmp_string}`"

if [ "${pkg_name}" = "." ]; then
  tmp_string="`pwd`"
  pkg_name="`basename ${tmp_string}`"
fi


#
# Setup Environment:
#

pkg_env="${HOME}/bin/_conf/.env"
if [ ! -r "${pkg_env}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Not Found Environment file: ${pkg_env}" >&2
  exit 2
fi

if [ -s "${pkg_env}" ]; then
  . ${pkg_env}
else
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Environment file is empty: ${pkg_env}" >&2
  exit 2
fi



#
# Check Environment:
#


# Check TMP_DIR:
if [ -z "${TMP_DIR}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Environment variable TMP_DIR not defined" >&2
  exit 2
elif [ ! -d "${TMP_DIR}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Directory TMP_DIR not found (${TMP_DIR})" >&2
  exit 2
elif [ ! -w "${TMP_DIR}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Directory TMP_DIR not writeable (${TMP_DIR})" >&2
  exit 2
fi


# Check BIN_DIR:
if [ -z "${BIN_DIR}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Environment variable BIN_DIR not defined" >&2
  exit 2
elif [ ! -d "${BIN_DIR}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Directory BIN_DIR not found (${BIN_DIR})" >&2
  exit 2
fi


# Check COMPANY_NAME:
if [ -z "${COMPANY_NAME}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Environment variable COMPANY_NAME not defined" >&2
  exit 2
fi


# Check HOST_NAME:
if [ -z "${HOST_NAME}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Environment variable HOST_NAME not defined" >&2
  exit 2
fi


# Check MAIL_SYSDBA:
if [ -z "${MAIL_DBA}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Environment variable MAIL_RECIPIENTS not defined" >&2
  exit 2
fi


# Check UTL_SEND:
if [ -z "${UTL_SEND}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Environment variable UTL_SEND not defined" >&2
  exit 2
elif [ ! -f "${UTL_SEND}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. File UTL_SEND not found (${UTL_SEND})" >&2
  exit 2
elif [ ! -x "${UTL_SEND}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. File UTL_SEND not executable (${UTL_SEND})" >&2
  exit 2
fi


# Initialize Package:

pkg_flag="`basename $0 .sh`"
run_in_progress="${TMP_DIR}/${pkg_name}_${mess}.lock"
log_file="${TMP_DIR}/${pkg_name}_${mess}.log"
prefix="${COMPANY_NAME}#${HOST_NAME} ${pkg_name}"
mess_theme="${prefix}: Error! Another process running (${run_in_progress})"

mail_recipients="$MAIL_DBA"
echo $mail_recipients

# Check Another process for running:

if [ -f ${run_in_progress} ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: Error! Another process running. Remove a file ${run_in_progress}" >&2
  echo "Remove a file ${run_in_progress}" | ${BIN_DIR}/_lib/utl_send.sh "${mess_theme}" "${mail_recipients}"
  exit 2
fi



# Prevent Parallel Execution:
touch ${run_in_progress}


# Run Implementation:
${BIN_DIR}/pkg/${pkg_name}/body.sh | tee ${log_file}



# Cleanup Stop Flag:
test -r ${run_in_progress} && rm ${run_in_progress}
:t5:~/bin/_sql$




:t5:~/bin/_sql$more ${HOME}/bin/pkg/adrci_purge/body.sh
#!/bin/bash


#
# Check Parameters:
#

# Package Name:
tmp_string="`dirname $0`"
pkg_name="`basename ${tmp_string}`"

if [ "${pkg_name}" = "." ]; then
  tmp_string="`pwd`"
  pkg_name="`basename ${tmp_string}`"
fi

# Check for internal call:
if [ ! $1 = '_run' ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: Error! (Parameter=1) Call `basename $0` from ./_run.sh" >&2
  exit 2
fi



#
# Define local Variables:
#

# Variables:

prefix="${COMPANY_NAME}#${HOST_NAME} ${pkg_name}"
mess_theme="${prefix}: Purge trace and dump files"
temp_file=${TMP_DIR}/${pkg_name}.tmp
mess_limit="The limit ${limit_per_free}% is exceeded"

mail_recipients="$MAIL_DBA"
echo $mail_recipients

#
# Body Section:
#

${BIN_DIR}/_lib/adrci_purge.sh  > ${temp_file}

cat ${temp_file} | ${BIN_DIR}/_lib/utl_send.sh "${mess_theme}" "${mail_recipients}"
:t5:~/bin/_sql$



:t5:~/bin$more  /export/home/oradb/bin/_lib/adrci_purge.sh
#!/bin/sh

for ADRHOME in `adrci exec="show home"`
do
    if [ $ADRHOME = "ADR" -o $ADRHOME = "Homes:" ]
    then
        continue;
    fi
    echo $ADRHOME
    adrci << EOF
         set home $ADRHOME
         echo $ADRHOME
         set control (SHORTP_POLICY = 168)
         set control (LONGP_POLICY = 720)

         # purge all tracefiles older than 2 days (2880 minutes):
         purge -age   2880 -type trace

         # purging ALERT older than 30 days
         purge -age 43200 -type ALERT

         # purging INCIDENT older than 14 days
         purge -age  20160 -type INCIDENT

         # purging TRACE older than 14 days
         purge -age  20160 -type TRACE

         # purging CDUMP older than 14 days
         purge -age  20160 -type CDUMP

         # purging HM older than 14 days
         purge -age  20160 -type HM

         show tracefile -rt
         purge
    exit
EOF
done

:t5:~/bin$





:t5:~/bin$more ${HOME}/bin/pkg/clean_sys_audit/_run.sh
#!/bin/bash


#
# Package Name:
#

tmp_string="`dirname $0`"
pkg_name="`basename ${tmp_string}`"

if [ "${pkg_name}" = "." ]; then
  tmp_string="`pwd`"
  pkg_name="`basename ${tmp_string}`"
fi



# Check Parameters:
if [ $1 ]; then
  retention_period=$1
else
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: Error! (Parameter=2). Call `basename $0` " >&2
  exit 2
fi


#
# Setup Environment:
#

pkg_env="${HOME}/bin/_conf/.env"
if [ ! -r "${pkg_env}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Not Found Environment file: ${pkg_env}" >&2
  exit 2
fi

if [ -s "${pkg_env}" ]; then
  . ${pkg_env}
else
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Environment file is empty: ${pkg_env}" >&2
  exit 2
fi


#
# Check Environment:
#

# Check ORACLE_USER:
if [ -z "${ORA_USER}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Environment variable ORA_USER not defined" >&2
  exit 2
else
  ora_user=${ORA_USER}
fi


# Check ORACLE_BASE:
if [ -z "${ORACLE_BASE}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Environment variable ORACLE_BASE not defined" >&2
  exit 2
else
  oracle_base=${ORACLE_BASE}
fi


# Check ORACLE_HOME:
if [ -z "${ORACLE_HOME}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Environment variable ORACLE_HOME not defined" >&2
  exit 2
elif [ ! -d "${ORACLE_HOME}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Directory ORACLE_HOME not found (${ORACLE_HOME})" >&2
  exit 2
fi


# Check TMP_DIR:
if [ -z "${TMP_DIR}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Environment variable TMP_DIR not defined" >&2
  exit 2
elif [ ! -d "${TMP_DIR}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Directory TMP_DIR not found (${TMP_DIR})" >&2
  exit 2
elif [ ! -w "${TMP_DIR}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Directory TMP_DIR not writeable (${TMP_DIR})" >&2
  exit 2
fi


# Check BIN_DIR:
if [ -z "${BIN_DIR}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Environment variable BIN_DIR not defined" >&2
  exit 2
elif [ ! -d "${BIN_DIR}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Directory BIN_DIR not found (${BIN_DIR})" >&2
  exit 2
fi


# Check COMPANY_NAME:
if [ -z "${COMPANY_NAME}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Environment variable COMPANY_NAME not defined" >&2
  exit 2
fi


# Check HOST_NAME:
if [ -z "${HOST_NAME}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Environment variable HOST_NAME not defined" >&2
  exit 2
fi


# Check MAIL_RECIPIENTS:
if [ -z "${MAIL_DBA}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Environment variable MAIL_RECIPIENTS not defined" >&2
  exit 2
fi


# Check UTL_SEND:
if [ -z "${UTL_SEND}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Environment variable UTL_SEND not defined" >&2
  exit 2
elif [ ! -f "${UTL_SEND}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. File UTL_SEND not found (${UTL_SEND})" >&2
  exit 2
elif [ ! -x "${UTL_SEND}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. File UTL_SEND not executable (${UTL_SEND})" >&2
  exit 2
fi



# Initialize Package:

pkg_flag="`basename $0 .sh`"
run_in_progress=${TMP_DIR}/${pkg_name}_${oracle_sid}.lock
log_file=${TMP_DIR}/${pkg_name}_${oracle_sid}.log
prefix="${COMPANY_NAME}#${HOST_NAME} ${pkg_name}"
mess_theme="${prefix}: Error! Another process running (${run_in_progress})"

###mail_recipients="$MAIL_DBA"
echo $mail_recipients


# Check Another process for running:
if [ -f ${run_in_progress} ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: Error! Another process running. Remove a file ${run_in_progress}" >&2
  echo "Remove a file ${run_in_progress}" | ${BIN_DIR}/_lib/utl_send.sh "${mess_theme}" "${mail_recipients}"
  exit 2
fi


# Prevent Parallel Execution:
touch ${run_in_progress}


# Run Implementation:
${BIN_DIR}/pkg/${pkg_name}/body.sh "${pkg_flag}" "${retention_period}" | tee ${log_file}


# Send E-Mail:
# mess_theme="${host_name}(${oracle_sid}): ${mess_header}"
# cat ${log_file} | ${BIN_DIR}/_lib/utl_send.sh "${mess_theme}" "${mail_recipients}"


# Cleanup Stop Flag:
test -r ${run_in_progress} && rm ${run_in_progress}
:t5:~/bin$




:t5:~/bin$more ${HOME}/bin/pkg/clean_sys_audit/body.sh
#!/bin/bash

#
# Check Parameters:
#

# Package Name:
tmp_string="`dirname $0`"
pkg_name="`basename ${tmp_string}`"

if [ "${pkg_name}" = "." ]; then
  tmp_string="`pwd`"
  pkg_name="`basename ${tmp_string}`"
fi

# Check for internal call:
if [ ! $1 = '_run' ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: Error! (Parameter=1) Call `basename $0` from ./_run.sh" >&2
  exit 2
fi


# Check For :
if [ $2 ]; then
  retention_period=$2
else
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: Error! (Parameter=3) Call `basename $0` With 3-d parameter" >&2
  exit 2
fi


#
# Define local variables:
#

# Variables:


host_name=${HOST_NAME}
oracle_sid=${ORACLE_SID}
mail_recipients="$MAIL_DBA"

sys_audit_dir=${ORACLE_HOME}/rdbms/audit/

echo "`date +%T` Check directory for system audit: (${sys_audit_dir})"

if [ -r ${sys_audit_dir} ]; then
  echo "system audit RDBMS dir done."
  ${FIND_UTL} /u01/app/oradb/product/11.2.0.3/dbhome_1/rdbms/audit/ -type f -name "*_*\_*\_*.aud" -mtime +${retention_period} -print
 -exec ls -l {} \;
  ${FIND_UTL} /u01/app/oradb/product/11.2.0.3/dbhome_1/rdbms/audit/ -type f -name "*_*\_*\_*.aud" -mtime +${retention_period} -print
 -exec rm {} \;
else
  loc_mess_theme="${host_name}(${oracle_sid})-${pkg_name}: Error! Not Found RDBMS Directory for Clean system audit"
  loc_mess_body="Not exist directory: ${sys_audit_dir}"
  echo "${loc_mess_body}" | ${BIN_DIR}/_lib/utl_send.sh "${loc_mess_theme}" "${mail_recipients}"
  echo " - Error!"
  exit
fi

:t5:~/bin$




:t5:~/bin$more ${HOME}/bin/pkg/gather_statistics/_run.sh
#!/bin/bash


#
# Package Name:
#

tmp_string="`dirname $0`"
pkg_name="`basename ${tmp_string}`"

if [ "${pkg_name}" = "." ]; then
  tmp_string="`pwd`"
  pkg_name="`basename ${tmp_string}`"
fi



# Check Parameters:
if [ $1 ]
then
  oracle_sid=`echo ${1} | tr "[A-Z]" "[a-z]"`
else
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: Error! (Parameter=1). Call `basename $0` " >&2
  exit 2
fi


#
# Setup Environment:
#

pkg_env="${HOME}/bin/_conf/.env"
if [ ! -r "${pkg_env}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Not Found Environment file: ${pkg_env}" >&2
  exit 2
fi

if [ -s "${pkg_env}" ]; then
  . ${pkg_env}
else
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Environment file is empty: ${pkg_env}" >&2
  exit 2
fi


#
# Check Environment:
#


# Check ORACLE_USER:
if [ -z "${ORA_USER}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Environment variable ORA_USER not defined" >&2
  exit 2
else
  ora_user=${ORA_USER}
fi

# Check Database Instance:
loc_status=`ps -fu ${ora_user} | grep -w "ora_[a-z]*_${oracle_sid}"`
loc_res=$?

if [ ${loc_res} -eq 0 ]; then
  echo "Database Instance OK"
else
  echo "Error! Not found Database Instance."
  exit
fi


# Check ORACLE_HOME:
if [ -z "${ORACLE_HOME}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Environment variable ORACLE_HOME not defined" >&2
  exit 2
elif [ ! -d "${ORACLE_HOME}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Directory ORACLE_HOME not found (${ORACLE_HOME})" >&2
  exit 2
fi


# Check TMP_DIR:
if [ -z "${TMP_DIR}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Environment variable TMP_DIR not defined" >&2
  exit 2
elif [ ! -d "${TMP_DIR}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Directory TMP_DIR not found (${TMP_DIR})" >&2
  exit 2
elif [ ! -w "${TMP_DIR}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Directory TMP_DIR not writeable (${TMP_DIR})" >&2
  exit 2
fi


# Check BIN_DIR:
if [ -z "${BIN_DIR}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Environment variable BIN_DIR not defined" >&2
  exit 2
elif [ ! -d "${BIN_DIR}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Directory BIN_DIR not found (${BIN_DIR})" >&2
  exit 2
fi


# Check COMPANY_NAME:
if [ -z "${COMPANY_NAME}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Environment variable COMPANY_NAME not defined" >&2
  exit 2
fi


# Check HOST_NAME:
if [ -z "${HOST_NAME}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Environment variable HOST_NAME not defined" >&2
  exit 2
fi


# Check MAIL_RECIPIENTS:
if [ -z "${MAIL_DBA}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Environment variable MAIL_RECIPIENTS not defined" >&2
  exit 2
fi


# Check UTL_SEND:
if [ -z "${UTL_SEND}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. Environment variable UTL_SEND not defined" >&2
  exit 2
elif [ ! -f "${UTL_SEND}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. File UTL_SEND not found (${UTL_SEND})" >&2
  exit 2
elif [ ! -x "${UTL_SEND}" ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: ERROR!!! Execution Aborted. File UTL_SEND not executable (${UTL_SEND})" >&2
  exit 2
fi



# Initialize Package:

pkg_flag="`basename $0 .sh`"
run_in_progress=${TMP_DIR}/${pkg_name}_${oracle_sid}.lock
log_file=${TMP_DIR}/${pkg_name}_${oracle_sid}.log
prefix="${COMPANY_NAME}#${HOST_NAME}(${oracle_sid}) ${pkg_name}"
mess_theme="${prefix}: Error! Another process running (${run_in_progress})"
mess_header="Gather Statistics"

mail_recipients="${MAIL_DBA}"
echo $mail_recipients


# Check Another process for running:
if [ -f ${run_in_progress} ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: Error! Another process running. Remove a file ${run_in_progress}" >&2
  echo "Remove a file ${run_in_progress}" | ${BIN_DIR}/_lib/utl_send.sh "${mess_theme}" "${mail_recipients}"
  exit 2
fi


# Prevent Parallel Execution:
touch ${run_in_progress}


# Run Implementation:
${BIN_DIR}/pkg/${pkg_name}/body.sh "${pkg_flag}" "${oracle_sid}" | tee ${log_file}


# Send E-Mail:
mess_theme="${prefix}: ${mess_header}"
cat ${log_file} | ${BIN_DIR}/_lib/utl_send.sh "${mess_theme}" "${mail_recipients}"


# Cleanup Stop Flag:
test -r ${run_in_progress} && rm ${run_in_progress}
:t5:~/bin$



:t5:~/bin$more ${HOME}/bin/pkg/gather_statistics/body.sh
#!/bin/bash


#
# Check Parameters:
#

# Package Name:
tmp_string="`dirname $0`"
pkg_name="`basename ${tmp_string}`"

if [ "${pkg_name}" = "." ]; then
  tmp_string="`pwd`"
  pkg_name="`basename ${tmp_string}`"
fi

# Check for internal call:
if [ ! $1 = '_run' ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: Error! (Parameter=1) Call `basename $0` from ./_run.sh" >&2
  exit 2
fi


# Check For :
if [ $2 ]
then
  echo " 2=${2} (ORACLE_SID)"
  ORACLE_SID=`echo ${2} | tr "[A-Z]" "[a-z]"`; export ORACLE_SID
else
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: Error! (Parameter=2) Call `basename $0` With 2-d parameter" >&2
  exit 2
fi


#
# Define local variables:
#

# Variables:

oracle_sid=${ORACLE_SID}
prefix="${COMPANY_NAME}#${HOST_NAME}(${oracle_sid}) ${pkg_name}"
mess_theme="${prefix}: ${mess} Warning! Collect statistics"
temp_file=${TMP_DIR}/${pkg_name}_${oracle_sid}.tmp

mail_recipients="${MAIL_DBA}"
echo ${mail_recipients}

# Block-01:
echo "`date +%T` (${ORACLE_SID}) Begin  - Collect Schema statistics for  SYS, SYSTEM, fixed_objects"

sqlplus -s / as sysdba << EOF
  set serveroutput on size 3000
  set linesize 120
  set echo off
  set head off
  set feed off


  --begin
  --  dbms_stats.gather_schema_stats(
  --    ownname          => 'SYS',
  --    estimate_percent => 10,
  --    method_opt       => 'FOR ALL INDEXED COLUMNS',
  --    cascade          => TRUE
  --  );
  --exception
  --  when others then
  --    dbms_output.put_line('ERROR(SYS): ' || sqlerrm());
  --end;
  --/

  --begin
  --  dbms_stats.gather_schema_stats(
  --    ownname    => 'SYSTEM',
  --    method_opt => 'FOR ALL INDEXED COLUMNS',
  --    cascade    => TRUE
  --  );
  --exception
  --  when others then
  --    dbms_output.put_line('ERROR(SYSTEM): ' || sqlerrm());
  --end;
  --/

  --begin
  --  dbms_stats.gather_fixed_objects_stats;
  --exception
  --  when others then
  --    dbms_output.put_line('ERROR(gather_fixed_objects_stats): ' || sqlerrm());
  --end;
  --/


  --begin
  --  dbms_stats.gather_system_stats;
  --exception
  --  when others then
  --    dbms_output.put_line('ERROR: ' || sqlerrm());
  --end;
  --/
EOF

echo "`date +%T` (${ORACLE_SID}) Finish - Collect Schema statistics for  SYS, SYSTEM, fixed_objects"
echo " "


# Block-06:
#echo "`date +%T` (${ORACLE_SID}) Begin  - Metalink Note: 420200.1"

#sqlplus -s / << EOF
#  set serveroutput on size 3000
#  set linesize 120
#  set echo off
#  set head off
#  set feed off
#
#  --Subject:  Poor performance when accessing V$RMAN_BACKUP_JOB_DETAILS (Metalink_Note:420200.1)
#  begin
#    dbms_stats.UNLOCK_TABLE_STATS('SYS','X\$KCCRSR');
#    dbms_stats.DELETE_TABLE_STATS('SYS','X\$KCCRSR');
#    dbms_stats.LOCK_TABLE_STATS('SYS','X\$KCCRSR');
#  exception
#    when others then
#      dbms_output.put_line('ERROR: ' || sqlerrm());
#  end;
#  /
#EOF
#
#echo "`date +%T` (${ORACLE_SID}) Finish - Metalink Note: 420200.1"
#echo " "



# Block-07:
echo "`date +%T` (${ORACLE_SID}) Begin  - Collect Individual Schema Statistics"
if [ -f ${BIN_DIR}/pkg/${pkg_name}/special_stat_${ORACLE_SID}.sh ]; then
   ${BIN_DIR}/pkg/${pkg_name}/special_stat_${ORACLE_SID}.sh ${ORACLE_SID}
else
  mailx -s "${HOST_NAME}(${ORACLE_SID}): Extended Statistics Script - Not Found" ${mail_recipients}
fi

echo "`date +%T` (${ORACLE_SID}) Finish - Collect Individual Schema Statistics"
echo " "


# :
echo "`date +%T` (${ORACLE_SID}) End    - Collect Statistics."
echo " "
:t5:~/bin$





:t5:~/bin$more ${HOME}/bin/pkg/gather_statistics/body.sh
#!/bin/bash


#
# Check Parameters:
#

# Package Name:
tmp_string="`dirname $0`"
pkg_name="`basename ${tmp_string}`"

if [ "${pkg_name}" = "." ]; then
  tmp_string="`pwd`"
  pkg_name="`basename ${tmp_string}`"
fi

# Check for internal call:
if [ ! $1 = '_run' ]; then
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: Error! (Parameter=1) Call `basename $0` from ./_run.sh" >&2
  exit 2
fi


# Check For :
if [ $2 ]
then
  echo " 2=${2} (ORACLE_SID)"
  ORACLE_SID=`echo ${2} | tr "[A-Z]" "[a-z]"`; export ORACLE_SID
else
  echo "`date +%Y.%m.%d" "%H:%M:%S` - ${pkg_name}: Error! (Parameter=2) Call `basename $0` With 2-d parameter" >&2
  exit 2
fi


#
# Define local variables:
#

# Variables:

oracle_sid=${ORACLE_SID}
prefix="${COMPANY_NAME}#${HOST_NAME}(${oracle_sid}) ${pkg_name}"
mess_theme="${prefix}: ${mess} Warning! Collect statistics"
temp_file=${TMP_DIR}/${pkg_name}_${oracle_sid}.tmp

mail_recipients="${MAIL_DBA}"
echo ${mail_recipients}

# Block-01:
echo "`date +%T` (${ORACLE_SID}) Begin  - Collect Schema statistics for  SYS, SYSTEM, fixed_objects"

sqlplus -s / as sysdba << EOF
  set serveroutput on size 3000
  set linesize 120
  set echo off
  set head off
  set feed off


  --begin
  --  dbms_stats.gather_schema_stats(
  --    ownname          => 'SYS',
  --    estimate_percent => 10,
  --    method_opt       => 'FOR ALL INDEXED COLUMNS',
  --    cascade          => TRUE
  --  );
  --exception
  --  when others then
  --    dbms_output.put_line('ERROR(SYS): ' || sqlerrm());
  --end;
  --/

  --begin
  --  dbms_stats.gather_schema_stats(
  --    ownname    => 'SYSTEM',
  --    method_opt => 'FOR ALL INDEXED COLUMNS',
  --    cascade    => TRUE
  --  );
  --exception
  --  when others then
  --    dbms_output.put_line('ERROR(SYSTEM): ' || sqlerrm());
  --end;
  --/

  --begin
  --  dbms_stats.gather_fixed_objects_stats;
  --exception
  --  when others then
  --    dbms_output.put_line('ERROR(gather_fixed_objects_stats): ' || sqlerrm());
  --end;
  --/


  --begin
  --  dbms_stats.gather_system_stats;
  --exception
  --  when others then
  --    dbms_output.put_line('ERROR: ' || sqlerrm());
  --end;
  --/
EOF

echo "`date +%T` (${ORACLE_SID}) Finish - Collect Schema statistics for SYS, SYSTEM, fixed_objects"
echo " "


# Block-06:
#echo "`date +%T` (${ORACLE_SID}) Begin  - Metalink Note: 420200.1"

#sqlplus -s / << EOF
#  set serveroutput on size 3000
#  set linesize 120
#  set echo off
#  set head off
#  set feed off
#
#  --Subject:  Poor performance when accessing V$RMAN_BACKUP_JOB_DETAILS (Metalink_Note:420200.1)
#  begin
#    dbms_stats.UNLOCK_TABLE_STATS('SYS','X\$KCCRSR');
#    dbms_stats.DELETE_TABLE_STATS('SYS','X\$KCCRSR');
#    dbms_stats.LOCK_TABLE_STATS('SYS','X\$KCCRSR');
#  exception
#    when others then
#      dbms_output.put_line('ERROR: ' || sqlerrm());
#  end;
#  /
#EOF
#
#echo "`date +%T` (${ORACLE_SID}) Finish - Metalink Note: 420200.1"
#echo " "



# Block-07:
echo "`date +%T` (${ORACLE_SID}) Begin  - Collect Individual Schema Statistics"
if [ -f ${BIN_DIR}/pkg/${pkg_name}/special_stat_${ORACLE_SID}.sh ]; then
   ${BIN_DIR}/pkg/${pkg_name}/special_stat_${ORACLE_SID}.sh ${ORACLE_SID}
else
  mailx -s "${HOST_NAME}(${ORACLE_SID}): Extended Statistics Script - Not Found" ${mail_recipients}
fi

echo "`date +%T` (${ORACLE_SID}) Finish - Collect Individual Schema Statistics"
echo " "


# :
echo "`date +%T` (${ORACLE_SID}) End    - Collect Statistics."
echo " "
:t5:~/bin$




:t5:~/bin$more ${HOME}/bin/pkg/gather_statistics/special_stat_testdb.sh
#!/bin/bash


# Check Parameters:
if [ ${1} ]; then
  ORACLE_SID=`echo ${1} | tr "[A-Z]" "[a-z]"`; export ORACLE_SID
else
  echo "usage:  SID"
  exit
fi



# Block-Ext-01:
echo "`date +%T` (${ORACLE_SID}) Begin  - Collect statistics for schema SCOTT"

sqlplus -s / << EOF
  set serveroutput on size 3000
  set linesize 120
  set echo off
  set head off
  set feed off

  begin
    dbms_stats.gather_schema_stats(
      ownname          => 'SCOTT',
      estimate_percent => 100,
      method_opt       => 'FOR ALL COLUMNS SIZE 1',
      granularity      => 'all',
      cascade          => TRUE
    );
  exception
    when others then
      dbms_output.put_line('ERROR: ' || sqlerrm());
  end;
  /

  -- :
  select 'min(last_analyzed)=' || min(last_analyzed) from dba_tables where owner='SCOTT';

  --#
  --#
  --#
  --analyze table scott.t1       DELETE STATISTICS;
  --analyze table scott.t2       DELETE STATISTICS;

  -- :
  exit
EOF

echo "`date +%T` (${ORACLE_SID}) Finish - Collect statistics for schema SCOTT"
echo " "
:t5:~/bin$







:t5:/u01/app/oradb/product/11.2.0.3/dbhome_1/dbs$strings spfiletestdb.ora
testdb.__oracle_base='/u01/app/oradb'#ORACLE_BASE set from environment
*.archive_lag_target=900
*.audit_sys_operations=TRUE
*.audit_trail='DB'
*.compatible='11.2.0.0.0'
*.control_files='+DATA/testdb_p/controlfile/current.256.807962603','+REDO/testdb_P/CONTROLFILE/current.271.815999063'
*.control_management_pack_access='DIAGNOSTIC+TUNING'
*.db_block_size=8192
*.db_cache_size=32212254720
*.db_create_file_dest='+DATA'
*.db_create_online_log_dest_1='+REDO'
*.db_domain='sun.com'
*.db_files=1024
*.db_name='testdb'
*.db_recovery_file_dest='+RECO'
*.db_recovery_file_dest_size=549755813888
*.db_unique_name='testdb_p'
*.dg_broker_start=TRUE
*.diagnostic_dest='/u01/app/oradb'
*.dispatchers='(PROTOCOL=TCP) (SERVICE=testdbXDB)'
*.fal_server='testdb_s1.sun.com'
*.fast_start_mttr_target=300
*.fast_start_parallel_rollback='LOW'
*.java_pool_size=268435456
*.job_queue_processes=30
*.large_pool_size=268435456
*.log_archive_config='dg_config=(testdb_p,testdb_s1)'
*.log_archive_dest_1='LOCATION=USE_DB_RECOVERY_FILE_DEST VALID_FOR=(ALL_LOGFILES, ALL_ROLES)'
*.log_archive_dest_2='service="testdb_s1.sun.com"','LGWR ASYNC NOAFFIRM delay=0 optional compression=disable max_failure=0 max_connections=1 reopen=300 db_unique_name="testdb_s1" net_timeout=30','valid_for=(all_logfiles,primary_role)'
*.log_archive_dest_state_2='ENABLE'
*.log_archive_format='%t_%s_%r.arc'
testdb.log_archive_format='%t_%s_%r.arc'
*.log_archive_max_processes=4
*.log_archive_min_succeed_dest=testdb.log_archive_trace=0
*.open_cursors=500
*.os_authent_prefix='OSP$'
*.pga_aggregate_target=4294967296
*.processes=500
*.remote_login_passwordfile='EXCLUSIVE'
*.sec_case_sensitive_logon=FALSE
*.shared_pool_reserved_size=209715200
*.shared_pool_size=2147483648
*.standby_file_management='AUTO'
*.undo_retention=36000
*.undo_tablespace='UNDOTBS1'
:t5:/u01/app/oradb/product/11.2.0.3/dbhome_1/dbs$