How to alter PATH within a shell script?
You have to use source
or eval
or to spawn a new shell.
When you run a shell script a new child shell is spawned. This child shell will execute the script commands. The father shell environment will remain untouched by anything happens in the child shell.
There are a lot of different techniques to manage this situation:
Prepare a file sourcefile containg a list of commands to
source
in the current shell:export JAVA_HOME=/cygdrive/c/dev/Java/jdk1.5.0_22 export PATH=$JAVA_HOME/bin:$PATH
and then source it
source sourcefile
note that there is no need for a sha-bang at the begin of the sourcefile, but it will work with it.
Prepare a script evalfile.sh that prints the command to set the environment:
#!/bin/sh echo "export JAVA_HOME=/cygdrive/c/dev/Java/jdk1.5.0_22" echo "export PATH=$JAVA_HOME/bin:$PATH"
and then
eval
uate it:eval `evalfile.sh`
Configure and run a new shell:
#!/bin/sh export JAVA_HOME=/cygdrive/c/dev/Java/jdk1.5.0_22 export PATH=$JAVA_HOME/bin:$PATH exec /bin/bash
note that when you type
exit
in this shell, you will return to the father one.Put an alias in your
~/.bashrc
:alias prepare_environ='export JAVA_HOME=/cygdrive/c/dev/Java/jdk1.5.0_22; export PATH=$JAVA_HOME/bin:$PATH;'
and call it when needed:
prepare_environ
You could do that by using the source builtin:
. script_name
Some shells provide an alias named source:
source script_name