执行cd -命令时报错-bash: cd: OLDPWD not set的解决方法
-bash: cd: OLDPWD not set 错误并实现返回目录需求 Hey there! Let's break down why you're hitting this error and how to get your directory navigation working as expected.
First, the root cause: OLDPWD is a bash environment variable that tracks the last directory you were in before switching. If you just opened your terminal or haven't run any cd commands yet, this variable hasn't been set at all—hence the error when trying cd -.
Below are solutions tailored to two common "go back" directory needs:
场景1:回到当前目录的父目录(比如从/home/you/projects回到/home/you)
This is the most common "go up one level" use case, and it works every time—no setup required:
cd ..
The double dots .. are a standard Linux file system shortcut for the parent directory of your current location.
场景2:回到 your previous directory(比如 switching from Folder A to Folder B, then wanting to jump back to A)
To use cd - successfully, you just need to let bash set the OLDPWD variable first:
- Run any
cdcommand to switch directories (e.g.,cd /tmp). Bash will automatically save your starting directory toOLDPWDafter this first switch. - Now
cd -will work perfectly, jumping you back to the directory you were in before that first switch.
For more flexible directory navigation, you can also use the directory stack commands:
- When in Folder A, run
pushd /path/to/FolderB—this switches you to B and adds A to a stack of saved directories. - To jump back to A, just run
popd. You can keep adding directories withpushdand usedirsto view the full stack anytime.
小补充
If you want OLDPWD to exist right when you open a terminal, you can add this line to your ~/.bashrc or ~/.bash_profile:
export OLDPWD="$HOME"
This sets OLDPWD to your home directory on startup, though in most cases this isn't necessary—bash will manage the variable automatically once you run your first cd command.
内容的提问来源于stack exchange,提问作者tmighty

