In the previous paragraph, I said:
- The true face of the so-called environment variable is actually an arbitrary string.
- When Bash starts, it imports a string containing the = sign into its own variable in the Environ array.
- Bash starts an external command by reorganizing its internal variables labeled as environment variables into a string array to assign to Environ
In this article, we continue to talk about three points:
- The Environ array may have an element with the same name on the left, which is the environment variable with the same name, how does Bash import?
- Bash can also import functions from environment variables and even import two variables and functions with the same name
- Bash can also export two variables and functions with the same name
If there are two environment variables with the same name, it is very simple, then the following values will overwrite the previous one:
$ env foo=1 foo=2 bash-c ' echo $foo ' 2 |
In the previous article we did not mention the function, Bash can actually import functions from the environment variables, such as the following:
$ foo () {echo foo function;} $ export-f Foo $ bash $ foo Foo function |
How did the Shell of the upper level pass the function to its child shell,bash? Let's demonstrate with the env command:
$ Env ' bash_func_foo%%= () {echo foo function;} ' bash-c ' foo ' Foo function |
In fact, Bash is to satisfy the "BASH_FUNC_ function name%%= () {function Body" format of the environment variables as the source code parsing and import. So two variables and functions with the same name do not conflict and can be imported at the same time, like this:
$ env ' foo=1 ' bash_func_foo%%= () {echo $;} ' bash-c ' foo $foo ' 1 |
Since you can import at the same time, then the export is no problem:
$ foo=1 $ foo () {echo foo function;} $ Export foo;export-f foo $ env ... Foo=1 Bash_func_foo%%= () {echo foo function } ... |
Previous versions of Bash 4.3.30
Note that the performance of this article only applies to bash 4.3.30 and later versions, the previous bash version does not add a BASH_FUNC_ prefix and a percent suffix to the function name when exporting the function, nor does it recognize the prefix suffix on import, as long as you see that the right side is "() {" Four characters, press the letter Number of imports, like this:
$ Env ' foo= () {echo foo function;} ' bash-c ' foo ' Foo function |
Since the conversion and recognition rules for environment variable strings are different, if you open a bash 3.2.25 in bash 4.3.30, the latter cannot be inherited to the former exported function:
$ bash4.3.30 $ foo () {echo foo function;} $ export-f Foo $ bash3.2.25 $ foo Bash3.2.25:foo:command not found |
And vice versa, and Foo is imported into a variable:
$ bash3.2.25 $ foo () {echo foo function;} $ export-f Foo $ bash4.3.30 $ foo Bash3.2.25:foo:command not found $ echo $foo () {echo foo function} |
How Bash imports a function from an environment variable