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!