为什么不"cd"?在shell脚本中工作? [英] Why doesn't "cd" work in a shell script?

查看:69
本文介绍了为什么不"cd"?在shell脚本中工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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"?在shell脚本中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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