Bash Scripting - Exporting Variables

We will discuss exporting variables in this article. In my earlier posts, we saw various examples of variable usage, but they only applied locally to the execution time. In other words, the variables will be lost if you log out (close the Shell). What if you want to use those variables again? The variables must be "Exported" if they are to be available to the user who created them or to any other user of the system.


Let's see how it works:

first, we will create a local variable:

[root@scriptbox scripts]# SEASON="Summer"

Now, we create a simple script:

#!/bin/bash

echo "The $SEASON is very hot this year"

And let's run it:

[root@scriptbox scripts]# ./vars.sh
The  is very hot this year

As you can see, the value of our local variable is missing from the script result:

Let's now correct it by exporting this variable so that all child shells of this parent shell can access it:

[root@scriptbox scripts]# export SEASON
[root@scriptbox scripts]# ./vars.sh    
The Summer is very hot this year
[root@scriptbox scripts]#


The previous mentioned example is still only temporary, and the variable data will also be lost if I log out of the shell. To make our variables accessible and available at all times, regardless of whether or not we close the shell, we can define them in the user home directory. ".bashrc".

[vagrant@scriptbox ~]$ ls -a
.  ..  .ansible  .bash_history  .bash_logout  .bash_profile  .bashrc  .ssh  .vbox_version
[vagrant@scriptbox ~]$

Our variables would be permanent and always available if we put them in this file (Per user, as the file is created per user that logged on to the system). Here is an example:

[vagrant@scriptbox ~]$ vim .bashrc

# .bashrc

# Source global definitions
if [ -f /etc/bashrc ]; then
        . /etc/bashrc
fi

# Uncomment the following line if you don't like systemctl's auto-paging feature:
# export SYSTEMD_PAGER=

# User specific aliases and functions

#Exported vars are here:
export SEASON="Summer"

Although this workaround may be great, we still want to use our variables globally so that we don't have to use unique files for each user. Let's look at the procedure:

[root@scriptbox ~]# vim /etc/profile

Note: The sequence is : First global variable (Profile file) and than local variable (bashrc file)

[root@scriptbox ~]# echo $SEASON
Winter



1 view0 comments