views:

100

answers:

3

I used 'change directory' in my shell script (bash)

#!/bin/bash
alias mycd='cd some_place'
mycd
pwd

pwd prints some_place correctly, but after the script finished my current working directory doesn't change.

Is it possible to change my path by script?

+10  A: 

The script is run in a separate subshell. That subshell changes directory, not the shell you run it in. A possible solution is to source the script instead of running it:

# Bash
source yourscript.sh
# or POSIX sh
. yourscript.sh
schot
thanks for this tip.
qrtt1
+8  A: 

You need to source the file as:

. myfile.sh

or

source myfile.sh

Without sourcing the changes will happen in the sub-shell and not in the parent shell which is invoking the script. But when you source a file the lines in the file are executed as if they were typed at the command line.

codaddict
thanks. it works
qrtt1
A: 

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.

thomasd