How does ~/ work? [duplicate]
Solution 1:
This is tilde expansion.
Tilde expansion is required by POSIX (see that first linked page) and appears in all modern Bourne-style shells. That includes the popular shells bash
, ksh93
, and zsh
, but also more minimalist shells like mksh
, dash
, and busybox ash
.
In practice, different POSIX-compatible shells sometimes differ in the precise details of tilde expansion, both in the unspecified case that HOME
would be used but is unset or empty, and to permit ~
notation to be used for other purposes than expanding users' home directories. For example, tilde expansion in bash
also provides a shorthand for accessing the values of the PWD
and OLDPWD
variables, with ~-
and ~+
, respectively.
However, in the typical cases, it works about the same across Bourne-style shells. These are typical cases (but note that this way of separating them is not official, it's just my way of presenting the material):
-
~
or~/
by itself expands to your home directory. -
~/
followed by more path components expands to a path starting at your home directory. -
~username
or~username/
by itself expands to the home directory of the user whose username isusername
. -
~username/
followed by more path components expands to a path starting at the home directory of the user whose username isusername
.
Solution 2:
~
is 'shorthand' for $HOME
~
is a 'shorthand' way to write $HOME
in other words your home directory. It works in shells (e.g. bash
) and is called 'tilde expansion'.
If you add a trailing slash you imply that you are talking about a directory.
Examples:
$ ls -d ~/
/home/sudodus/
$ ls -d ~
/home/sudodus
$ ls -d $HOME
/home/sudodus
$ sudo -i
[sudo] lösenord för sudodus:
# ls -d ~/
/root/
# ls -d ~
/root
# exit
logout
$ ls xournal.png
xournal.png
$ LANG=C ls xournal.png/
ls: cannot access 'xournal.png/': Not a directory