26

I typed cd - in terminal by mistake today, and I got an error saying:

bash: cd: OLDPWD not set

And unfortunately, man cd doesn't exist.

No manual entry for cd

What does it actually do?

Dan
  • 12,494
  • 7
  • 70
  • 94
  • 3
    `cd` is a Bash builtin. It is therefore documented in [`man bash-builtins`](http://manpages.ubuntu.com/manpages/trusty/en/man7/bash-builtins.7.html#contenttoc20), instead of its own page. This holds true for all other Bash builtins. You can tell it's a builtin because of the `bash: ` in front of the error message. – kiri Mar 15 '14 at 11:26
  • `help cd` does work for builtin commands, but unfortunately it doesn't say anything about the `-` special name. `man bash-builtins` mentioned above however does :) – raj Feb 11 '21 at 12:10

2 Answers2

27

cd - switches between the old and new present working directories.

avinash@avinash:~$ cd -
bash: cd: OLDPWD not set
avinash@avinash:~$ cd ~/Desktop
avinash@avinash:~/Desktop$ pwd
/home/avinash/Desktop
avinash@avinash:~/Desktop$ cd -
/home/avinash
avinash@avinash:~$ 

See also,

avinash@avinash:~$ echo $OLDPWD

avinash@avinash:~$ cd ~/Desktop
avinash@avinash:~/Desktop$ echo $OLDPWD
/home/avinash
avinash@avinash:~/Desktop$ cd d
avinash@avinash:~/Desktop/d$ echo $OLDPWD
/home/avinash/Desktop
avinash@avinash:~/Desktop/d$ 

The $OLDPWD variable stores the path of the previous present working directory.

Dan
  • 12,494
  • 7
  • 70
  • 94
Avinash Raj
  • 77,204
  • 56
  • 214
  • 254
10

Avinash Raj's answer is completely correct but as for the manual entry, you can get the POSIX manual pages and then man cd will work:

sudo apt-get install manpages-posix
man cd

The bit that tells you all this is the OPERANDS section:

-      When a hyphen is used as the operand, this shall be equivalent to the command:

       cd "$OLDPWD" && pwd

which changes to the previous working directory and then writes its name.
Oli
  • 289,791
  • 117
  • 680
  • 835