6

Could anybody explain to me how cd - command work? man cd tells me that An argument of - is equivalent to $OLDPWD. Then I found on the net that $OLDPWD is the previous working directory as set by the cd command. And when I do cd - on my unix I get -bash: cd: OLDPWD not set which is confusing for me.

UPDATE: it works now it gives me the previous working directory. I guess I did not use and cd command before so that is why $OLDPWD was not set.

One more question what cd (type cd and press enter) does? I wouldn't say that nothing. Is there any better technical explanation?

host [~]# cd
host [~]#
Radek
  • 1,133
  • 4
  • 26
  • 38

3 Answers3

10

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
/
Dave Cheney
  • 18,307
  • 7
  • 48
  • 56
6
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.

ptman
  • 27,124
  • 2
  • 26
  • 45
  • @ptman: looks like we are having different results with different shells in both `cd -` and `cd` cases – Radek Mar 03 '10 at 09:41
  • 1
    Nice, I never knew about `type`. I was used to man _(some shell builtin)_ giving me the raspberry. – Dave Cheney Mar 03 '10 at 09:54
1

cd by itself changes to your home directory

$ cd /tmp
$ pwd
/tmp
$ cd
$ pwd
/home/username
Dennis Williamson
  • 60,515
  • 14
  • 113
  • 148