How to run 'cd' in a shell script and stay there after the script finishes?

I used the "change directory" in my shell script (bash)

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

pwd correctly prints some_place , but after the script finishes, my current working directory does not change.

Can I change my path to a script?

+49
bash shell cd pwd
Oct 07 '10 at 7:13
source share
5 answers

You need to specify the file as:

 . myfile.sh 

or

 source myfile.sh 

Without a source, changes will occur in the sub-shell, and not in the parent shell that invokes the script. But when you send the file, the lines in the file are executed as if they were entered on the command line.

+65
Oct 07 '10 at 7:17
source share

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

 # Bash source yourscript.sh # or POSIX sh . yourscript.sh 
+14
07 Oct '10 at 7:17
source share

While finding the script you want to run is one solution, you should be aware that this script can then directly modify the environment of your current shell. It is also impossible to pass arguments.

Another way to do this is to implement the script as a function in bash.

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

This method is used by autojump: http://github.com/joelthelion/autojump/wiki to provide you with training bookmarks in the shell directory.

+12
Oct 07 '10 at 8:50
source share

This can be achieved by searching. Sourcing basically executes the script in the same shell, while normal execution ( sh test.sh or ./test.sh ) will create a subcommand and execute the script there.

test.sh

 cd development/ ls # Do whatever you want. 

Run test.sh on

 source test.sh 

. is the shortest designation for source . So you can also do

 . test.sh 

This will execute the script and change the directory of the current shell to development/ .

+3
Apr 15 '14 at 18:43
source share

whenever you run a script in your login shell, a new subprocess is generated and the script is executed in sub-shell. After the script completes, the subshell terminates and you return to the login shell. If every time you make cd through a script, the directory changes to the path specified by cd, but by the time the script finishes, you are returned to your shell to enter the working directory from where you started the script.

To overcome this, use

 source yourscript.sh 

what the source does, it executes the script as a TCL script, i.e. it has the same effect as entering each line on the command line of your login shell, and it runs from there. That way, when the script ends after cd, it stays in that directory.

+1
Nov 16 '11 at 12:35
source share



All Articles