Real shell (at least Bash) shell stores current working directory path in PWD
environment variable and old working directory path in OLDPWD
. Rewriting PWD
does not change your working directory, but rewriting OLDPWD
really changes where cd -
will take you.
Try this:
cd /tmp
echo "$OLDPWD" # /home/palec
export OLDPWD='/home'
cd - # changes working directory to /home
I don’t know how you implement the shell functionality (namely how you represent current working directory; usually it’s an inherent property of the process, implemented by the kernel) but I think that you really have to keep the old working directory in an extra variable.
By the way shell also forks for each command executed (except for the internal ones). Current working directory is a property of a process. When a command is started, it can change its inner current working directory, but it does not affect the shell’s one. Only cd
command (which is internal) can change shell’s current working directory.