Meaning of tilde in Linux bash (not home directory)
Solution 1:
It's a Bash feature called "tilde expansion". It's a function of the shell, not the OS. You'll get different behavior with csh, for example.
To answer your question about where the information comes from: your home directory comes from the variable $HOME
(no matter what you store there), while other user's homes are retrieved real-time using getpwent()
. This function is usually controlled by NSS; so by default values are pulled out of /etc/passwd
, though it can be configured to retrieve the information using any source desired, such as NIS, LDAP or an SQL database.
Tilde expansion is more than home directory lookup. Here's a summary:
~ $HOME
~fred (freds home dir)
~+ $PWD (your current working directory)
~- $OLDPWD (your previous directory)
~1 `dirs +1`
~2 `dirs +2`
~-1 `dirs -1`
dirs
and ~1
, ~-1
, etc., are used in conjunction with pushd
and popd
.
Edited to add:
As Sean Bright pointed out in a comment, the baseline tilde behavior regarding home directories is codified as standard behavior for POSIX-compliant shells. Additionally, the wordexp() C API function is specified to implement this behavior. Though, obviously, use with caution.
Solution 2:
Those are the home directories of the users. Try cd ~(your username)
, for example.
Solution 3:
Are they the home directories of users in /etc/passwd
? Services like postgres, sendmail, apache, etc., create system users that have home directories just like normal users.
Solution 4:
Those are users. Check your /etc/passwd
.
cd ~username
takes you to that user's home directory.
Solution 5:
On my machine, because of the way I have things set up, doing:
cd ~ # /work1/jleffler
cd ~jleffler # /u/jleffler
The first pays attention to the value of environment variable $HOME
; I deliberately set my $HOME
to a local file system instead of an NFS-mounted file system. The second reads from the password file (approximately; NIS complicates things a bit) and finds that the password file says my home directory is /u/jleffler
and changes to that directory.
The annoying stuff is that most software behaves as above (and the POSIX specification for the shell requires this behaviour). I use some software (and I don't have much choice about using it) that treats the information from the password file as the current value of $HOME, which is wrong.
Applying this to the question - as others have pointed out, 'cd ~x
' goes to the home directory of user 'x', and more generally, whenever tilde expansion is done, ~x
means the home directory of user 'x' (and it is an error if user 'x' does not exist).
It might be worth mentioning that:
cd ~- # Change to previous directory ($OLDPWD)
cd ~+ # Change to current directory ($PWD)
I can't immediately find a use for '~+
', unless you do some weird stuff with moving symlinks in the path leading to the current directory.
You can also do:
cd -
That means the same as ~-
.