How to view and count users on a Linux system
The who command shows you every login session open on the machine:
You can also use the w command to get a more detailed view of what each login session is doing:
You can count the total number of open sessions by counting the lines in the output of who or w with the -h option. (The -h option omits header lines, which we don't want to count.) To do this, pipe the output using the vertical bar ("|") to create a command pipeline. The output of one program in the pipeline is passed as input to the next. Here, we count the lines of both who and w -h by piping them to wc -l, effectively generating a count of active sessions.
Counting unique users
The above method counts login sessions, but if a user has more than one login session open they are counted more than once. To count unique users, we have to get more creative. We can use the cut command to strip all information except for the user name:
The above command says, "take the output of who, and display only the first field of information, which is delimited by a space." It gives us a list of only the usernames, but we still need to filter out repeated names.
To do this, we can add the sort -u command. This sorts the names alphabetically and filters out any lines that are not unique:
And finally, to count these unique users, we add wc -l at the end of our command pipeline:
Using ps to count users running a process
Another useful technique is to use the ps command to create a list every user on the system that owns a currently-running process. To do this, we can use ps with the options -e, -a, -h, and -o user. They can be combined as follows:
This command says, "show information for every process owned by any user, do not show headers, and print only the name of the user."
Notice that in addition to the users previously listed by who, we also see root listed here. The who command shows only users logged in to a terminal session, but ps lists users that own a running process, even if they don't have a terminal open. The ps command includes root, and it may include other system-specific users.
As before, we can sort our output and only list unique names:
...and produce the total desired: