本文主要是介绍bash脚本无法设置环境变量?你需要了解 source 和 sh 的区别,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
问题背景
有时需要通过脚本设置环境变量,但是发现脚本可以正常执行,但是环境变量没有任何更改。
假设有脚本内容如下:
#!/bin/bashexport TEMP=1
尝试执行,可以发现:
- 以 sh 方式执行的时候,无法设置环境变量。
- 以 source 方式执行的时候,可以正确设置环境变量。
$ sh env.sh
$ echo $TEMP$ source env.sh
$ echo $TEMP
1
当你发现无法通过脚本设置环境变量的时候,使用source执行即可解决。
source 和 sh 的区别
一句话说明:
- source 在当前shell中执行脚本中的命令流
- sh 在 subshell 中执行脚本中的命令流,因此不会影响当前的shell环境。
source 源码
通过读源码可以得到最为直观的解释。
执行逻辑为:打开文件,将其内容放入一个大的字符串中,关闭文件,然后执行这个字符串。
// bash/builtins/source.def/* Read and execute commands from the file passed as argument. Guess what.This cannot be done in a subshell, since things like variable assignmentstake place in there. So, I open the file, place it into a large string,close the file, and then execute the string. */
int
source_builtin (list)WORD_LIST *list;
{
// ...
}
这篇关于bash脚本无法设置环境变量?你需要了解 source 和 sh 的区别的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!