Bash script to change parent shell directory [duplicate] Bash script to change parent shell directory [duplicate] unix unix

Bash script to change parent shell directory [duplicate]


You can technically source your script to run it in your parent shell instead of spawning a subshell to run it. This way whatever changes you make to your current shell (including changing directories) persist.

source /path/to/my/script/script

or

. /path/to/my/script/script

But sourcing has its own dangers, use carefully.

(Peripherally related: how to use scripts to change directories)


Use a shell function to front-end your script

setup () {  # first, call your big script.  # (It could be open-coded here but that might be a bit ugly.)  # then finally...  cd someplace}

Put the shell function in a shell startup file.


Child processes (including shells) cannot change current directory of parent process. Typical solution is using eval in the parent shell. In shell script echo commands you want to run by parent shell:

echo "cd $filepath"

In parent shell, you can kick the shell script with eval:

eval `sh foo.sh`

Note that all standard output will be executed as shell commands. Messages should output to standard error:

echo "Some messages" >&2command ... >&2