7

The who command can be used to find logged-in users, but it prints duplicate values if there are multiple shells running. How do I get a list of the currently logged-in users without duplicates?

2
  • It should not print duplicate values unless you open multiple tty and log in. However who -q might be what you look for, but not sure, have no way to test on a system hosting multiple simultaneous users.
    – Videonauth
    Nov 20, 2017 at 5:23
  • who -q prints total number and users. Shall we use sort | uniq?
    – Anony
    Nov 20, 2017 at 5:25

1 Answer 1

9

We can pipe the output of who to awk to print only the first cell of each record (row) and then pipe it to the command sort, that will sort the values alphabetically and will output only the unique -u entries:

who | awk '{print $1}' | sort -u

Or we can use only awk in this way:

who | awk '!seen[$1]++ {print $1}'

A POSIX compliant solution, provided by @dessert - where cut will use the spaces as delimiter -d' ' and will print only the first field of each record -f1:

who | cut -d' ' -f1 | sort -u

Thanks to @DavidFoerster here is a lot shorter syntax that doesn't lose the information of all the other columns:

who | sort -u -k 1,1

For the same purposes we could use the command w with the option -h (ignore headers), for example:

w -h | awk '!seen[$1]++ {print $1}'

We could use also the command users combined with the command rs (reshape data) with the transpose option -T and then again sort -u:

users | rs -T | sort -u

We could use and who -q with transposition in the following way - where the command head -1 will crop only the first line of the output of the previous command:

who -q | head -1 | rs -T | sort -u

See also:

3
  • 1
    @dessert: the output of w and who isn't alphabetically sorted, so I intentionally have used sort -u in the first solution. Also the output of who -q should be transposed (like as the last example) otherwise the result isn't correct.
    – pa4080
    Nov 20, 2017 at 7:52
  • 1
    I don't think the section on time comparison is useful. Unless you have thousands of users logged in, the startup time for the commands is going to be far greater than the time taken to process and print the output. The section just adds noise to the answer without any benefit.
    – muru
    Nov 20, 2017 at 8:32
  • 2
    @muru, you are right. I've removed the time comparison section from the answer.
    – pa4080
    Nov 20, 2017 at 8:37

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .