Global environment variables in a shell script
如何在bash脚本中设置全局环境变量?
如果我做类似的事情
1 2 | #!/bin/bash FOO=bar |
或…
1 2 | #!/bin/bash export FOO=bar |
…var似乎保留在本地上下文中,而我希望在脚本完成执行后继续使用它们。
用
1 | . myscript.sh |
这将在当前shell环境中运行脚本。
1 2 3 | FOO=1 export BAR=2 ./runScript.sh |
那么,
当运行shell脚本时,它是在子shell中完成的,因此它不会影响父shell的环境。您希望通过执行以下操作来获取脚本的源代码:
1 | . ./setfoo.sh |
它在当前shell的上下文中执行,而不是作为子shell执行。
从bash手册页:
. 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.
Linux命令
1 2 | source is a Unix command that evaluates the file following the command, as a list of commands, executed in the current context |
1 2 | #!/bin/bash export FOO=bar |
或
1 2 3 | #!/bin/bash FOO=bar export FOO |
出口:
shell应将导出属性赋予与指定名称对应的变量,这将使它们处于随后执行命令的环境中。如果变量名称后跟=word,则该变量的值应设置为word。
1 2 | FOO=bar export FOO |