为什么我不能使用“cd"更改目录?在脚本中? [英] Why can't I change directories using "cd" in a script?

查看:76
本文介绍了为什么我不能使用“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"更改目录?在脚本中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆