Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
417 views
in Technique[技术] by (71.8m points)

linux - 为什么“ cd”在shell脚本中不起作用?(Why doesn't “cd” work in a shell script?)

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

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

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

I saved this file as proj, added execute permission with chmod , and copied it to /usr/bin .

(我将此文件另存为proj,并使用chmod添加了执行权限,然后将其复制到/usr/bin 。)

When I call it by: proj , it does nothing.

(当我通过以下方式调用它时: proj ,它什么都不做。)

What am I doing wrong?

(我究竟做错了什么?)

  ask by ashokgelal translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Shell scripts are run inside a subshell, and each subshell has its own concept of what the current directory is.

(Shell脚本在一个子Shell中运行,每个子Shell对当前目录都有自己的概念。)

The cd succeeds, but as soon as the subshell exits, you're back in the interactive shell and nothing ever changed there.

(cd成功,但是一旦子shell退出,您就回到了交互式shell中,那里什么也没有改变。)

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

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...