BASH

Bash Environment Variables Tutorial

This is a Bash Environment Variables Tutorial. There exists two types of variables:

  • Global Variables
  • Local Variables

Global variables or environment variables are available in all shells. The env or printenv commands can be used to display environment variables. Local variables are only available in the current shell.
 
 
 


 
Apart from dividing variables in local and global variables, we can also divide them in categories according to the sort of content the variable contains. In this respect, variables come in four types:

  • String Variables
  • Integer Variables
  • Constant Variables
  • Array Variables

The details and differences of the types will discussed in another article.

The following table shows an overview of the whole article:

1. Creating Variables

Variables are case sensitive and capitalized by default. Giving local variables a lowercase name is a convention which is sometimes applied. However, you are free to use the names you want or to mix cases.

Variables can also contain digits, but a name starting with a digit is not allowed:

The Output of the Shell Script
The Output of the Shell Script

To set a variable in the shell, use

 
VARNAME="value"

Putting spaces around the equal sign will cause errors. It is a good habit to quote content strings when assigning values to variables: this will reduce the chance that you make errors.

An example how to set a variable with space, upper- and lowercase letters:

An Example about System Environment Variables
An Example about System Environment Variables

2. Exporting Variables

A variable created like the ones in the example above is only available to the current shell. It is a local variable. Child processes of the current shell will not be aware of this variable.

In order to pass variables to a subshell, we need to export them using the export built-in command. Variables that are exported are referred to as environment variables. Setting and exporting is usually done in one step:

 
export VARNAME="value"

A subshell can change variables it inherited from the parent, but the changes made by the child don’t affect the parent.

An Example how to export an Environment Variable
An Example how to export an Environment Variable

3. Reserved Variables

3.1 Bourne shell reserved variables

Bash uses certain shell variables in the same way as the Bourne shell. In some cases, Bash assigns a default value to the variable. The table below gives an overview of these plain shell variables:

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 expansion.
MAILIf this parameter is set to a file name 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 file names which the shell periodically checks for new mail.
OPTARGThe value of the last option argument processed by the getopts built-in.
OPTINDThe index of the last option argument processed by the getopts built-in.
PATHA colon-separated list of directories in which the shell looks for commands.
PS1The primary prompt string. The default value is “‘\s-\v\$ ‘”.
PS2The secondary prompt string. The default value is “‘> ‘”.

3.2 Bash reserved variables

These variables are set or used by Bash, but other shells do not normally treat them specially.

auto_resumeThis variable controls how the shell interacts with the user and job control.
BASHThe full pathname used to execute the current instance of Bash.
BASH_ENVIf this variable is set when Bash is invoked to execute a shell script, its value is expanded and used as the name of a startup file to read before executing the script.
BASH_VERSIONThe version number of the current instance of Bash.
BASH_VERSINFOA read-only array variable whose members hold version information for this instance of Bash.
COLUMNSUsed by the select built-in to determine the terminal width when printing selection lists. Automatically set upon receipt of a SIGWINCH signal.
COMP_CWORDAn index into ${COMP_WORDS} of the word containing the current cursor position.
COMP_LINEThe current command line.
COMP_POINTThe index of the current cursor position relative to the beginning of the current command.
COMP_WORDSAn array variable consisting of the individual words in the current command line.
COMPREPLYAn array variable from which Bash reads the possible completions generated by a shell function invoked by the programmable completion facility.
DIRSTACKAn array variable containing the current contents of the directory stack.
EUIDThe numeric effective 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 to ignore when performing file name completion.
FUNCNAMEThe name of any currently-executing shell function.
GLOBIGNOREA colon-separated list of patterns defining the set of file names to be ignored by file name expansion.
GROUPSAn array variable containing the list of groups of which the current user is a member. histchars Up to three characters which control history expansion, quick substitution, and tokenization.
HISTCMDThe history number, or index in the history list, of the current command.
HISTCONTROLDefines whether a command is added to the history file.
HISTFILEThe name of the file to which the command history is saved. The default value is ~/.bash_history.
HISTFILESIZEThe maximum number of lines contained in the history file, defaults to 500.
HISTIGNOREA colon-separated list of patterns used to decide which command lines should be saved in the history list.
HISTSIZEThe maximum number of commands to remember on the history list, default is 500.
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.
HOSTNAMEThe name of the current host.
HOSTTYPEA string describing the machine Bash is running on.
IGNOREEOFControls the action of the shell on receipt of an EOF character as the sole input.
INPUTRCThe name of the Readline initialization file, overriding the default /etc/inputrc.
LANGUsed to determine the locale category for any category not specifically selected with a variable starting with LC_.
LC_ALLThis variable overrides the value of LANG and any other LC_ variable specifying a locale category.
LC_COLLATEThis variable determines the collation order used when sorting the results of file name expansion, and determines the behavior of range expressions, equivalence classes, and collating sequences within file name expansion and pattern matching.
LC_CTYPEThis variable determines the interpretation of characters and the behavior of character classes within file name expansion and pattern matching.
LC_MESSAGESThis variable determines the locale used to translate double-quoted strings preceded by a “$” sign.
LC_NUMERICThis variable determines the locale category used for number formatting.
LINENOThe line number in the script or shell function currently executing.
LINESUsed by the select built-in to determine the column length for printing selection lists.
MACHTYPEA string that fully describes the system type on which Bash is executing, in the standard GNU CPU-COMPANY-SYSTEM format.
MAILCHECKHow often (in seconds) that the shell should check for mail in the files specified in the MAILPATH or MAIL variables.
OLDPWDThe previous working directory as set by the cd built-in.
OPTERRIf set to the value 1, Bash displays error messages generated by the getopts built-in.
OSTYPEA string describing the operating system Bash is running on.
PIPESTATUSAn array variable containing a list of exit status values from the processes in the most recently executed foreground pipeline (which may contain only a single command).
POSIXLY_CORRECTIf this variable is in the environment when bash starts, the shell enters POSIX mode.
PPIDThe 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 “‘+ ‘”.
PWDThe current working directory as set by the cd built-in command.
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.
SECONDSThis variable expands to the number of seconds since the shell was started.
SHELLOPTSA colon-separated list of enabled shell options.
SHLVLIncremented by one each time a new instance of Bash is started.
TIMEFORMATThe value of this parameter is used as a format string specifying how the timing information for pipelines prefixed with the time reserved word should be displayed.
TMOUTIf set to a value greater than zero, TMOUT is treated as the default timeout for the read built-in. In an interative shell, the value is interpreted as the number of seconds to wait for input after issuing the primary prompt when the shell is interactive. Bash terminates after that number of seconds if input does not arrive.
UIDThe numeric, real user ID of the current user.

The following image shows an Example, how to display reserved Environment Variables:

An Example how to set a local Environment Variable
An Example how to set a local Environment Variable

4. Special Parameters

The shell treats several parameters specially. These parameters may only be referenced. Assignment to them is not allowed.

$*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.
$@Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, each parameter expands to a separate word.
$#Expands to the number of positional parameters in decimal.
$?Expands to the exit status of the most recently executed foreground pipeline.
$-A hyphen expands to 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).
$$Expands to the process ID of the shell.
$!Expands to the process ID of the most recently executed background (asynchronous) command.
$0Expands to the name of the shell or shell script.
$_The underscore variable is set at shell startup and contains the absolute file name of the shell or script being executed as passed in the argument list. Subsequently, it expands to the last argument to the previous command, after expansion.

The positional parameters are the words following the name of a shell script. They are put into the variables $1, $2, $3 and so on. As long as needed, variables are added to an internal array. $# holds the total number of parameters, as is demonstrated with this simple script:

positional.sh

 
#!/bin/bash
# positional.sh
# This script reads 3 positional parameters and prints them out.
POSPAR1="$1"
POSPAR2="$2"
POSPAR3="$3"
echo "$1 is the first positional parameter, \$1."
echo "$2 is the second positional parameter, \$2."
echo "$3 is the third positional parameter, \$3."
echo
echo "The total number of positional parameters is $#."

The following GUI shows the result of calling the Shell-Script with four parameters:

An Example of an invalid Environment Variable Name
An Example of an invalid Environment Variable Name

5. Summary

This was a simple Example about Bash Environment Variables. We have discussed how to set, to display, to export local and global Variables. We also learned some Reserved Variables, which depends on the given Shell. Finally we have written a Script to demonstrate the Usage of Special Parameters.

Andreas Pomarolli

Andreas has graduated from Computer Science and Bioinformatics at the University of Linz. During his studies he has been involved with a large number of research projects ranging from software engineering to data engineering and at least web engineering. His scientific focus includes the areas of software engineering, data engineering, web engineering and project management. He currently works as a software engineer in the IT sector where she is mainly involved with projects based on Java, Databases and Web Technologies.
Subscribe
Notify of
guest

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

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button