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;
{
// ...
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lylhw13_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值