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

1

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.

codeitram

Posted 2019-07-13T16:03:48.827

Reputation: 13

Answers

2

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

Kamil Maciorowski

Posted 2019-07-13T16:03:48.827

Reputation: 38 429

The point is any executable changes its own working directory (if ever), I really didn't get you here, could you help, please? – codeitram – 2019-07-13T17:39:28.247

2@codeitram Each process has its own working directory; if cd runs in as a separate process from the shell (which /usr/bin/cd does), when it changes directory it's changing the directory of the cd process, not that of the shell process. You wanted the shell process's directory to change. In order to change the shell process's directory, the change must be done in that process (i.e. in the shell itself), not in another process. – Gordon Davisson – 2019-07-13T20:15:38.380