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 [~]#
link|improve this question

feedback

3 Answers

up vote 4 down vote accepted

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

link|improve this answer
@ptman: looks like we are having different results with different shells in both cd - and cd cases – Radek Mar 3 '10 at 9:41
1  
Nice, I never knew about type. I was used to man (some shell builtin) giving me the raspberry. – Dave Cheney Mar 3 '10 at 9:54
feedback

cd by itself changes to your home directory

$ cd /tmp
$ pwd
/tmp
$ cd
$ pwd
/home/username
link|improve this answer
@Dennis Williamson: yes, yes, I already forgot ... – Radek Mar 3 '10 at 10:10
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.