Bash – Exporting a variable from inside a function equals to global export of that variable

bashenvironment-variablesfunctionshell-scriptsubshell

I use Ubuntu 16.04 with the native Bash on it.

I'm not sure if executing

#!/bin/bash
myFunc() {
    export myVar="myVal"
}
myFunc

equals in any sense, to just executing export myVar="myVal".

Of course, a global variable should usually be declared outside of a function (a matter of convention I assume, even if technically possible) but I do wonder about the more exotic cases where one writes some very general function and wants a variable inside it to still be available to everything, anywhere.

Would export of a variable inside a function, be identical to exporting it globally, directly in the CLI, making it available to everything in the shell (all subshells, and functions inside them)?

Best Answer

Your script creates an environment variable, myVar, in the environment of the script. The script, as it is currently presented, is functionally exactly equivalent to

#!/bin/bash

export myVar="myVal"

The fact that the export happens in the function body is not relevant to the scope of the environment variable (in this case). It will start to exist as soon as the function is called.

The variable will be available in the script's environment and in the environment of any other process started from the script after the function call.

The variable will not exist in the parent process' environment (the interactive shell that you run the script from), unless the script is sourced (with . or source) in which case the whole script will be executing in the interactive shell's environment (which is the purpose of "sourcing" a shell file).

Without the function call itself:

myFunc() {
    export myVar="myVal"
}

Sourcing this file would place myFunc in the environment of the calling shell. Calling the function would then create the environment variable.

See also the question What scopes can shell variables have?

Related Question