perating system
59Linux
Invoking the Shell
The command interpreter for the Bash shell (bash) can be invoked as follows:
bash [options] [arguments]
Bash can execute commands from a terminal, from a file (when the first argument is a script),
or from standard input (if no arguments remain or if -s is specified). The shell automatically
prints prompts if standard input is a terminal, or if -i is given on the command line.
On many systems, /bin/sh is a link to Bash. When invoked as sh, Bash acts more like the
traditional Bourne shell: login shells read /etc/profile and ˜/.profile, and regular
shells read $ENV, if it’s set. Full details are available in the bash(1) manpage.
Options
-c str
Read commands from string str.
-D, --dump-strings
Print all $"..." strings in the program.
-i Create an interactive shell (prompt for input).
-O option
Enable shopt option option.
-p Star t up as a privileged user. Don’t read $ENV or $BASH_ENV, don’t impor t functions
from the environment, and ignore the value of $SHELLOPTS. The normal fixedname
startup files (such as $HOME/.bash_profile) are read.
-r, --restricted
Create a restricted shell.
-s Read commands from standard input. Output from built-in commands goes to file
descriptor 1; all other shell output goes to file descriptor 2.
--debugger
Read the debugging profile at startup, turn on the extdebug option to shopt, and
enable function tracing. For use by the Bash debugger (see http://bashdb.sourceforge.net).
--dump-po-strings
Same as -D, but output in GNU gettext format.
--help
Print a usage message and exit successfully.
--init-file file, --rcfile file
Use file as the startup file instead of ˜/.bashrc for interactive shells.
Invoking the Shell 3
--login
Shell is a login shell.
--noediting
Do not use the readline librar y for input, even in an interactive shell.
--noprofile
Do not read /etc/profile or any of the personal startup files.
--norc
Do not read ˜/.bashrc. Enabled automatically when invoked as sh.
--posix
Turn on POSIX mode.
--verbose
Same as set -v; the shell prints lines as it reads them.
--version
Print a version message and exit.
-, --
End option processing.
The remaining options are listed under the set built-in command.
Ar guments
Arguments are assigned in order to the positional parameters $1, $2, etc. If the first argument
is a script, commands are read from it, and the remaining arguments are assigned to $1, $2,
etc. The name of the script is available as $0. The script file itself need not be executable, but
it must be readable.
Syntax
This section describes the many symbols peculiar to the shell. The topics are arranged as follows:
• Special files
• Filename metacharacters
• Quoting
• Command forms
• Redirection forms
Special Files
The shell reads one or more star tup files. Some of the files are read only when a shell is a
login shell. Bash reads these files:
4 Chapter 1 – The Bash Shell
1. /etc/profile. Executed automatically at login.
2. The first file found from this list: ˜/.bash_profile, ˜/.bash_login, or ˜/.profile.
Executed automatically at login.
3. ˜/.bashrc is read by every nonlogin shell. Ho wever, if invoked as sh, Bash instead
reads $ENV, for POSIX compatibility.
The getpwnam() and getpwuid() functions are the sources of home directories for ˜name
abbreviations. (On single-user systems, the user database is stored in /etc/passwd.
Ho wever, on networked systems, this information may come from NIS, NIS+, or LDAP, not
your workstation password file.)
Filename Metacharacters
* Match any string of zero or more characters.
? Match any single character.
[abc...] Match any one of the enclosed characters; a hyphen can specify a
range (e.g., a-z, A-Z, 0–9).
[!abc...] Match any character not enclosed as above.
˜ Home director y of the current user.
˜name Home director y of user name.
˜+ Current working director y ($PWD).
˜- Pr evious working director y ($OLDPWD).
With the extglob option on:
?(pattern) Match zero or one instance of patter n.
*(pattern) Match zero or more instances of patter n.
+(pattern) Match one or more instances of patter n.
@(pattern) Match exactly one instance of patter n.
!(pattern) Match any strings that don’t match patter n.
This patter n can be a sequence of patterns separated by |, meaning that the match applies to
any of the patterns. This extended syntax resembles that available in egrep and awk.
Bash supports the POSIX [[=c=]] notation for matching characters that have the same
weight, and [[.c.]] for specifying collating sequences. In addition, character classes, of the
form [[:class:]], allow you to match the following classes of characters:
Class Characters matched Class Characters matched
alnum Alphanumeric characters graph Nonspace characters
alpha Alphabetic characters print Printable characters
blank Space or Tab punct Punctuation characters
cntrl Control characters space Whitespace characters
digit Decimal digits upper Uppercase characters
lower Lowercase characters xdigit Hexadecimal digits
Syntax 5
Bash also accepts the [:word:] character class, which is not in POSIX. [[:word:]] is equivalent
to [[:alnum:]_].
Examples
$ ls new* List new and new.1
$ cat ch? Match ch9 but not ch10
$ vi[D-R]* Match files that begin with uppercase D through R
$ pr !(*.o|core) | lp Print files that are not object files or core dumps
NOTE: On modern systems, ranges such as [D-R] are not portable; the system’s locale may
include more than just the uppercase letters from D to R in the range.
Quoting
Quoting disables a character’s special meaning and allows it to be used literally. The following
table displays characters that have special meaning:
Character Meaning
; Command separator
& Background execution
() Command grouping
| Pipe
< > & Redirection symbols
* ? [ ] ˜ + - @ ! Filename metacharacters
" ’ \ Used in quoting other characters
‘ Command substitution
$ Variable substitution (or command or arithmetic substitution)
space tab newline Word separators
These characters can be used for quoting:
" " Ev erything between " and " is taken literally, except for the following characters that
keep their special meaning:
$ Variable (or command and arithmetic) substitution will occur.
‘ Command substitution will occur.
" This marks the end of the double quote.
’ ’ Ev erything between ’ and ’ is taken literally, except for another ’. You cannot embed
another ’ within such a quoted string.
\ The character following a \ is taken literally. Use within " " to escape ", $, and ‘.
Often used to escape itself, spaces, or newlines.
$" "
Just like" ", except that locale translation is done.
$’ ’
Similar to’ ’, but the quoted text is processed for the following escape sequences:
6 Chapter 1 – The Bash Shell
Sequence Value Sequence Value
\a Aler t \t Tab
\b Backspace \v Vertical tab
\cX Control character X \nnn Octal value nnn
\e Escape \xnn Hexadecimal value nn
\E Escape \’ Single quote
\f Form feed \" Double quote
\n Ne wline \\ Backslash
\r Carriage return
Examples
$ echo ’Single quotes "protect" double quotes’
Single quotes "protect" double quotes
$ echo "Well, isn’t that \"special\"?"
Well, isn’t that "special"?
$ echo "You have ‘ls | wc -l‘ files in ‘pwd‘"
You have 43 files in /home/bob
$ echo "The value of \$x is $x"
The value of $x is 100
Command For ms
cmd & Execute cmd in background.
cmd1 ; cmd2 Command sequence; execute multiple cmds on the same line.
{ cmd1 ; cmd2; } Execute commands as a group in the current shell.
(cmd1 ; cmd2) Execute commands as a group in a subshell.
cmd1 | cmd2 Pipe; use output from cmd1 as input to cmd2.
cmd1 ‘cmd2‘ Command substitution; use cmd2 output as arguments to cmd1.
cmd1 $(cmd2) POSIX shell command substitution; nesting is allowed.
cmd $((expression)) POSIX shell arithmetic substitution. Use the result of expression as
argument to cmd.
cmd1 && cmd2 AND; execute cmd1 and then (if cmd1 succeeds) cmd2. This is a
“shor t circuit” operation: cmd2 is never executed if cmd1 fails.
cmd1 || cmd2 OR; execute either cmd1 or (if cmd1 fails) cmd2. This is a “shor t
circuit” operation; cmd2 is never executed if cmd1 succeeds.
! cmd NOT; execute cmd, and produce a zero exit status if cmd exits
with a nonzero status. Other wise, produce a nonzero status when
cmd exits with a zero status.
Examples
$ nroff file > file.txt & Format in the background
$ cd; ls Execute sequentially
$ (date; who; pwd) > logfile All output is redirected
$ sort file | pr -3 | lp Sor t file, page output, then print
$ vi ‘grep -l ifdef *.c‘ Edit files found by grep
$ egrep ’(yes|no)’ ‘cat list‘ Specify a list of files to search
$ egrep ’(yes|no)’ $(cat list) POSIX version of previous
Syntax 7
$ egrep ’(yes|no)’ $(< list) Faster; not in POSIX
$ grep XX file && lp file Print file if it contains the pattern
$ grep XX file || echo "XX not found" Other wise, echo an error message
Redirection For ms
File descriptor Name Common abbreviation Typical default
0 Standard input stdin Keyboard
1 Standard output stdout Screen
2 Standard error stderr Screen
The usual input source or output destination can be changed, as seen in the following
sections.
Simple redirection
cmd > file
Send output of cmd to file (overwrite).
cmd >> file
Send output of cmd to file (append).
cmd < file
Take input for cmd from file.
cmd << text
The contents of the shell script up to a line identical to text become the standard input
for cmd (text can be stored in a shell variable). This command form is sometimes called
a here document. Input is usually typed at the keyboard or in the shell program. Commands
that typically use this syntax include cat, ex, and sed. (If <<- is used, leading
tabs are stripped from the contents of the here document, and the tabs are ignored
when comparing input with the end-of-input text marker.) If any part of text is quoted,
the input is passed through verbatim. Other wise, the contents are processed for variable,
command, and arithmetic substitutions.
cmd <<< word
Supply text of word, with trailing newline, as input to cmd. (This is known as a here
string, from the free version of the rc shell.)
cmd <> file
Open file for reading and writing on the standard input. The contents are not
destroy ed.*
cmd >| file
Send output of cmd to file (overwrite), even if the shell’s noclobber option is set.
* With <, the file is opened read-only, and writes on the file descriptor will fail. With <>, the file is opened read-write;
it is up to the application to actually take advantage of this.
8 Chapter 1 – The Bash Shell
Redirection using file descriptors
cmd >&n Send cmd output to file descriptor n.
cmd m>&n Same as previous, except that output that would normally go to file descriptor m
is sent to file descriptor n instead.
cmd >&- Close standard output.
cmd <&n Take input for cmd from file descriptor n.
cmd m<&n Same as previous, except that input that would normally come from file descriptor
m comes from file descriptor n instead.
cmd <&- Close standard input.
cmd <&n- Mo ve input file descriptor n instead of duplicating it.
cmd >&n- Mo ve output file descriptor n instead of duplicating it.
Multiple redirection
cmd 2>file Send standard error to file; standard output remains the same
(e.g., the screen).
cmd > file 2>&1 Send both standard error and standard output to file.
cmd &> file Same as previous. Preferred form.
cmd >& file Same as previous.
cmd > f1 2>f2 Send standard output to file f1 and standard error to file f2.
cmd| teefiles Send output of cmd to standard output (usually the terminal) and
to files.
cmd 2>&1 | tee files Send standard output and error output of cmd to standard output
(usually the terminal) and to files.
No space should appear between file descriptors and a redirection symbol; spacing is optional
in the other cases.
Bash allows multidigit file descriptor numbers. Other shells do not.
Examples
$ cat part1 > book
$ cat part2 part3 >> book
$ mail tim < report
$ sed ’s/ˆ/XX /g’ << END_ARCHIVE
> This is often how a shell archive is "wrapped",
> bundling text for distribution. You would normally
> run sed from a shell program, not from the command line.
> END_ARCHIVE
XX This is often how a shell archive is "wrapped",
XX bundling text for distribution. You would normally
XX run sed from a shell program, not from the command line.
To redirect standard output to standard error:
$ echo "Usage error: see administrator" 1>&2
The following command sends output (files found) to filelist, and error messages (inaccessible
files) to file no_access:
$ find / -print > filelist 2>no_access
Syntax 9
Functions
A shell function is a grouping of commands within a shell script. Shell functions let you modularize
your program by dividing it up into separate tasks. This way, the code for each task
need not be repeated ever y time you need to perform the task. The POSIX shell syntax for
defining a function follows the Bourne shell:
name () {
function body’s code come here
}
Functions are invoked just as are regular shell built-in commands or external commands. The
command-line parameters $1, $2, and so on receive the function’s arguments, temporarily
hiding the global values of $1, etc. For example:
# fatal --- print an error message and die:
fatal () {
echo "$0: fatal error:" "$@" >&2 # messages to standard error
exit 1
}
...
if [ $# = 0 ] # not enough arguments
then
fatal not enough arguments
fi
A function may use the return command to return an exit value to the calling shell program.
Be careful not to use exit from within a function unless you really wish to terminate
the entire program.
Bash allows you to define functions using an additional keyword, function, as follows:
function fatal {
echo "$0: fatal error:" "$@" >&2 # messages to standard error
exit 1
}
In Bash, all functions share traps with the “parent” shell (except the DEBUG trap, if function
tracing has been turned on). With the errtrace option enabled (either set -E or set -o
errtrace), functions also inherit the ERR trap. If function tracing has been enabled, functions
inherit the RETURN trap. Functions may have local variables, and they may be recursive.
Unlike the Korn shell, the syntax used to define a function is irrelevant.
Variables
This section describes the following:
• Variable assignment
• Variable substitution
• Built-in shell variables
10 Chapter 1 – The Bash Shell
• Other shell variables
• Arrays
• Special prompt strings
Variable Assignment
Variable names consist of any number of letters, digits, or underscores. Uppercase and lowercase
letters are distinct, and names may not start with a digit. Variables are assigned values
using the = operator. There may not be any whitespace between the variable name and the
value. You can make multiple assignments on the same line by separating each one with
whitespace:
firstname=Arnold lastname=Robbins numkids=4
By convention, names for variables used or set by the shell usually have all uppercase letters;
however, you can use uppercase names in your scripts if you use a name that isn’t special to
the shell.
By default, the shell treats variable values as strings, even if the value of the string is all digits.
Ho wever, when a value is assigned to an integer variable (created via declare -i), Bash evaluates
the righthand side of the assignment as an expression (see the later section “Arithmetic
Expressions”). For example:
$ i=5+3 ; echo $i
5+3
$ declare -i jj ; jj=5+3 ; echo $jj
8
Beginning with Bash Version 3.1, the += operator allows you to add or append the righthand
side of the assignment to an existing value. Integer variables treat the righthand side as an
expression, which is evaluated and added to the value. Arrays add the new elements to the
array (see the later section “Arrays”). For example:
$ name=Arnold
$ name+=" Robbins" ; echo $name String variable
Arnold Robbins
$ declare -i jj ; jj=3+5 ; echo $jj Integer variable
8
$ jj+=2+4 ; echo $jj
14
$ pets=(blacky rusty) Array variable
$ echo ${pets[*]}
blacky rusty
$ pets+=(raincloud sparky)
$ echo ${pets[*]}
blacky rusty raincloud sparky
Variable Substitution
No spaces should be used in the following expressions. The colon (:) is optional; if it’s
included, var must be nonnull as well as set.
Variables 11
var=value ... Set each variable var to a value.
${var} Use value of var; braces are optional if var is separated from the
following text. They are required for array variables.
${var:-value} Use var if set; otherwise, use value.
${var:=value} Use var if set; otherwise, use value and assign value to var.
${var:?value} Use var if set; otherwise, print value and exit (if not interactive). If
value isn’t supplied, print the phrase “parameter null or not set.”
${var:+value} Use value if var is set; otherwise, use nothing.
${#var} Use the length of var.
${#*} Use the number of positional parameters.
${#@} Same as previous.
${var#pattern} Use value of var after removing patter n from the left. Remove the
shor test matching piece.
${var##pattern} Same as #patter n, but remove the longest matching piece.
${var%pattern} Use value of var after removing patter n from the right. Remove
the shortest matching piece.
${var%%pattern} Same as %patter n, but remove the longest matching piece.
${!prefix*}, ${!prefix@} List of variables whose names begin with prefix.
${var:pos}, ${var:pos:len} Star ting at position pos (0-based) in variable var, extract len characters,
or extract rest of string if no len. pos and len may be arithmetic
expressions.
${var/pat/repl} Use value of var, with first match of pat replaced with repl.
${var/pat} Use value of var, with first match of pat deleted.
${var//pat/repl} Use value of var, with ever y match of pat replaced with repl.
${var/#pat/repl} Use value of var, with match of pat replaced with repl. Match
must occur at beginning of the value.
${var/%pat/repl} Use value of var, with match of pat replaced with repl. Match
must occur at end of the value.
Bash provides a special syntax that lets one variable indirectly reference another:
$ greet="hello, world" Create initial variable
$ friendly_message=greet Aliasing variable
$ echo ${!friendly_message} Use the alias
hello, world
Examples
$ u=up d=down blank= Assign values to three variables (last is null)
$ echo ${u}root Braces are needed here
uproot
$ echo ${u-$d} Display value of u or d; since u is set, it’s printed
up
$ echo ${tmp-‘date‘} If tmp is not set, the date command is executed
Sun Jun 11 13:14:54 EDT 2006
$ echo ${blank="no data"} blank is set, so it is printed (a blank line)
$ echo ${blank:="no data"} blank is set but null, so the string is printed
no data
$ echo $blank blank now has a new value
no data
$ tail=${PWD##*/} Take the current director y name and remove the
longest character string ending with /, which
removes the leading pathname and leaves the tail
12 Chapter 1 – The Bash Shell
Built-in Shell Variables
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.
$$ Pr ocess number of current process.
$! Pr ocess 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}.
$*, $@ 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. Many of these variables are for use
by the Bash Debugger (see http://bashdb.sourceforge.net) or for providing programmable completion
(see the section “Pr ogrammable Completion,” later in this reference).
$_ Temporar y variable; initialized to pathname of script or program
being executed. Later, stores the last argument of previous
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.
Variables 13
BASH_LINENO Array variable, corresponding to BASH_SOURCE and FUNCNAME.
For any given function number i (star ting at 0), ${FUNCNAME[
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 [[ ]] constr
uct. Index 0 is the text that matched the entire pattern. The
other indices are the text matched by parenthesized subexpressions.
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, indicating
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 readline
librar y treats as word separators when doing word completion.
COMP_WORDS For programmable completion. Array variable containing the
individual words on the command line.
DIRSTACK Array variable, containing the contents of the director y stack
as displayed by dirs. Changing existing elements modifies
the stack, but only pushd and popd can add or remove elements
from the stack.
EUID Read-only variable with the numeric effective UID of the current
user.
FUNCNAME Array variable, containing function names. Each element corresponds
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 cpucompany-
system format.
OLDPWD Pr evious working director y (set by cd).
14 Chapter 1 – The Bash Shell
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 Pr ocess number of this shell’s parent.
PWD Current working director y (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 ever y 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:
variable=value
This list includes the type of value expected when defining these variables.
CDPATH=dirs Directories searched by cd; allows shortcuts in changing directories;
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,
ENV=$HOME/.shellrc.
FCEDIT=file Editor used by fc command. The default is /bin/ed when Bash
is in POSIX mode. Other wise, 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.
Variables 15
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 different
than the number of commands.
HISTIGNORE=list A colon-separated list of patterns that must match the entire command
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 str ftime(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 director y; 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 librar y. 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. (See the earlier section
“Filename Metacharacters.”)
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 message
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.
16 Chapter 1 – The Bash Shell
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:. How ever,
the standard star tup 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
primar y prompt.
PS1=string Primar y prompt string; default is $.
PS2=string Secondar y prompt (used in multiline commands); default is >.
PS3=string Pr ompt string in select loops; default is #?.
PS4=string Pr ompt 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 director y.
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 !ˆ#. See the section “C-Shell–Style
Histor y,” later in this reference.
Arrays
Bash supports one-dimensional arrays. The first element is numbered 0. Bash has no limit on
the number of elements. Arrays are initialized with a special form of assignment:
message=(hi there how are you today)
where the specified values become elements of the array. Individual elements may also be
assigned to:
message[0]=hi This is the hard way
message[1]=there
message[2]=how
message[3]=are
message[4]=you
message[5]=today
Declaring arrays is not required. Any valid reference to a subscripted variable can create an
array.
Variables
PrintShare it! — Rate it: up down flag this hub








