What Does Cd - (Cd Hyphen) Do?

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?

2

2 Answers

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.

0

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.
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Marcus Vance

Marcus Vance

Cybersecurity & Digital Privacy Researcher

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.

Share this article
Twitter Facebook Pinterest