That's probably because the cd
command has to be built into the shell, not something external and executed. If an external command changed directory, it has no effect on the parent shell. (Even though there is usually a command /bin/cd
or /usr/bin/cd
on Linux and macOS systems, executing it changes the directory for that process, but has no effect on the process that invoked it.)
I do not understand the line "If the external command changed directory, it has no effect on the parent shell".
Normally, when a shell executes a command, it does fork()
and the child process uses exec()
to execute the command entered by the user. For example, if the entered command is 'ls /
', the shell arranges to execute /bin/ls
with two arguments, ls
and /
. However, if the command selected executes the chdir()
system call, that affects the child process, but does not affect the parent shell. So, the shell has to handle the cd
command itself, not via fork()
and exec()
.
Note that in DOS, a .BAT
file can do cd
and it affects the cmd.exe
process. This does not happen in Unix — a child process cannot affect the current directory of the parent process.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…