Showing posts with label shell. Show all posts
Showing posts with label shell. Show all posts

Wednesday, June 19, 2013

Script to calculate the logIn time in linux

This is could be very useful when you need to calculate the logIn time for attendance/swipes. Here it goes.


#!/bin/bash

. ~/.bash_functions

function updateLogInTime()
{
    file=$1
    fullDate=`date +"%d-%m-%Y %H:%M:%S"`
    today=`date +"%d-%m-%Y"`;
    todayEntry=`grep $today $1`;
    now=`date +"%H:%M:%S"`;
    nowInSecs=`tounixtime`
    if [ -z "$todayEntry" ]; then
       echo "UpdatedAt: $fullDate, In: $now/$nowInSecs, Out: $now/$nowInSecs, Total: `date -u -d @"0" +'%-H:%-M:%-S'`" >> $file;
    else
       tokens=( `getTokens "$todayEntry" ,` )
       # use for loop read all fields
       for (( i=0; i<${#tokens[@]}; i++ ))
       do
           token=${tokens[i]}
           case $token in
                UpdatedAt:)
                        updatedTodayEntry="$updatedTodayEntry $token $fullDate";;
                In:)
                        inTimeToken=${tokens[i+1]};
                        inTimeTokens=( `getTokens "$inTimeToken" /` );
                        inTime=${inTimeTokens[1]};
                        updatedTodayEntry="$updatedTodayEntry, $token $inTimeToken";;
                Out:)
                        updatedTodayEntry="$updatedTodayEntry, $token $now/$nowInSecs";;
                Total:)
                        diff=`calc $nowInSecs-$inTime`;
                        updatedTodayEntry="$updatedTodayEntry, $token `date -u -d @"$diff" +'%-H:%-M:%-S'`";;
           esac
       done
       updatedTodayEntry=`trim $updatedTodayEntry`
       sed -i s%"${todayEntry}"%"${updatedTodayEntry}"%g $file
    fi
}

function main()
{
     screenLocked=`isScreenLocked`;
     if [ $screenLocked -eq 0 ]; then
        updateLogInTime /krishna/Misc/Notifications/data/logInTime.db
     fi
}

main

Happy Coding!

Thursday, October 11, 2012

Shell script Tips - Using functions and Executing a java process as background one

It is small shell script which teach you about the things, that we use in our routine shell scripting life.
They are:
1) Functions.
2) Resolving the current path ro absolute path.
3) Blinking Text.
4) Proper usage of log.
5) Executing a java process in back ground.
6) Usage of ps and grep commands.
7) Proper code formation.

#!/bin/bash

########
# This is to log the events to a file in events directory, monitors and manages the java process which
# actually reads  the files and sends the events to third party for processing. 
#
# It also demonstrates the usage and handling of certain features defined in *ix kernal.
#
# @author Rajakrishna V. Reddy
# @version 1.0
#
########

### CONSTANTS may be changed over a time ###
jarName=arcsight-integration-1.0.jar
javaLogFileName=javaProcess.log
scriptLogFileName=script.log
javaFileName=com.mt.arcsight.ArcsightManager
NOW=`date +"%y-%m-%d %H:%M:%S"`


### Variables to be defined or automatically get defined by script as it is flowing ###
myName=$(readlink -fn $(type -p $0))
currentDir=$(dirname $myName)
eventDir=$currentDir/../events
logDir=$currentDir/../log
confDir=$currentDir/../conf
binDir=$currentDir
eventFileName=
event=
keyValuePairLength=

### Logging the text in blinking mode, and set it back to normal mode after display ###
function blinkingLog
{
        echo -e "[$NOW] [ArcsightServer] [INFO]: $* \033[0m"
}

### Creates all the required dirs, if doesn't exists ###
function makeAllDris
{
makeDir $eventDir
makeDir $logDir
makeDir $confDir

eventDir=$(cd $currentDir/../events && pwd)
logDir=$(cd $currentDir/../log && pwd)
confDir=$(cd $currentDir/../conf && pwd)
}

### Creates a dir, if doesn't exists ###
function makeDir
{
if [ ! -d $1 ]; then
#echo "Events dir is not exists, going to create: $eventDir";
mkdir $1
#echo "Created the event dir successfully: $eventDir";
return 1;
fi
}
### Just check and create the event dir ###
function checkAndCreateEventDir
{
if [ ! -d $eventDir ]; then
#echo "Events dir is not exists, going to create: $eventDir";
mkdir $eventDir
#echo "Created the event dir successfully: $eventDir";
return 1;
fi
}

### Just check and create the log dir ###
function checkAndCreateLogDir
{
        if [ ! -d $logDir ]; then
blinkingLog "\033[31m Log dir does not exists, \033[32mgoing to create it: $logDir"
                mkdir $logDir
                blinkingLog " Created the event dir successfully: $logDir";
        fi
if [ ! -f $logDir/$javaLogFileName ]; then
blinkingLog "\033[31m Log dir does not exists, \033[32mgoing to create it: $logDir/$javaLogFileName"
touch $logDir/$javaLogFileName;
chmod +w $logDir/$javaLogFileName;
       blinkingLog " Log file created successfully: $logDir/$javaLogFileName";
fi
}

### Get the present events count and get the desired filename by using the next event number ###
function checkAndCreateNextEventFile
{
fileCount=`ls -ltr $eventDir | wc -l`;

#Contains total number of files + "total 0", hence it gets the number of files + 1, which will be our next file number;
#fileCount=`expr $fileCount - 1`;

eventFileName=$fileCount.'event';
#echo "The next event file name is: $eventFileName";
touch $eventDir/$eventFileName;
chmod +w $eventDir/$eventFileName;
#echo "Event file is created successfully: $eventFileName."
}

### Write the content into the specified file, decided by checkAndCreateNextEventFile function. ###
function writeAnEvent
{
#blinkingLog "\033[05m Writing the given event into $eventDir/$eventFileName";
#blinkingLog "\033[05m Writing the event: $event"
checkAndCreateEventDir
checkAndCreateNextEventFile
echo "$event" > $eventDir/$eventFileName;
}

### Manages the java process by checking and starting it if not already running ###
function manageJavaProcess
{
        checkAndCreateLogDir
        pid=`ps -ef | grep -i $javaFileName | grep -v grep | awk '{print $2}'`
        if [ -z "$pid" -o "$pid" == " " ]; then
                blinkingLog " Checking the status of java app: \033[31m Process: $javaFileName is down..!!! \033[32mstarting it.!"
                java -cp $PATH:$currentDir/arcsight-integration-1.0.jar com.mt.arcsight.ArcsightManager $confDir/arcsight.properties > $logDir/$javaLogFileName 2>&1 &
sleep 0.1
        pid=`ps -ef | grep -i $javaFileName | grep -v grep | awk '{print $2}'`
blinkingLog "\033[32m Process $javaFileName is started with pid: $pid";
        else
                blinkingLog " Checking the status of java app: \033[32m Process $javaFileName is running with pid: $pid";
        fi
}

### Starting method of your process ###
function main
{
event=$*
keyValuePairLength=$#

makeAllDris
blinkingLog "\033[35m **** Sending the event to MWatch. ****";
manageJavaProcess
writeAnEvent
blinkingLog "\033[35m **** Sent the event to MWatch successfully. ****";
}

### Starting point of your process ###
main $*

Tuesday, October 9, 2012

Unix in a nut shell-1


1) Getting the Absolute Path in the shell script:

scriptFile=$(readlink -fn $(type -p $0))
echo "Absolute path: $scriptFile"

1) Reading ALL the command-line params in the shell script:

Shell script accepts parameters in following format... 
$1 : first 
$2 : second....so on upto  9th param,
$9 : 9th param 

whereas $0 : gives script/function name 

If your script has more than 9 params then !???? :( :( 

No worries ... just access them in following way... 
${12} : 12th param 
${18} : 18th param