为什么我不能使用“cd"更改目录?在脚本中?

编程入门 行业动态 更新时间:2024-10-28 08:23:12
本文介绍了为什么我不能使用“cd"更改目录?在脚本中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试编写一个小脚本来将当前目录更改为我的项目目录:

I'm trying to write a small script to change the current directory to my project directory:

#!/bin/bash cd /home/tree/projects/java

我将此文件保存为 proj,使用 chmod 添加执行权限,并将其复制到 /usr/bin.当我通过以下方式调用它时:proj,它什么都不做.我做错了什么?

I saved this file as proj, added execute permission with chmod, and copied it to /usr/bin. When I call it by: proj, it does nothing. What am I doing wrong?

推荐答案

Shell 脚本在子 Shell 中运行,每个子 Shell 都有自己的当前目录的概念.cd 成功了,但是一旦子 shell 退出,您就会返回交互式 shell,那里没有任何变化.

Shell scripts are run inside a subshell, and each subshell has its own concept of what the current directory is. The cd succeeds, but as soon as the subshell exits, you're back in the interactive shell and nothing ever changed there.

解决此问题的一种方法是改用别名:

One way to get around this is to use an alias instead:

alias proj="cd /home/tree/projects/java"

更多推荐

为什么我不能使用“cd"更改目录?在脚本中?

本文发布于:2023-07-16 03:58:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1117622.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:我不   脚本   目录   quot   cd

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!