Reputation: 7875
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.
Upvotes: 6
Views: 3767
Reputation: 532093
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.
Upvotes: 8
Reputation: 242123
declare
inside a functions defaults to local
. Use -g
to declare a global from inside a function.
Upvotes: 6