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 [~]#

3 Answers 3

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
/
1
  • 1
    @Dave Cheney: thank you Dave, great answer. Crystal clear now ...
    – Radek
    Mar 3, 2010 at 10:10
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.

2
  • @ptman: looks like we are having different results with different shells in both cd - and cd cases
    – Radek
    Mar 3, 2010 at 9:41
  • 1
    Nice, I never knew about type. I was used to man (some shell builtin) giving me the raspberry. Mar 3, 2010 at 9:54
1

cd by itself changes to your home directory

$ cd /tmp
$ pwd
/tmp
$ cd
$ pwd
/home/username
1
  • @Dennis Williamson: yes, yes, I already forgot ...
    – Radek
    Mar 3, 2010 at 10:10

Not the answer you're looking for? Browse other questions tagged .