How do I list logged-in users without duplicates?
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?
1 Answer
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 -uOr 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 -uThanks to @DavidFoerster here is a lot shorter syntax that doesn't lose the information of all the other columns:
who | sort -u -k 1,1For 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 -uWe 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 -uSee also:
3