Skip to main content
Bash Scripting

A better lastlog — Bash Scripting

By April 16, 2013No Comments

The output of lastlog is useful and shows you all the users and the date and time of their last login. Firstly though, we need to filter out the system accounts who never login. This is easy with grep -v “Never logged in”. More importantly we need to know how to compare two dates in Linux so we can show how many days ago users logged in.

Dates in Linux are the number of seconds after 1 Jan 1970, date +%s will show you this for the current date and time. We can then take the date for each user in lastlog and show their last log in time in seconds and subtract it from the current date and time.

for U in $( lastlog | grep -v "Never logged in"| awk '{ print $1 }'| tail -n +2)
do
  NOW=$(date +%s)
  USR=$(lastlog | grep -v 'Never logged in' | awk '{ print $1,":",$5,$6,$9 }'|grep $U)
  USRDATE=$(echo $USR | cut -d":" -f2)
  (( USRDATE = $(date --date "$USRDATE" +%s) / 86400 ))
  (( NOW = NOW / 86400 ))
  (( DAYS = NOW - USRDATE ))
  echo "The user $U: logged in $DAYS days ago"
done

It may not look the easiest to read but we first create a list of users for our for loop. Inside the loop we set the current date and time in the epoch format and search for the current user (in the loop) last login time. Dividing by 86400 gives us days instead of seconds and we delete the last login time from the current. Then we display all of the users and the number of days since their last log in.