`/usr/bin/cd` is not working in mac terminal

I was checking the path of cd command in macOS terminal using which cd, I got /usr/bin/cd, so whenever I use this full path to execute cd it doesn't work as expected.

So here are some examples.

  1. Any valid path here root(/) as arg.

    /usr/bin/cd / -> doesn't change dir as specified

  2. Any invalid path here (kjfd) as arg.

    /usr/bin/cd kjfd -> /usr/bin/cd: line 4: cd: kjfd: No such file or directory

So, I really don't understand why cd with complete path address(/usr/bin/cd /) is not working while other commands like bin/echo do work.


Solution 1:

It is working. /usr/bin/cd changes its own working directory. Then it exits.

A process can change only its own working directory, not the working directory of some other process. No external tool can change the working directory of your current shell (exceptions: debuggers and such), so normally you use the cd builtin which is a part of the shell itself. It's the shell who changes its own working directory, /usr/bin/cd cannot do this for the shell.

There is this question What is the point of the cd external command? This is from one of the answers there:

It serves primarily as making sure the POSIX tool-chest is available both inside and outside a shell […]

For cd, that is not tremendously useful but note that cd changes directories but has other side effects: it returns an exit status that helps determine whether you're able to chdir() to that directory or not, and outputs a useful error message explaining why you can't chdir() when you can't.

which cd is not aware of shell builtins. Again you need the shell itself to tell what sole cd really is. E.g. in Bash there is the type builtin:

$ type cd
cd is a shell builtin