简体   繁体   English

将函数局部变量导出到环境

[英]Exporting a function local variable to the environment

Consider the following code:考虑以下代码:

#!/usr/bin/bash

t_export() {
  declare dummy="Hello"
  export dummy
  echo dummy: $dummy
  echo printenv dummy: $(printenv dummy)
}

t_export
echo dummy: $dummy
echo printenv dummy: $(printenv dummy)

Output:输出:

dummy: Hello
printenv dummy: Hello
dummy:
printenv dummy:

How do you explain this?你怎么解释这个? I thought the environment is always global and therefore the variable dummy would also be visible outside the function.我认为环境总是全局的,因此变量dummy在函数外部也是可见的。

export doesn't copy values in to the current environment. export不会将值复制到当前环境中。 Instead, it sets the export attribute on a name .相反,它在name上设置 export 属性。 When a new processes is started, any variables marked with that attribute are copied (along with their current values) into the environment of the new process.当一个新进程启动时,任何标有该属性的变量(连同它们的当前值)都被复制到新进程的环境中。

When t_export returns, the variable dummy goes out of scope, which means it is no longer available to be exported to new processes.t_export返回时,变量dummy超出范围,这意味着它不再可用于导出到新进程。

declare inside a functions defaults to local .在函数内部declare默认为local Use -g to declare a global from inside a function.使用-g从函数内部声明全局。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM