You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

执行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 cd command to switch directories (e.g., cd /tmp). Bash will automatically save your starting directory to OLDPWD after 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:

  1. When in Folder A, run pushd /path/to/FolderB—this switches you to B and adds A to a stack of saved directories.
  2. To jump back to A, just run popd. You can keep adding directories with pushd and use dirs to 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:44:19