I was rebuilding the bash command ls
using C as a unix programming book exercise and had a look at various dir functions. And I realized, that chdir
, opendir
and similar don't accept pathnames starting with ~
but do accept .
or ..
First, why? And second, is the source code of the real unix ls
command somewhere visible? Because ls ~
does indeed work and I am curious how this works.
Asked
Active
Viewed 91 times
1

Lavair
- 888
- 10
- 21
-
3The `~` is expanded by the shell. – Ian Abbott Oct 22 '19 at 11:40
-
1https://stackoverflow.com/questions/9493234/chdir-to-home-directory – Mat Oct 22 '19 at 11:40
-
1"~" is replaced by bash, not evaluated by 'ls' or any other command executed. You can check by calling `echo ~`. But that means if you call your ls from bash, you will get the home directory as command line argument too – Ingo Leonhardt Oct 22 '19 at 11:42
-
ahh thanks. Yes that makes sense because I just realized that if I pass ~ as a command line argument, it works – Lavair Oct 22 '19 at 11:43
-
1@Lavair: Rather if you pass the expanded value of ~ (which the shell expanded) as a command line argument. – R.. GitHub STOP HELPING ICE Oct 22 '19 at 11:44
2 Answers
2
~
is a shell shortcut that expands to the home directory set in /etc/passwd
or ldap configuration. The kernel has no concept of home directory and has no idea what ~
directory is.

Maxim Egorushkin
- 131,725
- 17
- 180
- 271
-
1Note that if this were not the case, it would be impoissible to create a file whose name is (or begins with) ~. – R.. GitHub STOP HELPING ICE Oct 22 '19 at 11:45
-
There's much more: https://www.gnu.org/software/bash/manual/html_node/Tilde-Expansion.html – gstukelj Oct 22 '19 at 11:46
0
The ~
is expanded by the shell into the home directory.
You can look up the shell's source code to find the expansion.

S.S. Anne
- 15,171
- 8
- 38
- 76