I knew that there is a variable PWD which is changed when I type the command cd. But when I try to change it manually the current directory isn't changed. How to manipulate PWD directly?
-
6Well are you trying to change the PWD or are you trying to change the current directory? What are you really trying to achieve by manipulating PWD directly rather than using `cd`? That is, it is not clear what your actual goal is and I suspect your question may be an [XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). – kaylum Feb 29 '16 at 19:27
-
I just wanted to do the same thing that does the command cd, but in another way (by changing PWD manually). – David Tsaturyan Feb 29 '16 at 19:33
-
3Well, obviously changing `PWD` doesn't achieve that as you have found. Because `cd` is the cat that wags the `PWD` tail and not the other way around. `cd` is part of the shell. Most shells are written in C. So if you want to do what it does then write C (or some other language) code that does the same as it. In C the [`chdir`](http://linux.die.net/man/2/chdir) function can be used to change the current working directory. – kaylum Feb 29 '16 at 19:42
-
Either setting `$PWD` will do the same as a `cd`, or it will leave you shell in the rather strange state of having a `$PWD` which is different from the actual working directory (what will `pwd` print? What will `cd .` do?) – Martin Tournoij Feb 29 '16 at 19:42
-
1Think of it this way: It's a bit like drawing a mustache on your face in a mirror. =} – tink Feb 29 '16 at 19:54
3 Answers
Assignments to this variable may be ignored.
Assignments are not special in bash, dash, ash, zsh or ksh, and the value will simply be overwritten next time the shell changes directory.

- 116,971
- 11
- 170
- 194
While other shells might support such a variable as well, the $PWD
variable is generally specific to the bash shell.
The bash manual says:
PWD
The current working directory as set by the cd builtin.
Meaning it will be set when you use the cd
builtin to change a directory but bash will not change the current directory when you set $PWD
.

- 152,036
- 28
- 249
- 266
At least on my Mac and Linux machines running bash you can just overwrite the variable, so running PWD=/ will change your current directory (in the prompt) to /.
The variable PWD in bash is in control of the shell's working directory (again only the prompt) and you will see that the directory after the PWD= command has been changed but the pwd command isn't impacted by the change.
<0>xxxx@dhcp89-089-034:~$ PWD=/
<0>xxxx@dhcp89-089-034:/$ pwd
/Users/xxxx
Now the environment variable PWD is a bash prompt thing and is not the real working directory, nor is modifying it a useful thing to do unless you actually use the 'cd' command.

- 34
- 6