bash – What is export for?


Observing Bash scripts note that variables can be created in the following ways: :

export variable2="Hola tambien"

I wanted to know more about the difference of these 2 ways to declare the variables. And from what I understood, export would serve to make global variables.

But on exceeding the script and trying to print the global variable2 , I get the same result as my script's local variable variable1

$ ./ 
$ echo $variable1
$ echo $variable2

Making use of the source command or using . and performing the same previous procedure, I get the printing of the 2 variables as a result.

$ source 
$ echo $variable1
$ echo $variable2
Hola tambien

At this point I understood that the purpose of export is not to declare global variables.

What is the purpose of export?


export makes the variable available to running shell threads . It puts the variable in the environment so that other processes can make use of them.

Sometimes it is used to put a configuration path, a password, For example, to indicate that your pager is less , then you write export PAGER=less , and every time you use man <programa> in that session, it will use less as a pager. It could also be most , etc.

I give you an example script so you can see what export does.


export var1="Esta variable es global"

principal() {

    bash -c '
    echo -e "\nEn la parte principal"
    echo "Imprimiendo \$var1: $var1"
    echo "Imprimiendo \$var2: $var2"'

export var2  # A partir de aquí ya debería aparecer el valor de "var2"

Whose execution gives:

$ ./export

En la parte principal
Imprimiendo $var1: Esta variable es global
Imprimiendo $var2:

En la parte principal
Imprimiendo $var1: Esta variable es global
Imprimiendo $var2: Variable2

I used bash -c 'etc' to open a thread, and the first time it is executed, it does not show any value of the variable var2 , but after calling export var2 .

Scroll to Top