简体   繁体   中英

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.

export doesn't copy values in to the current environment. Instead, it sets the export attribute on a name . 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.

declare inside a functions defaults to local . Use -g to declare a global from inside a function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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