I am trying to make a bash script that will calculate the time difference between the users' first logon and the users most recent logon. Any help is appreciated :)
This is what I have so far:
read -p "Enter a user ID: " ID
echo "You entered the following ID(s): $ID"
#/bin/egrep -i "^$ID" /etc/passwd
echo -n "The users real name is: "
/bin/grep "^$ID" /etc/passwd | cut -f5 -d :
echo -n "$ID's first login time is: "
l1=`last "$ID" | tail -n 1`
echo -n "$ID's last login time is: "
l2=`last "$ID" | head -n 1`
echo $l1
echo $l2
echo -n "The time difference is $(l1-l2) "
This is based off the assumption you want to provide a username and not an ID.
Firstly, you want to perform your captures correctly
l1=$(last "$ID" | tail -n 1)
l2=$(last "$ID" | head -n 1)
in my instance left
l1="wtmp begins Sun Nov 9 07:32:12 2014"
l2="graham pts/11 :0 Sat Nov 29 22:13 still logged in"
which is no good since we need only dates
So let's fix that. Here's some hacky parsing to get only times:
l1=$(last -RF | grep $ID | tail -n 1 | tr -s ' ' | cut -d ' ' -f 3,4,5,6)
l2=$(last -RF "$ID" | head -n 1 | tr -s ' ' | cut -d ' ' -f 3,4,5,6)
I grep for l1 because last leaves the last logged in, but for consistency, I just grab the last row. last -RF removes the host (-R), since we're not interested and makes the time a bit nicer (-F). tr trims all additional spaces and cut, delimited by a blank, grabs the date.
We want to compute the time between, so let's change both to datetime strings and subtract:
a=$(date -ud "$l2" +"%s")
b=$(date -ud "$l1" +"%s")
d=$(( a-b ))
Finally let's print
echo "$ID's last login time is: $l1"
echo "$ID's first login time is: $l2"
echo "The time difference is $d seconds"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With