18

I want to list all the users dirs on the machine.Usually, I will do:

ls -l /home

But I use it in a script that will be deployed on others machines and maybe on that machines they don't call it home (e.g. myHome). So I want to generalize it to ls -l ~. But it just lists my users home dirs instead of all users home dirs name (basically I want to get a list of the users names on the machine). How can I generalize it?

5
  • 19
    There is in fact, no guarantee that all users' home directories are subdirectories of any one directory.
    – hobbs
    Dec 7 '17 at 8:05
  • 17
    @hobbs or that they even exist until the user logs in. This is one of those apparently simple issues that gets complex really quickly. Dec 7 '17 at 8:06
  • 11
    Keep in mind that ~ is generally the equivalent of /home/user, not of /home or /home/* (which seem to be closer to your intention).
    – Soron
    Dec 7 '17 at 9:29
  • 2
    @EightBitTony: ...nor is there any guarantee that the home directory exists at all. For example, on my Ubuntu install, several system users (including nobody) have their home directory set to /nonexistent, which, obviously, does not exist. (Of course, those users also have their password hash set to * and their shell set to /usr/sbin/nologin or /bin/false, so they really can't log in in the normal sense to begin with.) Dec 7 '17 at 14:25
  • 1
    On the other hand, an (old school) NFS server might serve home directories for users that are not known by name to its OS. Dec 8 '17 at 1:31
49

Many systems have a getent command to list or query the content of the Name Service databases like passwd, group, services, protocols...

getent passwd | cut -d: -f6

Would list the home directories (the 6th colon delimited field) of all the users in databases that can be enumerated.

The user name itself is in the first field, so for the list of user names:

getent passwd | cut -d: -f1

(note that it doesn't mean those users can login to the system or their home directory have been created, but that they are known to the system, they can be translated to a user id).

For databases that can't be enumerated, you can try and query each possible user id individually:

getent passwd {0..65535} | cut -d: -f1,6

(here assuming uids stop at 65535 (some systems support more) and a shell that supports zsh's {x..y} form of brace expansion). But you wouldn't want to do that often on systems where the user database is networked (and there's limited local caching) like LDAP, NIS+, SQL... as that could imply a lot of network traffic (and load on the directory server) to make all those queries.

That also means that if there are several users sharing the same uid, you'll only get one entry for each uid, so miss the others.

If you don't have getent, you could resort to perl:

perl -le 'while (@e = getpwent) {print $e[7]}'

for getent passwd ($e[0] for the user names), or:

perl -le 'for ($i=0;$i<65536;++$i) {
  if (@e = getpwuid $i) {print $e[0] ": " $e[7]}}'

for getent passwd {0..65535} with the same caveats.

In shells, you can use ~user to get the home directory of user, but in most shells, that only works for a limited set of user names (the list of allowed characters in user names supported for that ~ expansion operator varies from shell to shell) and with several shells (including bash), ~$user won't work (you'd need to resort to eval when the name of the user is stored in a variable there). And you'd still have to find a way to get the list of user names.

Some shells have builtin support to get that list of usernames.

  • bash: compgen -u would return the list of users in databases that can be enumerated.
  • zsh: the $userdirs associative array maps user names to their home directory (also limited to databases that can be enumerated, but if you do a ~user expansion for a user that is in a non-enumerable database, an entry will be added to $userdirs). So you can do:

    printf '%s => %s\n' "${(kv@)userdirs}"
    

    to list users with their home directory.

    That only works when zsh is interactive though.

  • tcsh, fish and yash are three other shells that can complete user names (for instance when completing ~<Tab> arguments), but it doesn't look like they let you obtain that list of user names programmatically.

10
  • The challenge for the OP will be knowing if getent is going to be there, which I guess to some extent depends on the scope of their 'others machines'. Dec 7 '17 at 8:38
  • 1
    @EightBitTony, I've added a perl alternative. Dec 7 '17 at 9:30
  • 1
    On Mac, it's probably something involving Open Directory.
    – SilverWolf
    Dec 7 '17 at 15:13
  • @seaturtle, perl -le 'while (@e = getpwent) {print $e[7]}' works fine on macOS. Dec 7 '17 at 15:23
  • 1
    @FloHe, those are user names. Most users on Unix systems are special system users whose life is dedicated to running system services. getent passwd shows you the user database. The first field is the user name, the 6th field is the users home directory. Dec 8 '17 at 15:54
17

A better way to list user home directories, is to parse /etc/passwd and extract them from there, and not make any assumptions about where they may be.

And judging by your second comment, you actually want the user names, not their home directories, in which case, /etc/passwd is a better choice anyway. Note that some Linux / UNIX machines will have other user authentication mechanisms configured (e.g. LDAP), and so ultimately, your query is more complex than you might first imagine, but /etc/passwd is a good place to start.

3
  • 9
    See also getent on systems that support it.
    – Kusalananda
    Dec 7 '17 at 8:06
  • 6
    Yes, getent is always better than parsing /etc/passwd (it addresses the concern with “other user authentication mechanisms”). Dec 7 '17 at 8:25
  • @Kusalananda The problem with a getent solution is it assumes the data source can be enumerated, and not just queried for a specific value. That's detailed in Stéphane Chazelas answer to this question, but I though I'd add a comment for anyone skimming over this page. Dec 7 '17 at 12:23
9

The short answer:

compgen -u

The medium answer: Since you're using bash, you can list all possible completions for ~ using compgen -A user. That's such a common usage, it can be abbreviated compgen -u. As a shell builtin, compgen does not have its own man page. Instead see bash(1) for documentation and read the section on Programmable Completion.

A more thorough alternative

If you're extremely concerned about portability, you might not even be able to rely on other machines having bash. In that case, do this:

(getent passwd ||
    dscl . -ls /Users dsAttrTypeNative:homeDirectory || 
    nidump passwd  ||
    cat /etc/passwd) 2>/dev/null  |  cut -d: -f6

Explanation The long answer tries everything, so it will work on pretty much any UNIX system, regardless of whether it uses the newer /etc/nsswitch.conf (both GNU/Linux and BSD come with getent), the traditional UNIX passwd flat file, MacOS's Directory Services¹ (dscl), or even the older, cat-themed MacOS X releases and NeXTSTEP (nidump).

Simplicity But, how portable do you need? Unix has many ways of doing things and sometimes simpler suffices. If you have to pick one, I'd recommend getent passwd | cut -d: -f6 for shell scripts.²


Footnote ¹: I haven't used MacOS in a bit, so if someone can confirm for me that I got the syntax right (and the output doesn't include any stray colons that would mess up cut), that'd be great. Thanks.

Footnote ²: What I recommend and what I do may differ. Personally, I'll more often use the traditional cut -d: -f1 /etc/passwd at the command line. After decades of repetition, my fingers can type it while my mind is working on other things.

6
  • 2
    All Mac OS X machines are pretty much guaranteed to have bash, as it comes with the system. (As does zsh and several other shells.)
    – SilverWolf
    Dec 7 '17 at 15:15
  • True enough, but back when I was using MacOS, Apple hadn't updated bash in a long time and it was some crusty version 3 thing that I always had to replace. Has Apple gotten better about updating bash?
    – hackerb9
    Dec 7 '17 at 15:29
  • True, didn't think about that. My version of bash (macOS Sierra 10.12.6) is 3.2.57. (:
    – SilverWolf
    Dec 7 '17 at 21:14
  • Anyway, bash has had compgen -u since 2.04 released in 2000. Dec 7 '17 at 21:26
2

What about ls -l ~/..? This lists all the directories in the parent of your home directory.

3
  • 5
    That only works on systems where all home directories are based in the same directory, which isn’t many (you might think /home is common on Linux systems, but what happens when you run that as root?). Listing home directories is an adventure full of pitfalls if you want to handle all cases you’re likely to come across, see the other answers for details. Dec 7 '17 at 12:39
  • 7
    This is arguably the only answer so far which directly answers OP's perceived problem. However, it doesn't answer OP's underlying problem.
    – pipe
    Dec 7 '17 at 13:40
  • 1
    The value in this answer is in understanding what it misses, and why it is not as good as the other higher-voted answers.
    – Criggie
    Dec 8 '17 at 8:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.