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 . When I call it by: proj , it does nothing. What am I doing wrong?


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"

You're doing nothing wrong! You've changed the directory, but only within the subshell that runs the script.

You can run the script in your current process with the "dot" command:

. proj

But I'd prefer Greg's suggestion to use an alias in this simple case.


The cd in your script technically worked as it changed the directory of the shell that ran the script, but that was a separate process forked from your interactive shell.

A Posix-compatible way to solve this problem is to define a shell procedure rather than a shell-invoked command script.

jhome () {
  cd /home/tree/projects/java
}

You can just type this in or put it in one of the various shell startup files.

链接地址: http://www.djcxy.com/p/56848.html

上一篇: 系统Shell脚本无法在PATH中找到我的命令

下一篇: 为什么“cd”不能在shell脚本中工作?