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

qrtt1 picture qrtt1 · Oct 7, 2010 · Viewed 68.3k times · Source

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?

Answer

codaddict picture codaddict · Oct 7, 2010

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.