Linux/Unix Parameterized Shell Script to Archive logs

You have already known about the tradition but more effective log archiving script, if you don’t then you might want to check this script first.

In case if you have many different jobs running and they are creating huge files under its individual directory then let’s modify little bit our script so we can use the same script for all the jobs instead of creating multiple script

 

PARAMETERIZED UNIX/LINUX SHELL SCRIPT

This is very easy way of reusing your script just by-passing parameter outside from the script. We need to provide the parameter(s) while running the script.

In our example, lets consider we have multiple directories under /local/apps/BatchServer/

You can make this script very generic by passing “directory name”. Assume, you have sub-directories like –  MyDIStudioJob_1MyDIStudioJob_2MyDIStudioJob_3, etc. You can pass these directory name from outside and it is referred and replaced by  $1 in the script.

 

Now your LEVROOT will become –  LEVROOT=/local/apps/BatchServer/$1

PS- Make sure you have Log and Archive folders created under each sub-directory.

 

LOG ARCHIVING SCRIPT

 

#——————————————————

# Script for archiving of logs 

# Script         : logs_Archive.sh

# Parameter   : $1: Sub-directory Name

# 02-01-2019 : Linux/Unix Admin

#——————————————————-

#!/bin/sh

# Varibales Used:

 

LEVROOT=/local/apps/Batchserver/$1

DATE=$(date +%d%m%y)

TIME=$(date +%H%M)

ARCHIVE=”$LEVROOT/Archive/$DATE-$TIME”

LOG=”$LEVROOT/”

 

find $LEVROOT/Archive/* -mtime +7 -type d -print -exec rm -R {} ;

 

mkdir $ARCHIVE

find $LOG -type f -print -exec mv {} $ARCHIVE ;

 

echo $ARCHIVE

echo $LOG

 

EXECUTE SCRIPT

Let’s say you want to run this script for job number 1 which has logs generated under subdirectory MyDIStudioJob_1

      ./logs_Archive.sh MyDIStudioJob_1

Or may be you want to run for Job number 3 as –

      ./logs_Archive.sh MyDIStudioJob_3 

 

PS: This script is all about moving the long files into Archive and clean up there. But if you have job or application running 24/7 then you can’t move your log files from original directory. You may want to check this best possible solution here in another blog post to handle such scenarios. 

 

1 thought on “Linux/Unix Parameterized Shell Script to Archive logs”

Leave a Comment