Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

closed as off topic by Michael Hampton, John Gardeniers, mdpc, kce, Ward Feb 7 '13 at 4:25

Questions on Server Fault are expected to relate to server, networking, or related infrastructure administration within the scope defined by the community. Consider editing the question or leaving comments for improvement if you believe the question can be reworded to fit within the scope. Read more about reopening questions here.If this question can be reworded to fit the rules in the help center, please edit the question.

up vote 9 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 -

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

cd without any arguments will chdir to $HOME

[dave@odessa tmp]$ echo $HOME
[dave@odessa tmp]$ HOME=/ cd
[dave@odessa /]$ pwd
share|improve this answer
@Dave Cheney: thank you Dave, great answer. Crystal clear now ... – Radek Mar 3 '10 at 10:10
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.

share|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
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

cd by itself changes to your home directory

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

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