Amantha
Amantha

Reputation: 17

Bash Script Doesn't run properly when closing the terminal

following Bash Script runs properly when I execute the exit command.

#!/bin/bash
user=$(echo $(who am i) | awk '{print $1" "$5" "$3" "$4}')
formattedUser=$(echo $user | tr -d '()')
finalData=$formattedUser" to "$(date +"%Y-%m-%d")" "$(date +"%H:%M")
logoutTime=$(date +"%m/%d/%Y %H:%M")":00"
startDate=$(echo $(who am i) | awk '{print $3}')
startDateFinal=$(echo $startDate | tr '-' '/')
startTime=$(echo $(who am i) | awk '{print $4}')
startTimeFinal=$startTime":00"
loginTime=$startDateFinal" "$startTimeFinal

function diff_seconds {
    var1=$(date "+%s" -d "$1");
    var2=$(date "+%s" -d "$2");
    period=$(( $var1 - $var2 ));
}

diff_seconds "$logoutTime" "$loginTime"
periodMins=$(echo $(( period / 60 )))
finalDataToLog=$finalData" "$periodMins
echo $finalDataToLog | tee -a /home/amantha/log-sources/logout.log
chmod 777 /home/amantha/log-sources/logout.log

I included above bash script in .bashrc.

trap /home/amantha/log-sources/logout.sh EXIT

You can see the output below.

amantha 192.168.1.36 2020-10-05 10:29 to 2020-10-05 10:31 2

1st field - user 2nd field - user ip 3rd field - logged in date 4th field - Logged in time 5th filed - "to" word 6th field - logged out date 7th Field - logged out time 8th field - time period

The issue is when i close terminal it doesn't work properly. Output:

to 2020-10-05 10:28 0

My purpose of doing this to determine a user's logged in time and logged out time using ssh. Do you have any solutuon? Above one is worked only for exit command. It doesn't work properly when I close terminal or Connection Failiure.

Upvotes: 0

Views: 340

Answers (1)

Dudi Boy
Dudi Boy

Reputation: 4865

You are trying to solve a solved problem.

If you are using RHEL/CENTOS/Fedora. The user's log are stored in:

/var/log/wtmp – Logs of last login sessions
/var/run/utmp – Logs of the current login sessions
/var/log/btmp – Logs of the bad login attempts

There is also last command. That is well documented here. Here is a good article solving your problem.

Upvotes: 1

Related Questions