How does cd command work? (unix) [closed]

Solution 1:

OLDPWD is not set, because you have't changed directory

[dave@odessa ~]$ cd -
-bash: cd: OLDPWD not set
[dave@odessa ~]$ cd /tmp
[dave@odessa tmp]$ cd -
/export/home/dave

[dave@odessa ~]$ cd /tmp
[dave@odessa tmp]$ echo $OLDPWD
/export/home/dave

cd without any arguments will chdir to $HOME

[dave@odessa tmp]$ echo $HOME
/export/home/dave
[dave@odessa tmp]$ HOME=/ cd
[dave@odessa /]$ pwd
/

Solution 2:

type cd

tells us that

cd is a shell builtin

man sh

tells us what you found out:

If a single dash is specified as the argument, it will be replaced by the value of OLDPWD.

The internal implementation of cd in the shell does a chdir(2) -syscall.

Solution 3:

cd by itself changes to your home directory

$ cd /tmp
$ pwd
/tmp
$ cd
$ pwd
/home/username