linux shell 变量继承问题

Shell 变量继承问题

问题与疑惑

已知

  • 命令替换会创建一个子shell(《Linux命令行与Shell脚本大全》时,第11章,11.4.3,最后部分的警告)
  • 圆括号命令组,也会创建子shell

又知

  • 除非对变量进行export,否则子shell无法继承父shell的变量、或者说父shell定义的变量在子shell中不可见。(根据《Linux命令行与Shell脚本大全》,第6章,6.2.1)

但是
在实践中,命令替换与圆括号命令组,都可以使用当前shell环境当中的变量,如下

#父shell定义的变量,没有export
var1=aaa
# 1、命令替换所在的子shell可以看见父shell中未export的变量
var2=$(echo $var1)
# 2、圆括号命令组的子shell同样可以看见父shell中未export的变量
(
	echo $var1
)

问题解决

根据Bash Manual, 3.7.3 Command Execution Environment

Command substitution, commands grouped with parentheses, and asynchronous commands are invoked in a subshell environment that is a duplicate of the shell environment, except that traps caught by the shell are reset to the values that the shell inherited from its parent at invocation. Builtin commands that are invoked as part of a pipeline are also executed in a subshell environment. Changes made to the subshell environment cannot affect the shell’s execution environment.

命令替换,放在()中的命令组,以及异步命令,这三种命令会在子shell中环境中创建,该子shell环境是当前shell的一份副本

参考

https://unix.stackexchange.com/questions/410721/variable-inherited-in-the-subshell-without-exporting-in-the-main-shell
https://www.gnu.org/software/bash/manual/html_node/Command-Execution-Environment.html#Command-Execution-Environment

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值