You are currently viewing Shell Scripting – Shell Variables
Shell Scripting – Shell Variables

Shell Scripting – Shell Variables

Shell Scripting – Shell Variables

Hello Everyone

Welcome to CloudAffaire and this is Debjeet.

In the last blog post, we have discussed user-defined global variables in the shell.

https://cloudaffaire.com/shell-scripting-environment-variables/

In this blog post, we will discuss shell variables that are defined by the shell itself. The shell variable is a special type of the variable used and set by the shell itself to store different shell configuration-related information. A shell variable can be global, user-specific, or session-specific. End users cannot define a new shell variable however they can set a pre-existing shell variable value if the variable is not read-only. Shell variables are mostly defined in uppercase letters as naming conventions.

Shell Scripting – Shell Variables

View all shell variables:

BASH: BASH returns the path to the bash binary itself. The default location is /bin/bash in most cases.

BASHOPTS: A colon-separated list of enabled shell options. Each word in the list is a valid argument for the -s option to the shopt built in command. The options appearing in BASHOPTS are those reported as on by shopt. 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 read-only.

BASHPID: Expands to the process ID of the current bash process. This differs from $$ under certain circumstances, such as subshells that do not require bash to be re-initialized.

BASH_ALIASES: An associative array variable whose members correspond to the internal list of aliases as maintained by the alias built in. Elements added to this array appear in the alias list; unsetting array elements cause aliases to be removed from the alias list.

BASH_ARGC: An array variable whose values are the number of parameters in each frame of the current bash execution call stack. The number of parameters to the current subroutine (shell function or script executed with . or source) is at the top of the stack. When a subroutine is executed, the number of parameters passed is pushed onto BASH_ARGC. The shell sets BASH_ARGC only when in extended debugging mode.

BASH_ARGV: An array variable containing all of the parameters in the current bash execution call stack. The final parameter of the last subroutine call is at the top of the stack; the first parameter of the initial call is at the bottom. When a subroutine is executed, the parameters supplied are pushed onto BASH_ARGV. The shell sets BASH_ARGV only when in extended debugging mode.

BASH_CMDS: An associative array variable whose members correspond to the internal hash table of commands as maintained by the hash built-in. Elements added to this array appear in the hash table; unsetting array elements cause commands to be removed from the hash table.

BASH_COMMAND: The command currently being executed or about to be executed, unless the shell is executing a command as the result of a trap, in which case it is the command executing at the time of the trap.

BASH_ENV: If this parameter is set when bash is executing a shell script, its value is interpreted as a filename containing commands to initialize the shell, as in ~/.bashrc. The value of BASH_ENV is subjected to parameter expansion, command substitution, and arithmetic expansion before being interpreted as a file name. PATH is not used to search for the resultant file name.

BASH_EXECUTION_STRING: Returns the command argument to the bash -c invocation option.

BASH_LINENO: An array variable whose members are the line numbers in source files where each corresponding member of FUNCNAME was invoked. ${BASH_LINENO[$i]} is the line number in the source file (${BASH_SOURCE[$i+1]}) where ${FUNCNAME[$i]} was called (or ${BASH_LINENO[$i-1]} if referenced within another shell function). Use LINENO to obtain the current line number.

BASH_REMATCH: An array variable whose members are assigned by the =~ binary operator to the [[ conditional command. The element with index 0 is the portion of the string matching the entire regular expression. The element with index n is the portion of the string matching the nth parenthesized subexpression. This variable is read-only.

BASH_SOURCE: An array variable whose members are the source filenames where the corresponding shell function names in the FUNCNAME array variable are defined. The shell function ${FUNCNAME[$i]} is defined in the file ${BASH_SOURCE[$i]} and called from ${BASH_SOURCE[$i+1]}.

BASH_SUBSHELL: A variable indicating the subshell level. Incremented by one each time a subshell or subshell environment is spawned. The initial value is 0.

BASH_VERSION: Expands to a string describing the version of this instance of bash. This is a read-only variable.

BASH_VERSINFO[n]: A read-only array variable whose members hold version information for this instance of bash. This is similar to BASH_VERSION but returns some extra information.

CDPATH: The search path for the cd command. This is a colon-separated list of directories in which the shell looks for destination directories specified by the cd command. A sample value is “.:~:/usr”

COLUMNS: Used by the select compound command to determine the terminal width when printing selection lists. Automatically set upon receipt of a SIGWINCH.

Autocompletion related variables:

COMPREPLY: An array variable from which bash reads the possible completions generated by a shell function invoked by the programmable completion facility.

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_KEY: The key (or final key of a key sequence) used to invoke the current completion function.

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.

COMP_TYPE: Set to an integer value corresponding to the type of completion attempted that caused a completion function to be called: TAB, for normal completion, ?, for listing completions after successive tabs, !, for listing alternatives on partial word completion, @, to list completions if the word is not unmodified, or %, for menu completion. This variable is available only in shell functions and external commands invoked by the programmable completion facilities.

COMP_WORDBREAKS: The set of characters that the readline library treats as word separators when performing word completion. If COMP_WORD‐BREAKS is unset, it loses its special properties, even if it is subsequently reset.

COMP_WORDS: An array variable (see Arrays below) consisting of the individual words in the current command line. The line is split into words as readline would split it, using COMP_WORDBREAKS as described above. This variable is available only in shell functions invoked by the programmable completion facilities.

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 built in. Assigning to members of this array variable may be used to modify directories already in the stack, but the pushd and popd built ins 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: Expands to the effective user ID of the current user, initialized at shell startup. This variable is read-only. The $EUID is not necessarily the same as the $UID though most of the time they return the same value.

FUNCNAME: An array variable containing the names of all shell functions currently in the execution call stack. The element with index 0 is the name of any currently-executing shell function. The bottom-most element (the one with the highest index) is “main”. This variable exists only when a shell function is executing. Assignments to FUNCNAME have no effect and return an error status. If FUNCNAME is unset, it loses its special properties, even if it is subsequently reset. This variable can be used with BASH_LINENO and BASH_SOURCE. Each element of FUNCNAME has corresponding elements in BASH_LINENO and BASH_SOURCE to describe the call stack. For instance, ${FUNCNAME[$i]} was called from the file ${BASH_SOURCE[$i+1]} at line number ${BASH_LINENO[$i]}. The caller built in displays the current call stack using this information.

GLOBIGNORE: A colon-separated list of patterns defining the set of filenames to be ignored by pathname expansion. If a filename matched by a pathname 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 return an error status. If GROUPS is unset, it loses its special properties, even if it is subsequently reset.

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.

HISTCONTROL: A colon-separated list of values controlling how commands are saved on the history list. If the list of values includes ignorespace, lines which begin with a space character are not saved in the history list. A value of ignoredups causes lines matching the previous history entry to not be saved. A value of ignoreboth is shorthand for ignorespace and ignoredups. A value of erasedups causes all previous lines matching the current line to be removed from the history list before that line is saved. Any value not in the above list is ignored. If HISTCONTROL is unset, or does not include a valid value, all lines read by the shell parser are saved on the history list, subject to the value of HISTIGNORE. 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.

HISTFILE: The name of the file in which command history is saved. The default value is ~/.bash_history. If unset, the command history is not saved when an interactive shell exits.

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, by removing the oldest entries, to contain no more than that number of lines. The default value is 500. The history file is also truncated to this size after writing it when an interactive shell exits.

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. ‘&’ may 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.

HISTSIZE: The number of commands to remember in the command history. The default value is 500.

HISTTIMEFORMAT: If this variable is set and not null, its value is used as a format string for strftime(3) to print the time stamp associated with each history entry displayed by the history built in. If this variable is set, time stamps are written to the history file so they may be preserved across shell sessions. This uses the history comment character to distinguish timestamps from other history lines.

HOME: The home directory of the current user; the default argument for the cd built in command. The value of this variable is also used when performing tilde expansion.

HOSTNAME: The hostname command assigns the system host name at bootup in an init script. However, the gethostname() function sets the Bash internal variable $HOSTNAME.

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 may 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, or does not name a readable file, bash attempts to read /etc/hosts to obtain the list of possible hostname completions. When HOSTFILE is unset, the hostname list is cleared.

HOSTTYPE: Automatically set to a string that uniquely describes the type of machine on which bash is executing. The default is system-dependent.

IFS: The Internal Field Separator that is used for word splitting after expansion and to split lines into words with the read built in command. The default value is <space><tab><newline>”.

IGNOREEOF: Controls the action of an interactive shell on receipt of an EOF character as the sole input. If set, the value is the number of consecutive EOF characters that must be typed as the first characters on an input line before bash exits. If the variable exists but does not have a numeric value, or has no value, the default value is 10. If it does not exist, EOF signifies the end of input to the shell.

locale related variables:

A locale is a set of language and cultural rules. These cover aspects such as language for messages, different character sets, lexicographic conventions, and so on. A program needs to be able to determine its locale and act accordingly to be portable to different cultures.

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 pathname expansion, and determines the behavior of range expressions, equivalence classes, and collating sequences within pathname expansion and pattern matching.

LC_CTYPE: This variable determines the interpretation of characters and the behavior of character classes within pathname 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.

LC_TIME: This variable determines the locale category used for time and date formatting.

LC_MONETARY: This variable determines the locale category used for monetary formatting.

LC_PAPER: This variable determines the locale category used for paper size.

LC_NAME: This variable determines the locale category used for name formatting.

LC_ADDRESS: This variable determines the locale category used for address formatting.

LC_TELEPHONE: This variable determines the locale category used for phone number formatting.

LC_MEASUREMENT: This variable determines the locale category used for the measurement unit.

LC_IDENTIFICATION: Metadata about the locale information

LINES: Used by the select compound command to determine the column length for printing selection lists. Automatically set upon receipt of a SIGWINCH.

LINENO: Each time this parameter is referenced, the shell substitutes a decimal number representing the current sequential line number (starting with 1) within a script or function. When not in a script or function, the value substituted is not guaranteed to be meaningful. If LINENO is unset, it loses its special properties, even if it is subsequently reset.

MACHTYP: Automatically set to a string that fully describes the system type on which bash is executing, in the standard GNU cpu-company-system format. The default is system-dependent.

MAIL: If this parameter is set to a file or directory name and the MAILPATH variable is not set, bash informs the user of the arrival of mail in the specified file or Maildir-format directory.

MAILCHECK: Specifies how often (in seconds) bash checks for mail. The default is 60 seconds. When it is time to check for mail, the shell does so before displaying the primary prompt. If this variable is unset, or set to a value that is not a number greater than or equal to zero, the shell disables mail checking.

MAILPATH: A colon-separated list of file names to be checked for mail. The message to be printed when mail arrives in a particular file may be specified 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 mailfile. Example: MAILPATH=’/var/mail/bfox?”You have mail”:~/shell-mail?”$_ has mail!”‘ Bash supplies a default value for this variable, but the location of the user mail files that it uses is system dependent (e.g., /var/mail/$USER).

MAPFILE: An array variable created to hold the text read by the mapfile builtin when no variable name is supplied.

OLDPWD: The previous working directory as set by the cd command.

Options related variables:

OPTARG: The value of the last option argument processed by the getopts built in command.

OPTIND: The index of the next argument to be processed by the getopts built in command.

OPTERR: If set to the value 1, bash displays error messages generated by the getopts built in command. OPTERR is initialized to 1 each time the shell is invoked or a shell script is executed.

OSTYPE: Automatically set to a string that describes the operating system on which bash is executing. The default is system-dependent.

PATH: The search path for commands. It is a colon-separated list of directories in which the shell looks for commands. A zero-length (null) directory name in the value of PATH indicates the current directory. A null directory name may appear as two adjacent colons, or as an initial or trailing colon. The default path is system-dependent, and is set by the administrator who installs bash. A common value is /usr/gnu/bin:/usr/local/bin:/usr/ucb:/bin:/usr/bin”.

PIPESTATUS: An 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).

PPID: The process ID of the shell’s parent. This variable is read-only.

PWD: The current working directory as set by the cd command.

POSIXLY_CORRECT: If this variable is in the environment when bash starts, the shell enters posix mode before reading the start up files, as if the –posix invocation option had been supplied. If it is set while the shell is running, bash enables posix mode, as if the command set -o posix had been executed.

PS1: The value of this parameter is expanded and used as the primary prompt string. The default value is \s-\v\$ ”.

PS2: The value of this parameter is expanded as with PS1 and used as the secondary prompt string. The default is > ”.

PS3: The value of this parameter is used as the prompt for the select command.

PS4: The value of this parameter is expanded as with PS1 and the value is printed before each command bash displays during an execution trace. The first character of PS4 is replicated multiple times, as necessary, to indicate multiple levels of indirection. The default is “+ ”.

PROMPT_COMMAND: If set, the value is executed as a command prior to issuing each primary prompt.

PROMPT_DIRTRIM: If set to a number greater than zero, the value is used as the number of trailing directory components to retain when expanding the \w and \W prompt string escapes. Characters removed are replaced with an ellipsis.

RANDOM: Each time this parameter is referenced, a random integer between 0 and 32767 is generated. The sequence of random numbers may be initialized by assigning a value to RANDOM. If RANDOM is unset, it loses its special properties, even if it is subsequently reset.

REPLY: Set to the line of input read by the read built-in command when no arguments are supplied.

SECONDS: Each time this parameter is referenced, the number of seconds since shell invocation is returned. If a value is assigned to SECONDS, the value returned upon subsequent references is the number of seconds since the assignment plus the value assigned. If SECONDS is unset, it loses its special properties, even if it is subsequently reset.

SHELL: The full pathname to the shell is kept in this environment variable. If it is not set when the shell starts, bash assigns to it the full pathname of the current user’s login shell.

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 built in 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 start up files. This variable is read-only.

SHLVL: Returns the number of bash instance running. Incremented by one each time an instance of bash is started.

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.

TMOUT: If set to a value greater than zero, TMOUT is treated as the default timeout for the read built in. The select command terminates if input does not arrive after TMOUT seconds when input is coming from a terminal. In an interactive shell, the value is interpreted as the number of seconds to wait for input after issuing the primary prompt. Bash terminates after waiting for that number of seconds if input does not arrive.

TMPDIR: If set, bash uses its value as the name of a directory in which bash creates temporary files for the shell’s use.

UID: Expands to the user ID of the current user, initialized at shell startup. This variable is read-only.

Hope you have enjoyed this article. In the next blog post, we will discuss operators.

 

Leave a Reply