13

I pressed ~TabTab on the bash command prompt and got an unexpected set of completions.

First it looked like all the folks in the /Users directory, and a lot more.

Then I thought it was doing the reverse lookup of folks with "home" directories in /etc/password, or perhaps the ones that were /var/empty -- this seems about right.

What I'm curious about is what's really going on and why this works as it does.

21

I don't have an OSX system handy to check on but on all *nixes, ~foo is a shorthand for the home directory of user foo. For example, this command will move into my user's $HOME (cd ~ alone will move into your home directory):

cd ~terdon

So, ~ and Tab will expand to all possible user names. The list should be the same as the list of users in /etc/passwd.

I can confirm that that is exactly what happens when I try this on my Debian.

  • It's the same when I try it on FreeBSD. – Jenny D May 27 '15 at 12:41
  • So the thing that threw me was that I didn't have directories in /home for those users. In fact, many said /var/empty. I figured that such completions were by disk lookup, so that ~ would be looking at the actual home directory on disk rather than the /etc/passwd entries. Because ~ really means "a user's home directory" and not actually a shortcut for /home (or /User), the expansion references /var/empty in my OS X case. Learned something new! Thanks! – Walt Stoneburner May 27 '15 at 16:58
  • @WaltStoneburner fdo's answer below suggests that OSX is doing something different, I don't know. On Linux, anyway, creating a directory in /home is irrelevant, that won't make a new username be listed. Also, note that not all users' $HOMEs are in /home (or /Users). – terdon May 27 '15 at 17:00
  • @terdon - I think you nailed it with your answer. On my Linux account I have a dovenull user that has a bogus directory of /nonexistent, it shows up in the autocompletion, but the cd command fails (as expected). – Walt Stoneburner May 27 '15 at 17:06
2

I thought it was doing the reverse lookup of folks with "home" directories in /etc/password.

On OS X Open Directory is consulted instead of /etc/passwd.

1

Bash Reference Manual says:

Bash attempts completion treating the text as username (if the text begins with ‘~’)

Bash uses getpwent function for completion.

man getpwent on OSX says:

These functions obtain information from opendirectoryd(8), including records in /etc/master.passwd which is described in master.passwd(5).

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.