Shell 脚本中的全局环境变量

如何在 bash 脚本中设置全局环境变量?

如果我做一些

#!/bin/bash
FOO=bar

或者

#!/bin/bash
export FOO=bar

... var 似乎停留在本地上下文中,而我希望在脚本执行完毕后继续使用它们。

164040 次浏览
FOO=bar
export FOO

Run your script with .

. myscript.sh

This will run the script in the current shell environment.

export governs which variables will be available to new processes, so if you say

FOO=1
export BAR=2
./runScript.sh

then $BAR will be available in the environment of runScript.sh, but $FOO will not.

When you run a shell script, it's done in a sub-shell so it cannot affect the parent shell's environment. You want to source the script by doing:

. ./setfoo.sh

This executes it in the context of the current shell, not as a sub shell.

From the bash man page:

. filename [arguments]
source filename [arguments]

Read and execute commands from filename in the current shell environment and return the exit status of the last command executed from filename.

If filename does not contain a slash, file names in PATH are used to find the directory containing filename.

The file searched for in PATH need not be executable. When bash is not in POSIX mode, the current directory is searched if no file is found in PATH.

If the sourcepath option to the shopt builtin command is turned off, the PATH is not searched.

If any arguments are supplied, they become the positional parameters when filename is executed.

Otherwise the positional parameters are unchanged. The return status is the status of the last command exited within the script (0 if no commands are executed), and false if filename is not found or cannot be read.

#!/bin/bash
export FOO=bar

or

#!/bin/bash
FOO=bar
export FOO

man export:

The shell shall give the export attribute to the variables corresponding to the specified names, which shall cause them to be in the environment of subsequently executed commands. If the name of a variable is followed by = word, then the value of that variable shall be set to word.

source myscript.sh is also feasible.

Description for linux command source:

source is a Unix command that evaluates the file following the command,
as a list of commands, executed in the current context

A common design is to have your script output a result, and require the cooperation of the caller. Then you can say, for example,

eval "$(yourscript)"

or perhaps less dangerously

cd "$(yourscript)"

This extends to tools in other languages besides shell script.

In your shell script, write the variables to another file like below and source these files in your ~/.bashrc or ~/.zshrc

echo "export FOO=bar" >> environment.sh

In your ~/.bashrc or ~/.zshrc, source it like below:

source Path-to-file/environment.sh

You can then access it globally.