May 052012
Shell Scripting


Built-in variables are automatically set by the shell and are typically used inside shell scripts. Built-in variables can make use of the variable substitution patterns shown previously. Note that the $ is not actually part of the variable name, although the variable is always referenced this way. The following are available in any Bourne-compatible shell:

$#            Number of command-line arguments.

$-            Options currently in effect (arguments supplied on command line or to set). The shell sets some options automatically.

$?            Exit value of last executed command.

$$            Process number of current process.

$!            Process number of last background command.

$0            First word; that is, the command name. This will have the full pathname if it was found via a PATH search.

$n            Individual arguments on command line (positional parameters). The

Bourne shell allows only nine parameters to be referenced directly (n = 1–9);Bash allows n to be greater than 9 if specified as ${n}.

$*, [email protected] All arguments  on command line ($1  $2 ...).

"$*"         All arguments  on command line as one string ("$1  $2..."). The values are separated by the first character in IFS.

"$@"        All arguments  on command line, individually quoted ("$1"  "$2" ...).


Bash automatically sets the following additional variables.

$_                                          Temporary variable; initialized to pathname of script or pro- gram being executed. Later, stores the last argument of previ ous command. Also stores name of matching MAIL file during mail checks.

BASH                                     The full pathname used to invoke this instance of Bash.

BASH_ARGC                           Array variable. Each element holds the number of arguments for the corresponding function or dot-script invocation. Set only in extended debug mode, with shopt -s extdebug. Cannot be unset.

BASH_ARGV                           An array variable similar to BASH_ARGC. Each element is one of the arguments passed to a function or dot-script. It functions as a stack, with values being pushed on at each call. Thus, the last element is the last argument to the most recent function or script invocation. Set only in extended debug mode, with shopt -s extdebug. Cannot be unset.

BASH_COMMAND                  The command currently executing or about to be executed.Inside a trap handler, it is the command running when the trap was invoked.

BASH_EXECUTION_STRING    The string argument passed to the -c option.

BASH_LINENO                       Array variable, corresponding to BASH_SOURCE and FUNCNAME.For any given function number i (starting at 0), ${FUNC-NAME[i]} was invoked in file ${BASH_SOURCE[i]} on line

${BASH_LINENO[i]}. The information is stored with the most recent function invocation first. Cannot be unset.

BASH_REMATCH                    Array variable, assigned by the =˜ operator of the [[ ]] con- struct. Index 0 is the text that matched the entire pattern. The other indices are the text matched by parenthesized subexpres- sions. This variable is read-only.

BASH_SOURCE                       Array variable, containing source filenames. Each element corresponds to those in FUNCNAME and BASH_LINENO. Cannot be unset.

BASH_SUBSHELL                    This variable is incremented by one each time a subshell or subshell environment is created.

BASH_VERSINFO[0]                 The major version number, or release, of Bash. BASH_VERSINFO[1]       The minor version number, or version, of Bash. BASH_VERSINFO[2]    The patch level.

BASH_VERSINFO[3]                 The build version.

BASH_VERSINFO[4]                 The release status.

BASH_VERSINFO[5]                 The machine type; same value as in MACHTYPE.

BASH_VERSION                      A string describing the version of Bash.

COMP_CWORD                                For programmable completion. Index into COMP_WORDS, indi- cating the current cursor position.

COMP_LINE                           For programmable completion. The current command line. COMP_POINT                  For programmable completion. The position of the cursor  as a character index in COMP_LINE.

COMP_WORDBREAKS            For programmable completion. The characters that the read- line library treats as word separators when doing word com- pletion.

COMP_WORDS                                For programmable completion. Array variable containing the individual words on the command line.

DIRSTACK                              Array variable, containing the contents of the directory stack as displayed by dirs. Changing existing elements modifies the stack, but only pushd and popd can add or remove ele- ments from the stack.

EUID                                      Read-only variable with the numeric effective UID of the cur- rent user.

FUNCNAME                            Array variable, containing function names. Each element cor- responds to those in BASH_SOURCE and BASH_LINENO.

GROUPS                                Array variable, containing the list of numeric group IDs in which the current user is a member.

HISTCMD                              The history number of the current command.

HOSTNAME                           The name of the current host.

HOSTTYPE                             A string that describes the host system.

LINENO                                 Current line number within the script or function.

MACHTYPE                            A string that describes the host system in the GNU cpu- company-system format.

OLDPWD                                  Previous working directory (set by cd).

OPTARG                                Name of argument to last option processed by getopts.

OPTIND                                 Numerical index of OPTARG.

OSTYPE                                 A string that describes the operating system.

PIPESTATUS                           Array variable, containing the exit statuses of the commands in the most recent foreground pipeline.

PPID                                       Process number of this shell’s parent.

PWD                                          Current working directory (set by cd).

RANDOM[=n]                               Generate a new random number with each reference; start with integer n, if given.

REPLY                                     Default reply; used by select and read.

SECONDS[=n]                        Number of seconds since the shell was started, or, if n is given, number of seconds since the assignment + n.

SHELLOPTS                            A colon-separated  list of shell options (for set -o). If set in the environment at startup, Bash enables each option present in the list.

SHLVL                                   Incremented by one every time a new Bash starts up.

UID                                       Read-only variable with the numeric real UID of the current user.



Other Shell Variables


The following variables are not automatically set by the shell, although many of them can influence the shell’s behavior. You typically use them in your .profile file, where you can define them to suit your needs. Variables can be assigned values by issuing commands of the form:


This list includes the type of value expected when defining these variables.


CDPATH=dirs                           Directories searched by cd; allows shortcuts in changing directo- ries; unset by default.

COLUMNS=n                            Screen’s column width; used in line edit modes and select lists.

COMPREPLY=(words  …)       Array variable from which Bash reads the possible completions generated by a completion function.

EMACS                                     If the value starts with t, Bash assumes it’s running in an Emacs buffer and disables line editing.

ENV=file                                 Name of script that gets executed at startup; useful for storing alias and function definitions. For example,



FCEDIT=file                           Editor used by fc command. The default is /bin/ed when Bash is in POSIX mode. Otherwise, the default is $EDITOR if set, vi if unset.

FIGNORE=patlist                      Colon-separated list of patterns describing the set of filenames to ignore when doing filename completion.

GLOBIGNORE=patlist                 Colon-separated list of patterns describing the set of filenames to ignore during pattern matching.

HISTCONTROL=list                     Colon-separated list of values controlling how commands are saved in the history file. Recognized values are ignoredups, ignorespace, ignoreboth, and erasedups.

HISTFILE=file                        File in which to store command history.

HISTFILESIZE=n                         Number of lines to be kept in the history file. This may be differ- ent than the number of commands.

HISTIGNORE=list                        A colon-separated  list of patterns that must match the entire com- mand line. Matching lines are not saved in the history file. An unescaped & in a pattern matches the previous history line.

HISTSIZE=n                               Number of history commands to be kept in the history file.

HISTTIMEFORMAT=string             A format string for strftime(3) to use for printing timestamps along with commands from the history command. If set (even if null), Bash saves timestamps  in the history file along with the commands.

HOME=dir                                  Home directory; set by login (from /etc/passwd file).

HOSTFILE=file                       Name of a file in the same format as /etc/hosts that Bash should use to find hostnames for hostname completion.

IFS=’chars’                            Input field separators; default is space, tab, and newline.

IGNOREEOF=n                          Numeric value indicating how many successive EOF characters must be typed before Bash exits. If null or nonnumeric value, default is 10.

INPUTRC=file                           Initialization file for the readline library. This overrides the default value of ˜/.inputrc.

LANG=locale                            Default value for locale; used if no LC_* variables are set. LC_ALL=locale          Current locale; overrides LANG and the other LC_* variables. LC_COLLATE=locale Locale to use for character collation (sorting order). LC_CTYPE=locale                                                Locale to use for character class functions.

LC_MESSAGES=locale                  Locale to use for translating $”…” strings. LC_NUMERIC=locale          Locale to use for the decimal-point character. LC_TIME=locale              Locale to use for date and time formats. LINES=n                                                Screen’s height; used for select lists.

MAIL=file                                Default file to check for incoming mail; set by login.

MAILCHECK=n                          Number of seconds between mail checks; default is 600 (10 minutes).

MAILPATH=files                        One or more files, delimited by a colon, to check for incoming mail. Along with each file, you may supply an optional message that the shell prints when the file increases in size. Messages are separated from the filename by a ? character, and the default mes- sage is You  have mail in $_. $_ is replaced with the name of the file. For example, you might have:

MAILPATH=”$MAIL?  Candygram!:/etc/motd?New Login Message”


OPTERR=n                                When set to 1 (the default value), Bash prints error messages from the built-in getopts command.

PATH=dirlist                          One or more pathnames, delimited by colons, in which to search for commands to execute. Default for many systems is /bin:/usr/bin. On Solaris, the default is /usr/bin:. However, the standard startup scripts change it to:/usr/bin:/usr/ucb:/etc:.

POSIXLY_CORRECT=string             When set at startup or while running, Bash enters POSIX mode, disabling behavior and modifying features that conflict with the POSIX standard.

PROMPT_COMMAND=command          If set, Bash executes this command each time before printing the primary prompt.

PS1=string                             Primary prompt string; default is $.

PS2=string                               Secondary prompt (used in multiline commands); default is >.

PS3=string                            Prompt string in select loops; default is #?.

PS4=string                               Prompt string for execution trace (bash  -x or set -x); default is +.

SHELL=file                            Name of default shell (e.g., /bin/sh). Bash sets this if it’s not in the environment at startup.

TERM=string                            Terminal type.

TIMEFORMAT=string                   A format string for the output for the time keyword.

TMOUT=n                                If no command is typed after n seconds, exit the shell. Also affects the read command and the select loop.

TMDIR=directory                     Place temporary files created and used by the shell in directory.

auto_resume=list                      Enables the use of simple strings for resuming stopped jobs. With a value of exact, the string must match a command name exactly. With a value of substring, it can match a substring of the command name.

histchars=chars                   Two or three characters that control Bash’s csh-style history expansion. The first character signals a history event; the second is the “quick substitution” character; the third indicates the start of a comment. The default value is !ˆ#.



© Incase of any copyright infringements please check copyrights page for faster resolutions.

Leave a Reply

Show Buttons
Hide Buttons