loop through logged on users or file?

Hi

I'm trying to loop through all logged on users and get their real names

So I came up with this script but it doesn't work

Who > userList #save logged on users to temp file
while read username #loop through file
do
awk '{ print $1 }' | grep /etc/passwd | cut -d: -f5
done < userList

# awk '{ print $1 }' | grep /etc/passwd | cut -d: -f5 basically gets the login name from each line in userList and gets the real name from the matching line in /etc/passwd but this doesn't work

Can someone please direct me to the right way of doing this?

I'm using bash shell

The finger command will give you real name..

man finger

Thanks, but how do I loop through each logged on users and extract their real names?

#!/bin/ksh

who | while read user junk
do
    nawk -F: -v user="${user}" '$1 == user { print $5; exit }'
done
#!/bin/ksh
who | while read user junk
do
   realname=`grep $user /etc/passwd | awk ' { FS=":"; print $5}'`
   print "User Id - $user and real name - $realname. \n"
done

why do you have both 'grep' and 'awk AND why do you have 'FS' inside the curly braces??'

Thanks, this worked for me:

who | while read user junk
do
realname=`grep $user /etc/passwd | cut -d: -f5`
echo "User Id = $user and real name - $realname. \n"
done

Why use awk or grep at all?

#! /bin/ksh
oldifs="$IFS"; IFS=:
 while read _user _ _ _ _realname _; do
  print $_user - $_realname
 done </etc/passwd
IFS="$oldifs"; unset oldifs

It's faster too...

it may be faster but it doesn't adress the question posed in the original question. The question asked was the list the full names of logged in users, not all users.

Do'h...
Well, it's not pretty, and won't work if the user field in "who" truncates long user names (as is the case on at least one system I work with,) but should be more or less portable between ksh, bash, and other modern POSIX shells:

#! /bin/ksh

# Build name->GECOS vars
oldifs="$IFS"; IFS=:
while read _user _ _ _ _realname _; do
 eval lookup_${_user}=\"$_realname\"
done </etc/passwd
IFS="$oldifs"; unset oldifs

# Loop through $(who)
who -s | while read _whoname _ ; do
 eval echo \$lookup_${_whoname} is online
done

You may get trickier with perl or ksh93, but this works in most cases.

Hi,

Did you check whether those username are present in /etc/passwd ?

this's an overkill.
Try this paradigm:

#! /bin/ksh

# Build name->GECOS vars
while IFS=: read _user _ _ _ _realname _; do
 eval lookup_${_user}=\"$_realname\"
done </etc/passwd

Mine doesn't take that into account, so if you're using, say LDAP, you'll need to gather the names another way.