Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 402
Roland Avatar asked Jul 18 '26 07:07

Roland


1 Answers

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.

like image 117
chepner Avatar answered Jul 19 '26 19:07

chepner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!