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

如何在指定目录打开Bash子shell并退出后返回原目录?

在指定目录启动Bash子Shell的方法

以下几种方案都能满足你的需求:启动子Shell时直接进入目标目录,且退出子Shell后自动回到原目录。

方法1:用bash -c结合目录切换与进程替换

通过先切换目录再启动交互式Shell的方式实现:

$ pwd
/original/location
$ bash -c "cd /another/location && exec bash"
$ pwd
/another/location
$ exit
$ pwd
/original/location

原理:cd /another/location完成目录切换,exec bash会用新的交互式Bash替换当前临时子Shell进程,避免额外嵌套,退出时直接回到父Shell的原目录。

方法2:通过--rcfile参数加载临时启动命令

让Bash启动时自动执行目录切换命令:

$ bash --rcfile <(echo 'cd /another/location')

这种方式利用Bash启动时读取指定配置文件的特性,临时注入cd命令,不影响父Shell的工作目录。

方法3:定义别名简化重复操作

如果频繁使用这个功能,可以在~/.bashrc中添加别名:

alias bashcd='bash -c "cd \$1 && exec bash"'

使用时只需输入:

bashcd /another/location

就能快速在指定目录启动子Shell。

内容的提问来源于stack exchange,提问作者jeffpkamp

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 02:27:41