Bash Environment Variables Tutorial

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

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

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

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

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

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

auto_resume Controls how the shell interacts with the user and job control.
BASH Provides the full pathname which is used to execute the current Bash session
BASH_ENV Value of this variable is expanded and used as the name of a startup file before a script is executed
BASH_VERSION Provides version number of the current instance of the Bash shell
BASH_VERSINFO Provides version information of the current instance of the Bash shell
COLUMNS Used by the plugins to determine the terminal width when printing selection lists.
COMP_CWORD Provides the current cursor position on the shell
COMP_LINE Provides the current line number on the shell
COMP_POINT Provides index of the current cursor position relative to the beginning of the current command
COMP_WORDS An array which provides a list of the unique words in the command line
COMPREPLY An array of String values through which Bash provides auto-completion functionality
DIRSTACK An array of String values containing the contents of the current directory stack
EUID Provides user ID of the current user
FCEDIT The editor used as a default by the -e option to the fc built-in command.
FIGNORE A colon-separated list of suffixes String values which need to be ignored when performing filename completion in the command line
FUNCNAME Returns the name of shell function in execution
GLOBIGNORE A colon-separated list of suffixes String patterns which need to be ignored during filename expansion
GROUPS Defines the list of groups of which the current user is a member of
HISTCMD The index in the history list of the current command
HISTCONTROL Defines if a command is added to the history file
HISTFILE Provides the name of the file where the command history is stored. The default value is ~/.bash_history.
HISTFILESIZE Defines the maximum number of lines stored in the history file
HISTIGNORE A colon-separated pattern Strings used to decide which command lines should be stored in the history file
HISTSIZE Defines the maximum count of commands to store on the history list
HOSTFILE Contains the name of a file in the same format as /etc/hosts that should be read when the shell needs to complete a hostname
HOSTNAME Provides the name of the current host
HOSTTYPE Provides name of the machine Bash is running on
IGNOREEOF Decide what to do when command receives EOF input only
INPUTRC Provides name of the Readline initialization file, default is /etc/inputrc
LANG Determine the locale category not selected with a variable starting with LC_.
LC_ALL Overrides the value of LANG and LC_ values specifying a locale category
LC_CTYPE Defines how characters and the character classes are interpreted when filename expansion and pattern matching is done
LC_MESSAGES Provides locale data used to translate double-quoted strings preceded by a “$” symbol.
LC_NUMERIC Provides locale category used for formatting numbers
LINENO Provides line number of the script or shell function currently executing
MACHTYPE A string that fully describes the system type on which Bash is executing, in the standard GNU CPU-COMPANY-SYSTEM format
OLDPWD The previous working directory as set by the cd command
OPTERR If set to the value 1, Bash displays error messages generated by the getopts built-in
OSTYPE Describes the OS Bash is running on
PIPESTATUS An array variable containing a list of exit status values from the processes in the most recently executed foreground pipeline
POSIXLY_CORRECT If this variable is set, the shell will enter POSIX mode on start
PPID Defined process ID of the shell’s parent process
PROMPT_COMMAND If set, the value is interpreted as a command to execute before the printing of each primary prompt (PS1).
PS3 The value of this variable is used as the prompt for the select command. Defaults to “‘#? ‘”
PS4 The value is the prompt printed before the command line is echoed when the -x option is set; defaults to “‘+ ‘”.
PWD Defines the current working directory
RANDOM Each 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.
REPLY The default variable for the read built-in
SECONDS Defines current shell life in seconds
SHELLOPTS List of shell options which are currently enabled
SHLVL Count of currently active Bash shells
TIMEFORMAT Format of date to be shown in shell
UID User 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:

CDPATH A colon-separated list of directories used as a search path for the cd built-in command.
HOME The current user’s home directory; the default for the cd built-in. The value of this variable is also used by tilde expansion.
IFS A list of characters that separate fields; used when the shell splits words as part of the expansion
MAIL If 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.
MAILPATH A colon-separated list of the filename which the shell periodically checks for new mail.
OPTARG The value of the last option argument processed by the getopts command
OPTIND The index of the last option argument processed by the getopts command
PATH A colon-separated list of directories in which the shell looks for commands.
PS1 Defines first prompt string with default value of “‘s-v$ ‘”.
PS2 Defines 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.
$@ 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
$0 Provides 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

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.

Related Posts
Leave a Reply

Your email address will not be published.Required fields are marked *