bash脚本无法设置环境变量?你需要了解 source 和 sh 的区别

问题背景

有时需要通过脚本设置环境变量,但是发现脚本可以正常执行,但是环境变量没有任何更改。

假设有脚本内容如下:

#!/bin/bash

export TEMP=1

尝试执行,可以发现:

  1. 以 sh 方式执行的时候,无法设置环境变量。
  2. 以 source 方式执行的时候,可以正确设置环境变量。
$ sh env.sh 
$ echo $TEMP

$ source env.sh 
$ echo $TEMP
1

当你发现无法通过脚本设置环境变量的时候,使用source执行即可解决。

source 和 sh 的区别

一句话说明:

  1. source 在当前shell中执行脚本中的命令流
  2. 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 assignments
   take 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;
{
// ...
}

相关推荐

  1. bashsh区别

    2024-06-15 14:54:02       6 阅读
  2. #!/bin/sh#!/bin/bash区别

    2024-06-15 14:54:02       16 阅读
  3. linux里sourceshbash、./有什么区别

    2024-06-15 14:54:02       43 阅读
  4. Windows 下 bat 脚本调用 Git bash 环境 sh 脚本

    2024-06-15 14:54:02       14 阅读
  5. `/bin/bash`、`sh` 或者直接./区别

    2024-06-15 14:54:02       18 阅读
  6. . ./ bash dash source 这五种执行shell脚本方式 区别

    2024-06-15 14:54:02       18 阅读
  7. 环境变量Bash内置命令

    2024-06-15 14:54:02       16 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-06-15 14:54:02       17 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-06-15 14:54:02       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-06-15 14:54:02       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-06-15 14:54:02       18 阅读

热门阅读

  1. 远程控制软件

    2024-06-15 14:54:02       9 阅读
  2. 基于stm32的WIFI语音气象站

    2024-06-15 14:54:02       46 阅读
  3. 机器学习之Transformer模型和大型语言模型(LLMs)

    2024-06-15 14:54:02       9 阅读
  4. 智能数据分析(2)Lecture 9-11

    2024-06-15 14:54:02       9 阅读
  5. 在远程服务器上安装虚拟环境

    2024-06-15 14:54:02       7 阅读
  6. PostgreSQL的视图pg_rules

    2024-06-15 14:54:02       7 阅读
  7. Python语言例题集(015)

    2024-06-15 14:54:02       8 阅读