BASH Programming Dev Ops System Administration

Bash Environment Variables Tutorial

Overview

Whenever we talk to a remote server or do anything on a shell, the shell stores data in form of variables which it stores in an area which is called the environment. The shell environment can be defined as a storage area which the shell compiles every time a new session for a shell is started. This is done so that the environment contains any local or global variables we’ve defined since its last start. We will learn about what local and global variables are in the coming section.

Types of Environment Variables

In a Bash environment, there are two types of environment variables which can be defined by a user to be used in scripts or the shell programs they write:

  1. Global Variables
  2. Local Variables

The Global variables which are defined as an environment variables are available in all shell sessions which shell compiles but the local variables are only available in the currently executing shell and they will be lost once the shell session is closed. In this lesson, we will study how to define global and local variables for a Bash environment and we will also see what are some of the reserved variables which cannot be set as either local or global variables in a Bash environment.

Creating Variables

Both local and global variables are case sensitive and usually capitalised. According to a convention, local variables should be kept lowercase and global variables should be kept uppercase. Although this is just a convention and you are free to keep any name for both local and global variables. A variable name cannot start with a number and should only contain characters in the beginning.

Let us try creating an invalid variable with an example:

export 1var=23

Here is what we get back with this command:

Creating invalid variable

Creating invalid variable

A general rule of thumb to create variables is shown below:

VARIABLE_NAME="value"

Note that NOT putting spaces around the equal symbol will cause errors. Also, it is a good habit to quote the string values we define for the variable so that there are less chances for errors. Let’s try defining a variable and print it on the shell:

website="linuxhint"
echo $website

Here is what we get back with this command:

Print variable

Print variable

Note that the variable we defined in above shell is a local variable and this variable will be deleted as soon as we restart the shell. To confirm this, restart the shell and try printing the variable again:

Local variable is lost on shell restart

Local variable is lost on shell restart

Exporting Variables

To convert a local variable we defined above into a global variable, we can export the variable by adding it to the .bashrc file so that is available even across shell restarts. Edit the .bashrc file with this command:

nano ~/.bashrc

We will now edit the file and add the following content at the end:

# Setting environment variables
export WEBSITE='LinuxHint'

Once the content is added, save and quit the file. If we now try to print the variable, it will still not exist. This is because we need to reload the file into the memory with the following command:

source ~/.bashrc

Once this is done, the variable will be printed (even across restarts):

Export variables

Export variables

Reserved Variables

Bash reserved variables

Reserved Variables in Bash are the one which is pre-defined in the shell. We can use them without defining them, like:

Print reserved variables

Print reserved variables

There is a complete list of variables in BASH, like:

auto_resumeControls how the shell interacts with the user and job control.
BASHProvides the full pathname which is used to execute the current Bash session
BASH_ENVValue of this variable is expanded and used as the name of a startup file before a script is executed
BASH_VERSIONProvides version number of the current instance of the Bash shell
BASH_VERSINFOProvides version information of the current instance of the Bash shell
COLUMNSUsed by the plugins to determine the terminal width when printing selection lists.
COMP_CWORDProvides the current cursor position on the shell
COMP_LINEProvides the current line number on the shell
COMP_POINTProvides index of the current cursor position relative to the beginning of the current command
COMP_WORDSAn array which provides a list of the unique words in the command line
COMPREPLYAn array of String values through which Bash provides auto-completion functionality
DIRSTACKAn array of String values containing the contents of the current directory stack
EUIDProvides user ID of the current user
FCEDITThe editor used as a default by the -e option to the fc built-in command.
FIGNOREA colon-separated list of suffixes String values which need to be ignored when performing filename completion in the command line
FUNCNAMEReturns the name of shell function in execution
GLOBIGNOREA colon-separated list of suffixes String patterns which need to be ignored during filename expansion
GROUPSDefines the list of groups of which the current user is a member of
HISTCMDThe index in the history list of the current command
HISTCONTROLDefines if a command is added to the history file
HISTFILEProvides the name of the file where the command history is stored. The default value is ~/.bash_history.
HISTFILESIZEDefines the maximum number of lines stored in the history file
HISTIGNOREA colon-separated pattern Strings used to decide which command lines should be stored in the history file
HISTSIZEDefines the maximum count of commands to store on the history list
HOSTFILEContains the name of a file in the same format as /etc/hosts that should be read when the shell needs to complete a hostname
HOSTNAMEProvides the name of the current host
HOSTTYPEProvides name of the machine Bash is running on
IGNOREEOFDecide what to do when command receives EOF input only
INPUTRCProvides name of the Readline initialization file, default is /etc/inputrc
LANGDetermine the locale category not selected with a variable starting with LC_.
LC_ALLOverrides the value of LANG and LC_ values specifying a locale category
LC_CTYPEDefines how characters and the character classes are interpreted when filename expansion and pattern matching is done
LC_MESSAGESProvides locale data used to translate double-quoted strings preceded by a “$” symbol.
LC_NUMERICProvides locale category used for formatting numbers
LINENOProvides line number of the script or shell function currently executing
MACHTYPEA string that fully describes the system type on which Bash is executing, in the standard GNU CPU-COMPANY-SYSTEM format
OLDPWDThe previous working directory as set by the cd command
OPTERRIf set to the value 1, Bash displays error messages generated by the getopts built-in
OSTYPEDescribes the OS Bash is running on
PIPESTATUSAn array variable containing a list of exit status values from the processes in the most recently executed foreground pipeline
POSIXLY_CORRECTIf this variable is set, the shell will enter POSIX mode on start
PPIDDefined process ID of the shell’s parent process
PROMPT_COMMANDIf set, the value is interpreted as a command to execute before the printing of each primary prompt (PS1).
PS3The value of this variable is used as the prompt for the select command. Defaults to “‘#? ‘”
PS4The value is the prompt printed before the command line is echoed when the -x option is set; defaults to “‘+ ‘”.
PWDDefines the current working directory
RANDOMEach time this parameter is referenced, a random integer between 0 and 32767 is generated. Assigning a value to this variable seeds the random number generator.
REPLYThe default variable for the read built-in
SECONDSDefines current shell life in seconds
SHELLOPTSList of shell options which are currently enabled
SHLVLCount of currently active Bash shells
TIMEFORMATFormat of date to be shown in shell
UIDUser ID of current active user of the shell

Try printing these variables to see how they work just like we did in the beginning.

Bourne Shell reserved variables

Just like the Bash shell parameters we provided above, the Bourne shell also has some reserved variables. Here are the plain shell variables the shell defines:

CDPATHA colon-separated list of directories used as a search path for the cd built-in command.
HOMEThe current user’s home directory; the default for the cd built-in. The value of this variable is also used by tilde expansion.
IFSA list of characters that separate fields; used when the shell splits words as part of the expansion
MAILIf this parameter is set to a filename and the MAILPATH variable is not set, Bash informs the user of the arrival of mail in the specified file.
MAILPATHA colon-separated list of the filename which the shell periodically checks for new mail.
OPTARGThe value of the last option argument processed by the getopts command
OPTINDThe index of the last option argument processed by the getopts command
PATHA colon-separated list of directories in which the shell looks for commands.
PS1Defines first prompt string with default value of “‘\s-\v\$ ‘”.
PS2Defines secondary prompt string with the default value of “‘> ‘”

Special Parameters

We can also have parameters which the shell treats specially which can only be used as references and assigning a value to them is not possible.

$*Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, it expands to a single word with the value of each parameter separated by the first character of the IFS special variable.
[email protected]Provides the positional parameters, starting from one. When the expansion occurs within double quotes, each parameter expands to a separate word.
$#Provides the number of positional parameters in decimal.
$?Provides the exit status of the most recently executed foreground pipeline.
$-A hyphen-sign provides the current option flags as specified upon invocation, by the set built-in command, or those set by the shell itself (such as the -i)
$$Provides the current process ID of the shell
$!Provides the current process ID of the most recently executed background command
$0Provides the name of the current shell or shell script

Let’s try an example of the positional parameters:

echo "$1 is the 1st positional parameter."
echo "$2 is the 2nd positional parameter."
echo "$3 is the 3rd positional parameter."
echo
echo "Total number of positional parameters is $#."

When we run this command with some parameters, we can see the following output:

Print positional params

Print positional params

Conclusion

In this lesson, we looked at how we can define and use variables in a Bash environment and what are the reserved variables in a shell.

About the author

Shubham Aggarwal

Shubham Aggarwal

I’m a Java EE Engineer with about 4 years of experience in building quality products. I have excellent problem-solving skills in Spring Boot, Hibernate ORM, AWS, Git, Python and I am an emerging Data Scientist.