Roland
Roland

Reputation: 7863

What is the difference between global scope and environment?

Is the global scope the same as the environment?

The declare builtin has a -g option:

The -g option forces variables to be created or modified at the global scope, even when declare is executed in a shell function. It is ignored in all other cases.

Upvotes: 1

Views: 93

Answers (1)

chepner
chepner

Reputation: 531918

TL;DR The global scope is initialized from the environment at startup, but is not the same as the environment.


The environment is a set of strings of the form <name>=<value> provided by the parent process. On startup, the shell takes each string whose <name> portion is a valid shell identifier and creates a variable in the global scope with that name.

For example, an environment string FOO=3 becomes a shell variable named FOO with the value 3.

On the other hand, an environment string like 10=6 is ignored by the shell, because 10 is not a valid shell identifier. The string remains in the environment, though, to be passed on to any child processes that might expect such a string. [UPDATE: The POSIX spec does not require such strings to be ignored; a conforming shell could either keep or discard them.]

There are also local variables, created by commands like local and declare inside a function definition. For example:

$ foo () { declare x; x=3; echo "$x"; }
$ x=2
$ foo
3
$ echo "$x"
2

x=2 created (or changed the value of) a variable in the global scope. Inside the function, declare x created a local variable. Changes to that variable did not affect the global by the same name.

The -g option to declare lets you make the name x inside the function refer to the global scope, rather than creating a local variable.

$ foo () { declare -g x; x=3; echo "$x"; }
$ x=2
$ foo
3
$ echo "$x"
3

Upvotes: 4

Related Questions