Preserve environments vars after shell script finishes

后端 未结 3 1898
别那么骄傲
别那么骄傲 2021-01-11 14:14

How can I keep the environment variables, set from a shell script, after the script finishes running?

相关标签:
3条回答
  • 2021-01-11 14:26

    This is not possible by running the script. The script spawns it's own sub-shell which is lost when the script completes.

    In order to preserve exports that you may have in your script, you can call them like this, which will add them to the current environment:

    . myScript.sh

    Notice the space between the . and the myScript.sh section.

    0 讨论(0)
  • 2021-01-11 14:31

    Environment variables exist the the environment that is private to each process. The shell passes a COPY of exported variables to it's children as their environment, but there is no way for them to pass their environment back to the parent or any process other than their children. You can print those variables and load them into the parent. Or as has been already mentioned, you can run your script in the current shell with either "source script" or ". script" (and you might need ./script if . isn't in your PATH). Some tools print their vars and the shell can load them using backticks like ssh-agent. That way whatever ssh-agent prints will be run as a command. If it prints something like "VAR1=VAL;VAR2=VAL2" that may do what you want.

    0 讨论(0)
  • 2021-01-11 14:51

    run the script as follows:

    source <script>
    
    -OR-
    
    . <script>
    

    This will run the script in the current shell, and define variables in the current shell. The variables will then be retained in the current shell after the script is done.

    0 讨论(0)
提交回复
热议问题