Script to list users and their last login?

hi all,

I'm trying to write a script to create a file with a list of all users, their gid, gecos field and their last login time

e.g.

fairly new to scripting, this is what I've got so far

#!/bin/sh( userlist= cat /etc/passwd  | awk -F: '{print $1," ",$4," ",$5}'  
 for name in $userlist   
 do login= last -1 $name   
 echo $name $login >> `hostname`_userlogins.txt   done)

The output of the first part is fine but I can't get the loop and last command working, and need to append the output of 'last -1' for each user to the end of their 'line'

Any help would be greatly appreciated!

Rearranging your script a bit. Could not see a sensible use of "for" but you can make good use of "while" to give you a per-user loop.
Don't know what Operating System you have of what Shell is "/bin/sh" on your computer.
This script may or may not need modification for your Shell.
On my computer "last -1" outputs unwanted text if the user has not logged in since the wtmp file was last reset - hence the extra grep to see if "last -1" replied with what we wanted.

#!/bin/sh
(
cat /etc/passwd | awk -F: '{print $1,$4,$5}' | sort | \
while read username gid gecos
do
        last_login=`last -1 ${username}|grep \^${username}|awk '{print $4,$5}'`
        echo "${username} ${gid} ${gecos} ${last_login}"
done
) > `hostname`_userlogins.txt
1 Like

Thanks Methl,

that works a treat!

Apologies for the original post, we're only ion IE6 at work and it wouldn't format the post correctly :frowning: