Home Bash Tips Difference Between Defining Bash Variables With And Without export

Difference Between Defining Bash Variables With And Without export

By sk
Published: Last Updated on 2.4K views

I've added this "export HISTCONTROL=ignoredups" line in ~/.bashrc file to avoid duplicate entries in Bash history in my Linux desktop. Did you notice that I prefixed the HISTCONTROL variable with "export"? Do you know - what is "export" option for? If you are wondering what is the difference between defining bash variables with and without export option, read on!

Difference Between Defining Bash Variables With And Without export

We define a variable with export to make it available to all sub-processes(or child processes). Meaning - if you define a variable with export like below,

export variable_name=value

The variable is available to any sub-process you run from that shell process.

If you define a variable without export like below,

variable_name=value

The variable is limited to the shell and it is not available to any other sub-process. You can use it for temporary and/or loop variables.

Allow me to show you an example, so you can understand it better.

Let me define a variable named "ostechnix" without "export" like below:

$ ostechnix="Welcome to ostechnix.com blog!"

Now display the value using "echo" command:

$ echo $ostechnix

It will display the value of ostechnix variable:

Welcome to ostechnix.com blog!

Now, start a new Bash shell session by running the following command:

$ bash

Then, try to display the value of ostechnix variable using echo command:

$ echo $ostechnix
Define bash variable without export
Define bash variable without export

See? It doesn't return anything! You see only blank output. Hence it is proved that when we define a variable without export, it will not be available to child processes.

Let us again define the same variable with export option:

$ export ostechnix="Welcome to ostechnix.com blog!"

Display the value of the variable:

$ echo $ostechnix

Sample output:

Welcome to ostechnix.com blog!

Start a new shell session:

$ bash

Try again to display the variable's value:

$ echo $ostechnix

It will now return the value.

Difference Between Defining Bash Variables With And Without export
Difference between defining Bash variables with and without export

Hence, the export makes the variable available to any other child processes in that shell environment.

You May Also Like

Leave a Comment

* By using this form you agree with the storage and handling of your data by this website.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

This website uses cookies to improve your experience. By using this site, we will assume that you're OK with it. Accept Read More