change the path variable of the parent shell in a shell script
I wanted to change the path environment variable in a shell script. The path variable should be modified after the execution 开发者_JAVA技巧of the shell script.
There are two ways I know of to do this. The first is to run the script in the context of the current shell with either of:
. myscript.sh
source myscript.sh
but that runs the risk of polluting the current shell with all sorts of stuff.
I'd prefer a solution where the amount of information leakage is minimal. That means still running it as a subshell but outputting the new path on statndard output:
PATH=$(myscript.sh)
This method is a much better one since the path is the only thing that can be affected by the subshell but you have to be careful with what that subshell outputs.
You need to source your script instead of executing it.
. script.sh
or
source script.sh
Inside of the script it's enough to either export od just set the variable.
When the script is executed, it runs in a separate shell process, and can't easily change parent shell's variables.
More about it here: Can a shell script set environment variables of the calling shell?
精彩评论