Why doesn't “cd” work in a shell script?

2018-12-31 01:44发布

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?

标签: linux shell
29条回答
时光乱了年华
2楼-- · 2018-12-31 02:24

This should do what you want. Change to the directory of interest (from within the script), and then spawn a new bash shell.

#!/bin/bash

# saved as mov_dir.sh
cd ~/mt/v3/rt_linux-rt-tools/
bash

If you run this, it will take you to the directory of interest and when you exit it it will bring you back to the original place.

root@intel-corei7-64:~# ./mov_dir.sh

root@intel-corei7-64:~/mt/v3/rt_linux-rt-tools# exit
root@intel-corei7-64:~#

This will even take you to back to your original directory when you exit (CTRL+d)

查看更多
听够珍惜
3楼-- · 2018-12-31 02:24

You can execute some lines in the same subshell if you end lines with backslash.

cd somedir; \
pwd
查看更多
梦该遗忘
4楼-- · 2018-12-31 02:25

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.

查看更多
不再属于我。
6楼-- · 2018-12-31 02:27

In your ~/.bash_profile file. add the next function

move_me() {
    cd ~/path/to/dest
}

Restart terminal and you can type

move_me 

and you will be moved to the destination folder.

查看更多
像晚风撩人
7楼-- · 2018-12-31 02:28

The cd is done within the script's shell. When the script ends, that shell exits, and then you are left in the directory you were. "Source" the script, don't run it. Instead of:

./myscript.sh

do

. ./myscript.sh

(Notice the dot and space before the script name.)

查看更多
登录 后发表回答