How-to: Shell variables and Environment variables

You can use variables in bash as in any programming language. There are no data types so a variable can contain a number, or a string of characters. There is no need to declare a variable, just assign a value:

STR="Hello World"
echo "$STR"

The VALUE of a variable is retrieved by placing a '$' before the variable name.

When echoing a variable it is important to surround the variable" in quotes", otherwise echo will expand the variable and attempt to perform globbing with any files that match in the current directory.

When you reference a variable in bash it is important not to put spaces around the equals sign: STR= 2, STR = 2, and STR =2 all mean slightly different things - the extra spaces will not throw a syntax error.

Bash variables are typically all-caps but lower or mixed case is also supported.

Shell variables are Global within bash, while an environment variable is visible to every process on the OS.

Reading (quoting) a variable

When reading a variable it is often useful to use parameter expansion(bash) to clearly indicate the variable name.
For example if you have a variable $MYVAR containing a filename (as a string) and want to do a rename, you might try:

mv "$MYVAR" "$MYVAR_bak" # this won’t work because bash will expect a variable called MYVAR_bak

To fix this, replace $MYVAR with ${MYVAR} which expands to the string value we want.

mv "$MYVAR" "${MYVAR}_bak"

Example - using the $? shell parameter to obtain an exit code from ls.

#!/bin/bash 
ls ~/file-that-doesnt-exist
EXITCODE=$? 
if [ "$EXITCODE" = "0" ]; then
  echo All OK
else     
  echo File Not found
fi

Shell and environment variables:

The shell maintains a list of variables, each of which has as value a list of zero or more words.

The values of shell variables can be displayed and changed with the echo, set and unset commands.

The system maintains its own list of environment variables. These can be displayed and changed with printenv, setenv and unsetenv.

(+) Variables may be made read-only with set -r (q.v.)

Read-only variables may not be modified or unset; attempting to do so will cause an error. Once made read-only, a variable cannot be made writable, so set -r should be used with caution. Environment variables cannot be made read-only.

Some variables are set by the shell or referred to by it. For instance, the argv variable is an image of the shell’s argument list, and words of this variable’s value are referred to in special ways. Some of the variables referred to by the shell are toggles; the shell does not care what their value is, only whether they are set or not.
For instance, the verbose variable is a toggle which causes command input to be echoed. The -v command line option sets this variable. Special shell variables lists all variables which are referred to by the shell.

 

Default Shell Variables

Bash automatically assigns default values to a number of variables, which are listed below.
Bash uses certain shell variables in the same way as the Bourne shell.

CDPATH
A colon-separated list of directories used as a search path for the cd builtin command.
HOME
The current user’s home directory; the default for the cd builtin command. The value of this variable is also used by tilde expansion.
IFS
A list of characters that separate fields (Internal Field Separator or Input Field Separator) used when the shell splits words as part of expansion. By default this is set to Space, Tab and Newline.
To set this to Newline only, use IFS=$'\n'
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 filenames which the shell periodically checks for new mail. Each list entry can specify the message that is printed when new mail arrives in the mail file by separating the file name from the message with a '?'. When used in the text of the message, $_ expands to the name of the current mail file.
OPTARG
The value of the last option argument processed by the getopts builtin.
OPTIND
The index of the last option argument processed by the getopts builtin.
PATH
A colon-separated list of directories in which the shell looks for commands.
PS1
The primary prompt string. The default value is `\s-\v\$ '.
PS2
The secondary prompt string. The default value is `> '.

Bash Variables

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

A few variables used by Bash are described in different chapters: variables for controlling the job control facilities.

BASH
The full pathname used to execute the current instance of Bash.
BASH_ENV
If 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_VERSION
The version number of the current instance of Bash.
BASH_VERSINFO
A readonly array variable whose members hold version information for this instance of Bash. The values assigned to the array members are as follows:
BASH_VERSINFO[0]
The major version number (the release).
BASH_VERSINFO[1]
The minor version number (the version).
BASH_VERSINFO[2]
The patch level.
BASH_VERSINFO[3]
The build version.
BASH_VERSINFO[4]
The release status (e.g., beta1).
BASH_VERSINFO[5]
The value of MACHTYPE.
COMP_WORDS
An array variable consisting of the individual words in the current command line. This variable is available only in shell functions invoked by the programmable completion facilities.
COMP_CWORD
An index into ${COMP_WORDS} of the word containing the current cursor position. This variable is available only in shell functions invoked by the programmable completion facilities.
COMP_LINE
The current command line. This variable is available only in shell functions and external commands invoked by the programmable completion facilities.
COMP_POINT
The index of the current cursor position relative to the beginning of the current command. If the current cursor position is at the end of the current command, the value of this variable is equal to ${#COMP_LINE}. This variable is available only in shell functions and external commands invoked by the programmable completion facilities.
COMPREPLY
An array variable from which Bash reads the possible completions generated by a shell function invoked by the programmable completion facility.
DIRSTACK
An array variable containing the current contents of the directory stack. Directories appear in the stack in the order they are displayed by the dirs builtin. Assigning to members of this array variable can be used to modify directories already in the stack, but the pushd and popd builtins must be used to add and remove directories. Assignment to this variable will not change the current directory. If DIRSTACK is unset, it loses its special properties, even if it is subsequently reset.
EUID
The numeric effective user id of the current user. This variable is readonly.
FCEDIT
The editor used as a default by the `-e' option to the fc builtin command.
FIGNORE
A colon-separated list of suffixes to ignore when performing filename completion. A file name whose suffix matches one of the entries in FIGNORE is excluded from the list of matched file names. A sample value is `.o:~'
GLOBIGNORE
A colon-separated list of patterns defining the set of filenames to be ignored by filename expansion. If a filename matched by a filename expansion pattern also matches one of the patterns in GLOBIGNORE, it is removed from the list of matches.
GROUPS
An array variable containing the list of groups of which the current user is a member. Assignments to GROUPS have no effect and are silently discarded. If GROUPS is unset, it loses its special properties, even if it is subsequently reset.
histchars
Up to three characters which control history expansion, quick substitution, and tokenization. The first character is the history expansion character, that is, the character which signifies the start of a history expansion, normally `!'. The second character is the character which signifies `quick substitution' when seen as the first character on a line, normally `^'. The optional third character is the character which indicates that the remainder of the line is a comment when found as the first character of a word, usually `#'. The history comment character causes history substitution to be skipped for the remaining words on the line. It does not necessarily cause the shell parser to treat the rest of the line as a comment.
HISTCMD
The history number, or index in the history list, of the current command. If HISTCMD is unset, it loses its special properties, even if it is subsequently reset.
FUNCNAME
The name of any currently-executing shell function. This variable exists only when a shell function is executing. Assignments to FUNCNAME have no effect and are silently discarded. If FUNCNAME is unset, it loses its special properties, even if it is subsequently reset.
HISTCONTROL
A value of `ignorespace' means to not enter lines which begin with a space or tab into the history list. A value of `ignoredups' means to not enter lines which match the last entered line. A value of `ignoreboth' combines the two options. Unset, or set to any other value than those above, means to save all lines on the history list. The second and subsequent lines of a multi-line compound command are not tested, and are added to the history regardless of the value of HISTCONTROL.
HISTIGNORE
A colon-separated list of patterns used to decide which command lines should be saved on the history list. Each pattern is anchored at the beginning of the line and must match the complete line (no implicit '*' is appended). Each pattern is tested against the line after the checks specified by HISTCONTROL are applied. In addition to the normal shell pattern matching characters, `&' matches the previous history line. `&' can be escaped using a backslash; the backslash is removed before attempting a match. The second and subsequent lines of a multi-line compound command are not tested, and are added to the history regardless of the value of HISTIGNORE. HISTIGNORE subsumes the function of HISTCONTROL. A pattern of `&' is identical to ignoredups, and a pattern of `[ ]*' is identical to ignorespace. Combining these two patterns, separating them with a colon, provides the functionality of ignoreboth.
HISTFILE
The name of the file to which the command history is saved. The default value is ~/.bash_history
HISTSIZE
The maximum number of commands to remember on the history list. The default value is 500.
HISTFILESIZE
The maximum number of lines contained in the history file. When this variable is assigned a value, the history file is truncated, if necessary, to contain no more than that number of lines. The history file is also truncated to this size after writing it when an interactive shell exits. The default value is 500.
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. The list of possible hostname completions can be changed while the shell is running; the next time hostname completion is attempted after the value is changed, Bash adds the contents of the new file to the existing list. If HOSTFILE is set, but has no value, Bash attempts to read /etc/hosts to obtain the list of possible hostname completions. When HOSTFILE is unset, the hostname list is cleared.
HOSTNAME
The name of the current host.
HOSTTYPE
A string describing the machine Bash is running on.
IGNOREEOF
Controls the action of the shell on receipt of an EOF character as the sole input. If set, the value denotes the number of consecutive EOF characters that can be read as the first character on an input line before the shell will exit. If the variable exists but does not have a numeric value (or has no value) then the default is 10. If the variable does not exist, then EOF signifies the end of input to the shell. This is only in effect for interactive shells.
INPUTRC
The name of the Readline initialization file, overriding the default of ~/.inputrc.
LANG
Used to determine the locale category for any category not specifically selected with a variable starting with LC_.
LC_ALL
This variable overrides the value of LANG and any other LC_ variable specifying a locale category.
LC_COLLATE
This variable determines the collation order used when sorting the results of filename expansion, and determines the behavior of range expressions, equivalence classes, and collating sequences within filename expansion and pattern matching.
LC_CTYPE
This variable determines the interpretation of characters and the behavior of character classes within filename expansion and pattern matching.
LC_MESSAGES
This variable determines the locale used to translate double-quoted strings preceded by a `$'.
LC_NUMERIC
This variable determines the locale category used for number formatting.
LINENO
The line number in 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.
MAILCHECK
How often (in seconds) that the shell should check for mail in the files specified in the MAILPATH or MAIL variables.
OLDPWD
The previous working directory as set by the cd builtin.
OPTERR
If set to the value 1, Bash displays error messages generated by the getopts builtin command.
OSTYPE
A string describing the Operating System Bash is running on.
PIPESTATUS
An array variable containing a list of exit status values from the processes n the most-recently-executed foreground pipeline (which can contain only a single command).
PPID
The process ID of the shell’s parent process. This variable is readonly.
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. If this variable is not set, the select command prompts with `#? '
PS4
The value is the prompt printed before the command line is echoed when the `-x' option is set. The first character of PS4 is replicated multiple times, as necessary, to indicate multiple levels of indirection. The default is `+ '.
PWD
The current working directory as set by the cd builtin.
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. Don’t use for cryptography, but this can generate random numbers eg to create a temporary file in a script.
REPLY
The default variable for the read builtin.
SECONDS
This variable expands to the number of seconds since the shell was started. Assignment to this variable resets the count to the value assigned, and the expanded value becomes the value assigned plus the number of seconds since the assignment.
SHELLOPTS
A colon-separated list of enabled shell options. Each word in the list is a valid argument for the `-o' option to the set builtin command. The options appearing in SHELLOPTS are those reported as `on' by `set -o'. If this variable is in the environment when Bash starts up, each shell option in the list will be enabled before reading any startup files. This variable is readonly.
SHLVL
Incremented by one each time a new instance of Bash is started. This is intended to be a count of how deeply your Bash shells are nested.
TIMEFORMAT
The 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. The `%' character introduces an escape sequence that is expanded to a time value or other information. The escape sequences and their meanings are as follows; the braces denote optional portions.
%%
A literal `%'.
%[p][l]R
The elapsed time in seconds.
%[p][l]U
The number of CPU seconds spent in user mode.
%[p][l]S
The number of CPU seconds spent in system mode.
%P
The CPU percentage, computed as (%U + %S) / %R.

The optional p is a digit specifying the precision, the number of fractional digits after a decimal point. A value of 0 causes no decimal point or fraction to be output. At most three places after the decimal point can be specified; values of p greater than 3 are changed to 3. If p is not specified, the value 3 is used. The optional l specifies a longer format, including minutes, of the form MMmSS.FFs. The value of p determines whether or not the fraction is included. If this variable is not set, Bash acts as if it had the value

$'\nreal\t%3lR\nuser\t%3lU\nsys\t%3lS'
If the value is null, no timing information is displayed. A trailing newline is added when the format string is displayed.
TMOUT
If set to a value greater than zero, 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. See read / sleep.
UID
The numeric real user id of the current user. This variable is readonly.

Related macOS commands

macOS How To
List of all macOS Environment variables
env - List or Set environment variables.


 
Copyright © 1999-2024 SS64.com
Some rights reserved