How can I find the number of users online in Linux?

Classically, the command is 'who' rather than 'users', but 'who' gives you more information. Looking back at the original Unix articles (mid-70s), the example would have been:

who | wc -l

Using 'wc -l' counts lines of output - it works with both 'users' and 'who'. Using '-w' only works reliably when there is one word per user (as with 'users' but not with 'who').

You could use 'grep -c' to count the lines. Since you are only interested in non-blank user names, you could do:

who | grep -c .

There's always at least one character on each line.


As noted in the comments by John T, the users command differs from who in a number of respects. The most important one is that instead of giving one name per line, it spreads the names out several per line — I don't have a machine with enough different users logged in to test what happens when the number of users becomes large. The other difference is that 'who' reports on terminal connections in use. With multiple terminal windows open, it will show multiple lines for a single user, whereas 'users' seems to list a logged in user just once.

As a consequence of this difference, the 'grep -c .' formulation won't work with the 'users' command; 'wc -w' is necessary.


You are looking for the wc (word count) command.

Try this:

users | wc -w

Open a shell and type:

who -q

The last line will give you a count.

EDIT:

(sigh) I misunderstood the question. Here's a somewhat brute-force approach:

To see unique user names:

who | awk '{ print $1 }' | sort | uniq

To see a count of unique users:

who | awk '{ print $1 }' | sort | uniq | wc -l 

Tags:

Linux