Bash – List logged in users (name, terminal, logintime)

bashshell-scriptuserswho

I'm trying to print a list of users, who are currently logged on a terminal. It should look like this:

enter image description here

I only got this so far:

enter image description here

I'm missing the Terminal and the Login time. How can I display them? This is what I got so far:

#!/bin/bash
NOWDATE=$(date +"%Y-%m-%d")
NOWTIME=$(date +"%T")
USERS=$(who | cut -d " " -f1)
TERMINAL=0
LOGIN=0

for u in $USERS
do
    echo "$NOWDATE""_""$NOWTIME User: " $u
done

Best Answer

Parsing the output of w is probably a better approach than who. Here are some representative data, which shows the login time:

$ who
tom      pts/1        2015-11-15 06:39 (michener:S.0)
$ w
 06:40:10 up  1:04,  1 user,  load average: 0.00, 0.01, 0.05
USER     TTY      FROM             LOGIN@   IDLE   JCPU   PCPU WHAT
tom      pts/1    michener:S.0     06:39    2.00s  0.03s  0.00s w

Those are more widely available than finger. Since this is a classroom exercise, parsing the data is left to OP. As a hint, awk can do more than print its fields in a one-liner:

  • Typically, one would handle the output of w by having in the awk script a BEGIN section (to set a line-number or state).
  • Then, a default action for each line (just curly braces with no pattern) would increment the line number.
  • Using the line number, handle the first line specially (skip it in this case: OP may need the number of users for a report header, but that is not used in OP's example), and skip the line with USER.
  • After that, each line can be printed as OP needs. awk will quit when there is no more data; it is not necessary to know the number of users to do this.

If OP is told to use who, that has options to list more information, e.g.,

$ who -l -u
LOGIN    tty5         2015-11-15 05:36              3670 id=5
LOGIN    tty6         2015-11-15 05:36              3671 id=6
LOGIN    tty4         2015-11-15 05:36              3669 id=4
LOGIN    tty3         2015-11-15 05:36              3668 id=3
LOGIN    tty2         2015-11-15 05:36              3667 id=2
LOGIN    tty1         2015-11-15 05:36              3666 id=1
tom      pts/1        2015-11-15 06:39 00:06        5780 (michener:S.0)
tom      pts/2        2015-11-15 06:52   .          6078 (michener:S.1)

again, showing the terminal name and the login times.