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:07

LOOOOOng time after, but I did the following:

create a file called case

paste the following in the file:

#!/bin/sh

cd /home/"$1"

save it and then:

chmod +x case

I also created an alias in my .bashrc:

alias disk='cd /home/; . case'

now when I type:

case 12345

essentially I am typing:

cd /home/12345

You can type any folder after 'case':

case 12

case 15

case 17

which is like typing:

cd /home/12

cd /home/15

cd /home/17

respectively

In my case the path is much longer - these guys summed it up with the ~ info earlier.

查看更多
高级女魔头
3楼-- · 2018-12-31 02:09

While sourcing the script you want to run is one solution, you should be aware that this script then can directly modify the environment of your current shell. Also it is not possible to pass arguments anymore.

Another way to do, is to implement your script as a function in bash.

function cdbm() {
  cd whereever_you_want_to_go
  echo "Arguments to the functions were $1, $2, ..."
}

This technique is used by autojump: http://github.com/joelthelion/autojump/wiki to provide you with learning shell directory bookmarks.

查看更多
倾城一夜雪
4楼-- · 2018-12-31 02:11

simply run:

cd /home/xxx/yyy && command_you_want
查看更多
伤终究还是伤i
5楼-- · 2018-12-31 02:11

It only changes the directory for the script itself, while your current directory stays the same.

You might want to use a symbolic link instead. It allows you to make a "shortcut" to a file or directory, so you'd only have to type something like cd my-project.

查看更多
残风、尘缘若梦
6楼-- · 2018-12-31 02:13

You can create a function like below in your .bash_profile and it will work smoothly.

The following function takes an optional parameter which is a project. For example, you can just run

cdproj

or

cdproj project_name

Here is the function definition.

cdproj(){
    dir=/Users/yourname/projects
    if [ "$1" ]; then
      cd "${dir}/${1}"
    else
      cd "${dir}"
    fi
}

Dont forget to source your .bash_profile

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

You can do following:

#!/bin/bash
cd /your/project/directory
# start another shell and replacing the current
exec /bin/bash

EDIT: This could be 'dotted' as well, to prevent creation of subsequent shells.

Example:

. ./previous_script  (with or without the first line)
查看更多
登录 后发表回答