bash - Unix, Linux Command

Bash is intended to be a conformant implementation of the
Shell and Utilities portion of the IEEE POSIX specification
(IEEE Standard 1003.1).
Bash can be configured to be POSIX-conformant by default.






An interactive shell is one started without non-option arguments
and without the
-c option
whose standard input and error are
both connected to terminals (as determined by
isatty(3)),
or one started with the
-i option.
 PS1 is set and
$- includes
i if
bash is interactive,
allowing a shell script or a startup file to test this state.


The following paragraphs describe how
bash executes its startup files.
If any of the files exist but cannot be read,
bash reports an error.
Tildes are expanded in file names as described below under
Tilde Expansion in the
 EXPANSION section.


When
bash is invoked as an interactive login shell, or as a non-interactive shell
with the --login option, it first reads and
executes commands from the file /etc/profile, if that
file exists.
After reading that file, it looks for ~/.bash_profile,
~/.bash_login, and ~/.profile, in that order, and reads
and executes commands from the first one that exists and is readable.
The
--noprofile option may be used when the shell is started to inhibit this behavior.


When a login shell exits,
bash reads and executes commands from the file ~/.bash_logout, if it
exists.


When an interactive shell that is not a login shell is started,
bash reads and executes commands from ~/.bashrc, if that file exists.
This may be inhibited by using the
--norc option.
The --rcfile file option will force
bash to read and execute commands from file instead of ~/.bashrc.


When
bash is started non-interactively, to run a shell script, for example, it
looks for the variable
 BASH_ENV in the environment, expands its value if it appears there, and uses the
expanded value as the name of a file to read and execute.
Bash behaves as if the following command were executed:


if [ -n "$BASH_ENV" ]; then . "$BASH_ENV"; fi



but the value of the
 PATH variable is not used to search for the file name.


If
bash is invoked with the name
sh, it tries to mimic the startup behavior of historical versions of
sh as closely as possible,
while conforming to the POSIX standard as well.
When invoked as an interactive login shell, or a non-interactive
shell with the --login option, it first attempts to
read and execute commands from
/etc/profile and
~/.profile, in that order.
The
--noprofile option may be used to inhibit this behavior.
When invoked as an interactive shell with the name
sh, bash looks for the variable
 ENV, expands its value if it is defined, and uses the
expanded value as the name of a file to read and execute.
Since a shell invoked as
sh does not attempt to read and execute commands from any other startup
files, the
--rcfile option has no effect.
A non-interactive shell invoked with the name
sh does not attempt to read any other startup files.
When invoked as
sh, bash enters
posix mode after the startup files are read.


When
bash is started in
posix mode, as with the
--posix command line option, it follows the POSIX standard for startup files.
In this mode, interactive shells expand the
 ENV variable and commands are read and executed from the file
whose name is the expanded value.
No other startup files are read.


Bash attempts to determine when it is being run by the remote shell
daemon, usually rshd.
If
bash determines it is being run by rshd, it reads and executes
commands from ~/.bashrc, if that file exists and is readable.
It will not do this if invoked as sh.
The
--norc option may be used to inhibit this behavior, and the
--rcfile option may be used to force another file to be read, but
rshd does not generally invoke the shell with those options
or allow them to be specified.


If the shell is started with the effective user (group) id not equal to the
real user (group) id, and the -p option is not supplied, no startup
files are read, shell functions are not inherited from the environment, the
 SHELLOPTS variable, if it appears in the environment, is ignored,
and the effective user id is set to the real user id.
If the -p option is supplied at invocation, the startup behavior is
the same, but the effective user id is not reset.


The following definitions are used throughout the rest of this
document.


|  &  ;  (  )  <  >  space  tab




||  &  &&  ;  ;;  (  )  |  <newline>



 
!    case    do    done    elif    else    esac    fi    for    function    if    in    select    then    until    while    {    }    time    [[    ]]


A simple command is a sequence of optional variable assignments
followed by blank-separated words and redirections, and
terminated by a control operator.  The first word
specifies the command to be executed, and is passed as argument zero.
The remaining words are passed as arguments to the invoked command.


The return value of a simple command is its exit status, or
128+n if the command is terminated by signal
n. 

A pipeline is a sequence of one or more commands separated by
the character
|. The format for a pipeline is:


[time [-p]] [ ! ] command [ | command2 ... ]


The standard output of
command is connected via a pipe to the standard input of
command2. This connection is performed before any redirections specified by the
command (see
 REDIRECTION below).


The return status of a pipeline is the exit status of the last
command, unless the pipefail option is enabled.
If pipefail is enabled, the pipeline’s return status is the
value of the last (rightmost) command to exit with a non-zero status,
or zero if all commands exit successfully.
If the reserved word
! precedes a pipeline, the exit status of that pipeline is the logical
negation of the exit status as described above.
The shell waits for all commands in the pipeline to
terminate before returning a value.


If the
time reserved word precedes a pipeline, the elapsed as well as user and
system time consumed by its execution are reported when the pipeline
terminates.
The -p option changes the output format to that specified by POSIX.
The
 TIMEFORMAT variable may be set to a format string that specifies how the timing
information should be displayed; see the description of
 TIMEFORMAT under
Shell Variables below.


Each command in a pipeline is executed as a separate process (i.e., in a
subshell).


A list is a sequence of one or more pipelines separated by one
of the operators
;, &, &&, or
||, and optionally terminated by one of
;, &, or
<newline>. 

Of these list operators,
&& and
|| have equal precedence, followed by
; and
&, which have equal precedence.


A sequence of one or more newlines may appear in a list instead
of a semicolon to delimit commands.


If a command is terminated by the control operator
&, the shell executes the command in the background
in a subshell.  The shell does not wait for the command to
finish, and the return status is 0.  Commands separated by a
; are executed sequentially; the shell waits for each
command to terminate in turn.  The return status is the
exit status of the last command executed.


The control operators
&& and
|| denote AND lists and OR lists, respectively.
An AND list has the form


command1 && command2


command2 is executed if, and only if,
command1 returns an exit status of zero.


An OR list has the form


command1 || command2




command2 is executed if and only if
command1 returns a non-zero exit status.  The return status of
AND and OR lists is the exit status of the last command
executed in the list.


A compound command is one of the following:



When the == and != operators are used, the string to the
right of the operator is considered a pattern and matched according
to the rules described below under Pattern Matching.
If the shell option
nocasematch is enabled, the match is performed without regard to the case
of alphabetic characters.
The return value is 0 if the string matches (==) or does not match
(!=) the pattern, and 1 otherwise.
Any part of the pattern may be quoted to force it to be matched as a
string.



An additional binary operator, =~, is available, with the same
precedence as == and !=.
When it is used, the string to the right of the operator is considered
an extended regular expression and matched accordingly (as in regex(3)). 
The return value is 0 if the string matches
the pattern, and 1 otherwise.
If the regular expression is syntactically incorrect, the conditional
expression’s return value is 2.
If the shell option
nocasematch is enabled, the match is performed without regard to the case
of alphabetic characters.
Substrings matched by parenthesized subexpressions within the regular
expression are saved in the array variable BASH_REMATCH.
The element of BASH_REMATCH with index 0 is the portion of the string
matching the entire regular expression.
The element of BASH_REMATCH with index n is the portion of the
string matching the nth parenthesized subexpression.



Expressions may be combined using the following operators, listed
in decreasing order of precedence:





A shell function is an object that is called like a simple command and
executes a compound command with a new set of positional parameters.
Shell functions are declared as follows:


Each of the metacharacters listed above under
 DEFINITIONS has special meaning to the shell and must be quoted if it is to
represent itself.


When the command history expansion facilities are being used
(see
 HISTORY EXPANSION below), the
history expansion character, usually !, must be quoted
to prevent history expansion.


There are three quoting mechanisms: the
escape character, single quotes, and double quotes.


A non-quoted backslash (\) is the
escape character. It preserves the literal value of the next character that follows,
with the exception of <newline>.  If a \<newline> pair
appears, and the backslash is not itself quoted, the \<newline>
is treated as a line continuation (that is, it is removed from the
input stream and effectively ignored).


Enclosing characters in single quotes preserves the literal value
of each character within the quotes.  A single quote may not occur
between single quotes, even when preceded by a backslash.


Enclosing characters in double quotes preserves the literal value
of all characters within the quotes, with the exception of
$, ‘, \, and, when history expansion is enabled,
!. The characters
$ and
‘ retain their special meaning within double quotes.  The backslash
retains its special meaning only when followed by one of the following
characters:
$, ‘, ",
\, or
<newline>. A double quote may be quoted within double quotes by preceding it with
a backslash.
If enabled, history expansion will be performed unless an
! appearing in double quotes is escaped using a backslash.
The backslash preceding the
! is not removed.


The special parameters
* and
@ have special meaning when in double
quotes (see
 PARAMETERS below).


Words of the form $\(aqstring\(aq are treated specially.  The
word expands to string, with backslash-escaped characters replaced
as specified by the ANSI C standard.  Backslash escape sequences, if
present, are decoded as follows:


The expanded result is single-quoted, as if the dollar sign had
not been present.


A double-quoted string preceded by a dollar sign ($) will cause
the string to be translated according to the current locale.
If the current locale is C or POSIX, the dollar sign
is ignored.
If the string is translated and replaced, the replacement is
double-quoted.


A parameter is set if it has been assigned a value.  The null string is
a valid value.  Once a variable is set, it may be unset only by using
the
unset builtin command (see
 SHELL BUILTIN COMMANDS below).


A
variable may be assigned to by a statement of the form


name=[value]


If
value is not given, the variable is assigned the null string.  All
values undergo tilde expansion, parameter and variable expansion,
command substitution, arithmetic expansion, and quote
removal (see
 EXPANSION below).  If the variable has its
integer attribute set, then
value is evaluated as an arithmetic expression even if the $((...)) expansion is
not used (see
Arithmetic Expansion below).
Word splitting is not performed, with the exception
of "$@" as explained below under
Special Parameters. Pathname expansion is not performed.
Assignment statements may also appear as arguments to the
alias, declare, typeset, export, readonly, and
local builtin commands.


In the context where an assignment statement is assigning a value
to a shell variable or array index, the += operator can be used to
append to or add to the variable’s previous value.
When += is applied to a variable for which the integer attribute has been
set, value is evaluated as an arithmetic expression and added to the
variable’s current value, which is also evaluated.
When += is applied to an array variable using compound assignment (see
Arrays below), the
variable’s value is not unset (as it is when using =), and new values are
appended to the array beginning at one greater than the array’s maximum index.
When applied to a string-valued variable, value is expanded and
appended to the variable’s value.


A
positional parameter is a parameter denoted by one or more
digits, other than the single digit 0.  Positional parameters are
assigned from the shell’s arguments when it is invoked,
and may be reassigned using the
set builtin command.  Positional parameters may not be assigned to
with assignment statements.  The positional parameters are
temporarily replaced when a shell function is executed (see
 FUNCTIONS below).


When a positional parameter consisting of more than a single
digit is expanded, it must be enclosed in braces (see
 EXPANSION below).


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


The following variables are set by the shell:






MAILPATH=\(aq/var/mail/bfox?"You have mail":~/shell-mail?"$_ has mail!"\(aq


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).




An array is created automatically if any variable is assigned to using
the syntax name[subscript]=value.  The
subscript is treated as an arithmetic expression that must evaluate to a number
greater than or equal to zero.  To explicitly declare an array, use
declare -a name (see
 SHELL BUILTIN COMMANDS below).
declare -a name[subscript] is also accepted; the subscript is ignored.  Attributes may be
specified for an array variable using the
declare and
readonly builtins.  Each attribute applies to all members of an array.


Arrays are assigned to using compound assignments of the form
name=(value1 ... valuen), where each
value is of the form [subscript]=string.  Only
string is required.  If
the optional brackets and subscript are supplied, that index is assigned to;
otherwise the index of the element assigned is the last index assigned
to by the statement plus one.  Indexing starts at zero.
This syntax is also accepted by the
declare builtin.  Individual array elements may be assigned to using the
name[subscript]=value syntax introduced above.


Any element of an array may be referenced using
${name[subscript]}.  The braces are required to avoid
conflicts with pathname expansion.  If
subscript is @ or *, the word expands to
all members of name.  These subscripts differ only when the
word appears within double quotes.  If the word is double-quoted,
${name[*]} expands to a single
word with the value of each array member separated by the first
character of the
 IFS special variable, and ${name[@]} expands each element of
name to a separate word.  When there are no array members,
${name[@]} expands to nothing.
If the double-quoted expansion occurs within a word, the expansion of
the first parameter is joined with the beginning part of the original
word, and the expansion of the last parameter is joined with the last
part of the original word.
This is analogous to the expansion
of the special parameters * and @ (see
Special Parameters above).  ${#name[subscript]} expands to the length of
${name[subscript]}.  If subscript is * or
@, the expansion is the number of elements in the array.
Referencing an array variable without a subscript is equivalent to
referencing element zero.


The
unset builtin is used to destroy arrays.  unset name[subscript]
destroys the array element at index subscript.
Care must be taken to avoid unwanted side effects caused by filename
generation.
unset name, where name is an array, or
unset name[subscript], where
subscript is * or @, removes the entire array.


The
declare, local, and
readonly builtins each accept a
-a option to specify an array.  The
read builtin accepts a
-a option to assign a list of words read from the standard input
to an array.  The
set and
declare builtins display array values in a way that allows them to be
reused as assignments.


The order of expansions is: brace expansion, tilde expansion,
parameter, variable and arithmetic expansion and
command substitution
(done in a left-to-right fashion), word splitting, and pathname
expansion.


On systems that can support it, there is an additional expansion
available: process substitution.


Only brace expansion, word splitting, and pathname expansion
can change the number of words of the expansion; other expansions
expand a single word to a single word.
The only exceptions to this are the expansions of
"$@" and "${name[@]}"
as explained above (see
 PARAMETERS). 

Brace expansion is a mechanism by which arbitrary strings
may be generated.  This mechanism is similar to
pathname expansion, but the filenames generated
need not exist.  Patterns to be brace expanded take
the form of an optional
preamble, followed by either a series of comma-separated strings or
a sequence expression between a pair of braces, followed by
an optional
postscript. The preamble is prefixed to each string contained
within the braces, and the postscript is then appended
to each resulting string, expanding left to right.


Brace expansions may be nested.  The results of each expanded
string are not sorted; left to right order is preserved.
For example, a{d,c,b}e expands into ‘ade ace abe’.


A sequence expression takes the form {x..y},
where x and y are either integers or single characters.
When integers are supplied, the expression expands to each number between
x and y, inclusive.
When characters are supplied, the expression expands to each character
lexicographically between x and y, inclusive.  Note that
both x and y must be of the same type.


Brace expansion is performed before any other expansions,
and any characters special to other expansions are preserved
in the result.  It is strictly textual.
Bash does not apply any syntactic interpretation to the context of the
expansion or the text between the braces.


A correctly-formed brace expansion must contain unquoted opening
and closing braces, and at least one unquoted comma or a valid
sequence expression.
Any incorrectly formed brace expansion is left unchanged.
A { or , may be quoted with a backslash to prevent its
being considered part of a brace expression.
To avoid conflicts with parameter expansion, the string ${
is not considered eligible for brace expansion.


This construct is typically used as shorthand when the common
prefix of the strings to be generated is longer than in the
above example:


mkdir /usr/local/src/bash/{old,new,dist,bugs}
or
chown root /usr/{ucb/{ex,edit},lib/{ex?.?*,how_ex}}


Brace expansion introduces a slight incompatibility with
historical versions of
sh. sh does not treat opening or closing braces specially when they
appear as part of a word, and preserves them in the output.
Bash removes braces from words as a consequence of brace
expansion.  For example, a word entered to
sh as file{1,2}
appears identically in the output.  The same word is
output as
file1 file2 after expansion by
bash. If strict compatibility with
sh is desired, start
bash with the
+B option or disable brace expansion with the
+B option to the
set command (see
 SHELL BUILTIN COMMANDS below).


If a word begins with an unquoted tilde character (‘~’), all of
the characters preceding the first unquoted slash (or all characters,
if there is no unquoted slash) are considered a tilde-prefix.
If none of the characters in the tilde-prefix are quoted, the
characters in the tilde-prefix following the tilde are treated as a
possible login name.
If this login name is the null string, the tilde is replaced with the
value of the shell parameter
 HOME. If
 HOME is unset, the home directory of the user executing the shell is
substituted instead.
Otherwise, the tilde-prefix is replaced with the home directory
associated with the specified login name.


If the tilde-prefix is a ‘~+’, the value of the shell variable
 PWD replaces the tilde-prefix.
If the tilde-prefix is a ‘~-’, the value of the shell variable
 OLDPWD, if it is set, is substituted.
If the characters following the tilde in the tilde-prefix consist
of a number N, optionally prefixed
by a ‘+’ or a ‘-’, the tilde-prefix is replaced with the corresponding
element from the directory stack, as it would be displayed by the
dirs builtin invoked with the tilde-prefix as an argument.
If the characters following the tilde in the tilde-prefix consist of a
number without a leading ‘+’ or ‘-’, ‘+’ is assumed.


If the login name is invalid, or the tilde expansion fails, the word
is unchanged.


Each variable assignment is checked for unquoted tilde-prefixes immediately
following a
: or the first
=. In these cases, tilde expansion is also performed.
Consequently, one may use file names with tildes in assignments to
 PATH,  MAILPATH, and
 CDPATH, and the shell assigns the expanded value.


The ‘$’ character introduces parameter expansion,
command substitution, or arithmetic expansion.  The parameter name
or symbol to be expanded may be enclosed in braces, which
are optional but serve to protect the variable to be expanded from
characters immediately following it which could be
interpreted as part of the name.


When braces are used, the matching ending brace is the first ‘}’
not escaped by a backslash or within a quoted string, and not within an
embedded arithmetic expansion, command substitution, or parameter
expansion.




Command substitution allows the output of a command to replace
the command name.  There are two forms:




$(command)
or
‘command‘


Bash performs the expansion by executing command and
replacing the command substitution with the standard output of the
command, with any trailing newlines deleted.
Embedded newlines are not deleted, but they may be removed during
word splitting.
The command substitution $(cat file) can be replaced by
the equivalent but faster $(< file).


When the old-style backquote form of substitution is used,
backslash retains its literal meaning except when followed by
$, ‘, or
\. The first backquote not preceded by a backslash terminates the
command substitution.
When using the $(command) form, all characters between the
parentheses make up the command; none are treated specially.


Command substitutions may be nested.  To nest when using the backquoted form,
escape the inner backquotes with backslashes.


If the substitution appears within double quotes, word splitting and
pathname expansion are not performed on the results.


Arithmetic expansion allows the evaluation of an arithmetic expression
and the substitution of the result.  The format for arithmetic expansion is:


$((expression))


The
expression is treated as if it were within double quotes, but a double quote
inside the parentheses is not treated specially.
All tokens in the expression undergo parameter expansion, string
expansion, command substitution, and quote removal.
Arithmetic expansions may be nested.


The evaluation is performed according to the rules listed below under
 ARITHMETIC EVALUATION. If
expression is invalid,
bash prints a message indicating failure and no substitution occurs.


Process substitution is supported on systems that support named
pipes (FIFOs) or the /dev/fd method of naming open files.
It takes the form of
<(list)
or
>(list).
The process list is run with its input or output connected to a
FIFO or some file in /dev/fd.  The name of this file is
passed as an argument to the current command as the result of the
expansion.  If the >(list) form is used, writing to
the file will provide input for list.  If the
<(list) form is used, the file passed as an
argument should be read to obtain the output of list.


When available, process substitution is performed
simultaneously with parameter and variable expansion,
command substitution,
and arithmetic expansion.


The shell scans the results of
parameter expansion,
command substitution,
and
arithmetic expansion
that did not occur within double quotes for
word splitting. 

The shell treats each character of
 IFS as a delimiter, and splits the results of the other
expansions into words on these characters.  If
 IFS is unset, or its
value is exactly
<space><tab><newline>, the default, then
any sequence of
 IFS characters serves to delimit words.  If
 IFS has a value other than the default, then sequences of
the whitespace characters
space and
tab are ignored at the beginning and end of the
word, as long as the whitespace character is in the
value of
 IFS (an
 IFS whitespace character).
Any character in
 IFS that is not
 IFS whitespace, along with any adjacent
 IFS whitespace characters, delimits a field.
A sequence of
 IFS whitespace characters is also treated as a delimiter.
If the value of
 IFS is null, no word splitting occurs.


Explicit null arguments ("" or \(aq\(aq) are retained.
Unquoted implicit null arguments, resulting from the expansion of
parameters that have no values, are removed.
If a parameter with no value is expanded within double quotes, a
null argument results and is retained.


Note that if no expansion occurs, no splitting
is performed.


After word splitting,
unless the
-f option has been set,
bash scans each word for the characters
*, ?, and
[. If one of these characters appears, then the word is
regarded as a
pattern, and replaced with an alphabetically sorted list of
file names matching the pattern.
If no matching file names are found,
and the shell option
nullglob is disabled, the word is left unchanged.
If the
nullglob option is set, and no matches are found,
the word is removed.
If the
failglob shell option is set, and no matches are found, an error message
is printed and the command is not executed.
If the shell option
nocaseglob is enabled, the match is performed without regard to the case
of alphabetic characters.
When a pattern is used for pathname expansion,
the character
‘‘.’’ at the start of a name or immediately following a slash
must be matched explicitly, unless the shell option
dotglob is set.
When matching a pathname, the slash character must always be
matched explicitly.
In other cases, the
‘‘.’’ character is not treated specially.
See the description of
shopt below under
 SHELL BUILTIN COMMANDS for a description of the
nocaseglob, nullglob, failglob, and
dotglob shell options.


The
 GLOBIGNORE shell variable may be used to restrict the set of file names matching a
pattern. If
 GLOBIGNORE is set, each matching file name that also matches one of the patterns in
 GLOBIGNORE is removed from the list of matches.
The file names
‘‘.’’ and
‘‘..’’ are always ignored when
 GLOBIGNORE is set and not null.  However, setting
 GLOBIGNORE to a non-null value has the effect of enabling the
dotglob shell option, so all other file names beginning with a
‘‘.’’ will match.
To get the old behavior of ignoring file names beginning with a
‘‘.’’, make
‘‘.*’’ one of the patterns in
 GLOBIGNORE. The
dotglob option is disabled when
 GLOBIGNORE is unset.


Pattern Matching


Any character that appears in a pattern, other than the special pattern
characters described below, matches itself.  The NUL character may not
occur in a pattern.  A backslash escapes the following character; the
escaping backslash is discarded when matching.
The special pattern characters must be quoted if
they are to be matched literally.


The special pattern characters have the following meanings:





Within
[ and
], character classes can be specified using the syntax
[:class:], where class is one of the
following classes defined in the POSIX standard:


 
alnum   alpha   ascii   blank   cntrl   digit   graph   lower   print   punct   space   upper   word   xdigit

A character class matches any character belonging to that class.
The word character class matches letters, digits, and the character _.



Within
[ and
], an equivalence class can be specified using the syntax
[=c=], which matches all characters with the
same collation weight (as defined by the current locale) as
the character c.



Within
[ and
], the syntax [.symbol.] matches the collating symbol
symbol.




After the preceding expansions, all unquoted occurrences of the
characters
\, \(aq, and " that did not result from one of the above
expansions are removed.


In the following descriptions, if the file descriptor number is
omitted, and the first character of the redirection operator is
<, the redirection refers to the standard input (file descriptor
0).  If the first character of the redirection operator is
>, the redirection refers to the standard output (file descriptor
1).


The word following the redirection operator in the following
descriptions, unless otherwise noted, is subjected to brace expansion,
tilde expansion, parameter expansion, command substitution, arithmetic
expansion, quote removal, pathname expansion, and word splitting.
If it expands to more than one word,
bash reports an error.


Note that the order of redirections is significant.  For example,
the command


ls > dirlist 2>&1


directs both standard output and standard error to the file
dirlist, while the command


ls 2>&1 > dirlist


directs only the standard output to file
dirlist, because the standard error was duplicated as standard output
before the standard output was redirected to
dirlist. 

Bash handles several filenames specially when they are used in
redirections, as described in the following table:




A failure to open or create a file causes the redirection to fail.


Redirections using file descriptors greater than 9 should be used with
care, as they may conflict with file descriptors the shell uses
internally.


Redirection of input causes the file whose name results from
the expansion of
word to be opened for reading on file descriptor
n, or the standard input (file descriptor 0) if
n is not specified.


The general format for redirecting input is:


[n]<word


Redirection of output causes the file whose name results from
the expansion of
word to be opened for writing on file descriptor
n, or the standard output (file descriptor 1) if
n is not specified.  If the file does not exist it is created;
if it does exist it is truncated to zero size.


The general format for redirecting output is:


[n]>word


If the redirection operator is
>, and the
noclobber option to the
set builtin has been enabled, the redirection will fail if the file
whose name results from the expansion of word exists and is
a regular file.
If the redirection operator is
>|, or the redirection operator is
> and the
noclobber option to the
set builtin command is not enabled, the redirection is attempted even
if the file named by word exists.


Redirection of output in this fashion
causes the file whose name results from
the expansion of
word to be opened for appending on file descriptor
n, or the standard output (file descriptor 1) if
n is not specified.  If the file does not exist it is created.


The general format for appending output is:


[n]>>word




Bash allows both the
standard output (file descriptor 1) and
the standard error output (file descriptor 2)
to be redirected to the file whose name is the
expansion of
word with this construct.


There are two formats for redirecting standard output and
standard error:


&>word
and
>&word


Of the two forms, the first is preferred.
This is semantically equivalent to


>word 2>&1


This type of redirection instructs the shell to read input from the
current source until a line containing only
word (with no trailing blanks)
is seen.  All of
the lines read up to that point are then used as the standard
input for a command.


The format of here-documents is:



<<[-]word
        here-document
delimiter


No parameter expansion, command substitution, arithmetic expansion,
or pathname expansion is performed on
word. If any characters in
word are quoted, the
delimiter is the result of quote removal on
word, and the lines in the here-document are not expanded.
If word is unquoted,
all lines of the here-document are subjected to parameter expansion,
command substitution, and arithmetic expansion.  In the latter
case, the character sequence
\<newline> is ignored, and
\ must be used to quote the characters
\, $, and
‘. 

If the redirection operator is
<<-, then all leading tab characters are stripped from input lines and the
line containing
delimiter. This allows
here-documents within shell scripts to be indented in a
natural fashion.



<<<word


The word is expanded and supplied to the command on its standard
input.


The redirection operator


[n]<&word


is used to duplicate input file descriptors.
If
word expands to one or more digits, the file descriptor denoted by
n is made to be a copy of that file descriptor.
If the digits in
word do not specify a file descriptor open for input, a redirection error occurs.
If
word evaluates to
-, file descriptor
n is closed.  If
n is not specified, the standard input (file descriptor 0) is used.


The operator


[n]>&word


is used similarly to duplicate output file descriptors.  If
n is not specified, the standard output (file descriptor 1) is used.
If the digits in
word do not specify a file descriptor open for output, a redirection error occurs.
As a special case, if n is omitted, and word does not
expand to one or more digits, the standard output and standard
error are redirected as described previously.


The redirection operator


[n]<&digit-


moves the file descriptor digit to file descriptor
n, or the standard input (file descriptor 0) if n is not specified.
digit is closed after being duplicated to n.


Similarly, the redirection operator


[n]>&digit-


moves the file descriptor digit to file descriptor
n, or the standard output (file descriptor 1) if n is not specified.


The redirection operator


[n]<>word


causes the file whose name is the expansion of
word to be opened for both reading and writing on file descriptor
n, or on file descriptor 0 if
n is not specified.  If the file does not exist, it is created.


Aliases are created and listed with the
alias command, and removed with the
unalias command.


There is no mechanism for using arguments in the replacement text.
If arguments are needed, a shell function should be used (see
 FUNCTIONS below).


Aliases are not expanded when the shell is not interactive, unless
the
expand_aliases shell option is set using
shopt (see the description of
shopt under
 SHELL BUILTIN COMMANDS
below).


The rules concerning the definition and use of aliases are
somewhat confusing.
Bash always reads at least one complete line
of input before executing any
of the commands on that line.  Aliases are expanded when a
command is read, not when it is executed.  Therefore, an
alias definition appearing on the same line as another
command does not take effect until the next line of input is read.
The commands following the alias definition
on that line are not affected by the new alias.
This behavior is also an issue when functions are executed.
Aliases are expanded when a function definition is read,
not when the function is executed, because a function definition
is itself a compound command.  As a consequence, aliases
defined in a function are not available until after that
function is executed.  To be safe, always put
alias definitions on a separate line, and do not use
alias in compound commands.


For almost every purpose, aliases are superseded by
shell functions.


Variables local to the function may be declared with the
local builtin command.  Ordinarily, variables and their values
are shared between the function and its caller.


If the builtin command
return is executed in a function, the function completes and
execution resumes with the next command after the function
call.
Any command associated with the RETURN trap is executed
before execution resumes.
When a function completes, the values of the
positional parameters and the special parameter
# are restored to the values they had prior to the function’s
execution.


Function names and definitions may be listed with the
-f option to the
declare or
typeset builtin commands.  The
-F option to
declare or
typeset will list the function names only
(and optionally the source file and line number, if the extdebug
shell option is enabled).
Functions may be exported so that subshells
automatically have them defined with the
-f option to the
export builtin.
A function definition may be deleted using the -f option to
the
unset builtin.
Note that shell functions and variables with the same name may result
in multiple identically-named entries in the environment passed to the
shell’s children.
Care should be taken in cases where this may cause a problem.


Functions may be recursive.  No limit is imposed on the number
of recursive calls.




Constants with a leading 0 are interpreted as octal numbers.
A leading 0x or 0X denotes hexadecimal.
Otherwise, numbers take the form [base#]n, where base
is a decimal number between 2 and 64 representing the arithmetic
base, and n is a number in that base.
If base# is omitted, then base 10 is used.
The digits greater than 9 are represented by the lowercase letters,
the uppercase letters, @, and _, in that order.
If base is less than or equal to 36, lowercase and uppercase
letters may be used interchangeably to represent numbers between 10
and 35.


Operators are evaluated in order of precedence.  Sub-expressions in
parentheses are evaluated first and may override the precedence
rules above.


Unless otherwise specified, primaries that operate on files follow symbolic
links and operate on the target of the link, rather than the link itself.




If no command name results, redirections are performed, but do not
affect the current shell environment.  A redirection error causes the
command to exit with a non-zero status.


If there is a command name left after expansion, execution proceeds as
described below.  Otherwise, the command exits.  If one of the expansions
contained a command substitution, the exit status of the command is
the exit status of the last command substitution performed.  If there
were no command substitutions, the command exits with a status of zero.


If the command name contains no slashes, the shell attempts to
locate it.  If there exists a shell function by that name, that
function is invoked as described above in
 FUNCTIONS. If the name does not match a function, the shell searches for
it in the list of shell builtins.  If a match is found, that
builtin is invoked.


If the name is neither a shell function nor a builtin,
and contains no slashes,
bash searches each element of the
 PATH for a directory containing an executable file by that name.
Bash uses a hash table to remember the full pathnames of executable
files (see
hash under
 SHELL BUILTIN COMMANDS below).
A full search of the directories in
 PATH is performed only if the command is not found in the hash table.
If the search is unsuccessful, the shell prints an error
message and returns an exit status of 127.


If the search is successful, or if the command name contains
one or more slashes, the shell executes the named program in a
separate execution environment.
Argument 0 is set to the name given, and the remaining arguments
to the command are set to the arguments given, if any.


If this execution fails because the file is not in executable
format, and the file is not a directory, it is assumed to be
a shell script, a file
containing shell commands.  A subshell is spawned to execute
it.  This subshell reinitializes itself, so
that the effect is as if a new shell had been invoked
to handle the script, with the exception that the locations of
commands remembered by the parent (see
hash below under
 SHELL BUILTIN COMMANDS)
are retained by the child.


If the program is a file beginning with
#!, the remainder of the first line specifies an interpreter
for the program.  The shell executes the
specified interpreter on operating systems that do not
handle this executable format themselves.  The arguments to the
interpreter consist of a single optional argument following the
interpreter name on the first line of the program, followed
by the name of the program, followed by the command
arguments, if any.






Command substitution, commands grouped with parentheses,
and asynchronous commands are invoked in a
subshell environment that is a duplicate of the shell environment,
except that traps caught by the shell are reset to the values
that the shell inherited from its parent at invocation.  Builtin
commands that are invoked as part of a pipeline are also executed in a
subshell environment.  Changes made to the subshell environment
cannot affect the shell’s execution environment.


If a command is followed by a & and job control is not active, the
default standard input for the command is the empty file /dev/null.
Otherwise, the invoked command inherits the file descriptors of the calling
shell as modified by redirections.


The shell provides several ways to manipulate the environment.
On invocation, the shell scans its own environment and
creates a parameter for each name found, automatically marking
it for
export to child processes.  Executed commands inherit the environment.
The
export and
declare -x commands allow parameters and functions to be added to and
deleted from the environment.  If the value of a parameter
in the environment is modified, the new value becomes part
of the environment, replacing the old.  The environment
inherited by any executed command consists of the shell’s
initial environment, whose values may be modified in the shell,
less any pairs removed by the
unset command, plus any additions via the
export and
declare -x commands.


The environment for any
simple command or function may be augmented temporarily by prefixing it with
parameter assignments, as described above in
 PARAMETERS. These assignment statements affect only the environment seen
by that command.


If the
-k option is set (see the
set builtin command below), then
all parameter assignments are placed in the environment for a command,
not just those that precede the command name.


When
bash invokes an external command, the variable
_ is set to the full file name of the command and passed to that
command in its environment.


If a command is not found, the child process created to
execute it returns a status of 127.  If a command is found
but is not executable, the return status is 126.


If a command fails because of an error during expansion or redirection,
the exit status is greater than zero.


Shell builtin commands return a status of 0 (true) if
successful, and non-zero (false) if an error occurs
while they execute.
All builtins return an exit status of 2 to indicate incorrect usage.


Bash itself returns the exit status of the last command
executed, unless a syntax error occurs, in which case it exits
with a non-zero value.  See also the exit builtin
command below.


Non-builtin commands run by bash have signal handlers
set to the values inherited by the shell from its parent.
When job control is not in effect, asynchronous commands
ignore
 SIGINT and
 SIGQUIT in addition to these inherited handlers.
Commands run as a result of command substitution ignore the
keyboard-generated job control signals
 SIGTTIN,  SIGTTOU, and
 SIGTSTP. 

The shell exits by default upon receipt of a
 SIGHUP. Before exiting, an interactive shell resends the
 SIGHUP to all jobs, running or stopped.
Stopped jobs are sent
 SIGCONT to ensure that they receive the
 SIGHUP. To prevent the shell from
sending the signal to a particular job, it should be removed from the
jobs table with the
disown builtin (see
 SHELL BUILTIN COMMANDS below) or marked
to not receive
 SIGHUP using
disown -h. 

If the
huponexit shell option has been set with
shopt, bash sends a
 SIGHUP to all jobs when an interactive login shell exits.


If bash is waiting for a command to complete and receives a signal
for which a trap has been set, the trap will not be executed until
the command completes.
When bash is waiting for an asynchronous command via the wait
builtin, the reception of a signal for which a trap has been set will
cause the wait builtin to return immediately with an exit status
greater than 128, immediately after which the trap is executed.


The shell associates a
job with each pipeline.  It keeps a table of currently executing
jobs, which may be listed with the
jobs command.  When
bash starts a job asynchronously (in the
background), it prints a line that looks like:


[1] 25647


indicating that this job is job number 1 and that the process ID
of the last process in the pipeline associated with this job is 25647.
All of the processes in a single pipeline are members of the same job.
Bash uses the
job abstraction as the basis for job control.


To facilitate the implementation of the user interface to job
control, the operating system maintains the notion of a current terminal
process group ID.  Members of this process group (processes whose
process group ID is equal to the current terminal process group ID)
receive keyboard-generated signals such as
 SIGINT. These processes are said to be in the
foreground. Background processes are those whose process group ID differs from the terminal’s;
such processes are immune to keyboard-generated signals.
Only foreground processes are allowed to read from or write to the
terminal.  Background processes which attempt to read from (write to) the
terminal are sent a
 SIGTTIN (SIGTTOU) signal by the terminal driver,
which, unless caught, suspends the process.


If the operating system on which
bash is running supports
job control,
bash contains facilities to use it.
Typing the
suspend character (typically
^Z, Control-Z) while a process is running
causes that process to be stopped and returns control to
bash. Typing the
delayed suspend character (typically
^Y, Control-Y) causes the process to be stopped when it
attempts to read input from the terminal, and control to
be returned to
bash. The user may then manipulate the state of this job, using the
bg command to continue it in the background, the
fg command to continue it in the foreground, or
the
kill command to kill it.  A ^Z takes effect immediately,
and has the additional side effect of causing pending output
and typeahead to be discarded.


There are a number of ways to refer to a job in the shell.
The character
% introduces a job name.  Job number
n may be referred to as
%n. A job may also be referred to using a prefix of the name used to
start it, or using a substring that appears in its command line.
For example,
%ce refers to a stopped
ce job.  If a prefix matches more than one job,
bash reports an error.  Using
%?ce, on the other hand, refers to any job containing the string
ce in its command line.  If the substring matches more than one job,
bash reports an error.  The symbols
%% and
%+ refer to the shell’s notion of the
current job, which is the last job stopped while it was in
the foreground or started in the background.
The
previous job may be referenced using
%-. When there is the current job only,
%- refers to the shell’s notion of the current job.
In output pertaining to jobs (e.g., the output of the
jobs command), the current job is always flagged with a
+, and the previous job with a
-. A single % (with no accompanying job specification) also refers to the
current job.


Simply naming a job can be used to bring it into the
foreground:
%1 is a synonym for
‘‘fg %1’’,
bringing job 1 from the background into the foreground.
Similarly,
‘‘%1 &’’ resumes job 1 in the background, equivalent to
‘‘bg %1’’.


The shell learns immediately whenever a job changes state.
Normally,
bash waits until it is about to print a prompt before reporting
changes in a job’s status so as to not interrupt
any other output.  If the
-b option to the
set builtin command
is enabled,
bash reports such changes immediately.
Any trap on
 SIGCHLD is executed for each child that exits.


If an attempt to exit
bash is made while jobs are stopped, the shell prints a warning message.  The
jobs command may then be used to inspect their status.
If a second attempt to exit is made without an intervening command,
the shell does not print another warning, and the stopped
jobs are terminated.


The command number and the history number are usually different:
the history number of a command is its position in the history
list, which may include commands restored from the history file
(see
 HISTORY below), while the command number is the position in the sequence
of commands executed during the current shell session.
After the string is decoded, it is expanded via
parameter expansion, command substitution, arithmetic
expansion, and quote removal, subject to the value of the
promptvars shell option (see the description of the
shopt command under
 SHELL BUILTIN COMMANDS below).


In this section, the emacs-style notation is used to denote
keystrokes.  Control keys are denoted by C-key, e.g., C-n
means Control-N.  Similarly,
meta keys are denoted by M-key, so M-x means Meta-X.  (On keyboards
without a
meta key, M-x means ESC x, i.e., press the Escape key
then the
x key.  This makes ESC the meta prefix.
The combination M-C-x means ESC-Control-x,
or press the Escape key
then hold the Control key while pressing the
x key.)


Readline commands may be given numeric
arguments, which normally act as a repeat count.
Sometimes, however, it is the sign of the argument that is significant.
Passing a negative argument to a command that acts in the forward
direction (e.g., kill-line) causes that command to act in a
backward direction.
Commands whose behavior with arguments deviates from this are noted
below.


When a command is described as killing text, the text
deleted is saved for possible future retrieval
(yanking).  The killed text is saved in a
kill ring.  Consecutive kills cause the text to be
accumulated into one unit, which can be yanked all at once.
Commands which do not kill text separate the chunks of text
on the kill ring.


Readline is customized by putting commands in an initialization
file (the inputrc file).
The name of this file is taken from the value of the
 INPUTRC variable.  If that variable is unset, the default is
~/.inputrc. When a program which uses the readline library starts up, the
initialization file is read, and the key bindings and variables
are set.
There are only a few basic constructs allowed in the
readline initialization file.
Blank lines are ignored.
Lines beginning with a # are comments.
Lines beginning with a $ indicate conditional constructs.
Other lines denote key bindings and variable settings.


The default key-bindings may be changed with an
inputrc file.
Other programs that use this library may add their own commands
and bindings.


For example, placing


M-Control-u: universal-argument
or
C-Meta-u: universal-argument
into the
inputrc would make M-C-u execute the readline command
universal-argument. 

The following symbolic character names are recognized:
RUBOUT, DEL, ESC, LFD, NEWLINE, RET, RETURN, SPC, SPACE, and
TAB. 

In addition to command names, readline allows keys to be bound
to a string that is inserted when the key is pressed (a macro).


The syntax for controlling key bindings in the
inputrc file is simple.  All that is required is the name of the
command or the text of a macro and a key sequence to which
it should be bound. The name may be specified in one of two ways:
as a symbolic key name, possibly with Meta- or Control-
prefixes, or as a key sequence.


When using the form keyname:function-name or macro,
keyname is the name of a key spelled out in English.  For example:


Control-u: universal-argument

Meta-Rubout: backward-kill-word

Control-o: "> output"


In the above example,
C-u is bound to the function
universal-argument, M-DEL is bound to the function
backward-kill-word, and
C-o is bound to run the macro
expressed on the right hand side (that is, to insert the text
> output

into the line).


In the second form, "keyseq":function-name or macro,
keyseq differs from
keyname above in that strings denoting
an entire key sequence may be specified by placing the sequence
within double quotes.  Some GNU Emacs style key escapes can be
used, as in the following example, but the symbolic character names
are not recognized.


"\C-u": universal-argument

"\C-x\C-r": re-read-init-file

"\e[11~": "Function Key 1"


In this example,
C-u is again bound to the function
universal-argument. C-x C-r is bound to the function
re-read-init-file, and
ESC [ 1 1 ~ is bound to insert the text
Function Key 1.



The full set of GNU Emacs style escape sequences is


In addition to the GNU Emacs style escape sequences, a second
set of backslash escapes is available:


When entering the text of a macro, single or double quotes must
be used to indicate a macro definition.
Unquoted text is assumed to be a function name.
In the macro body, the backslash escapes described above are expanded.
Backslash will quote any other character in the macro text,
including " and \(aq.


Bash allows the current readline key bindings to be displayed or modified
with the
bind builtin command.  The editing mode may be switched during interactive
use by using the
-o option to the
set builtin command (see
 SHELL BUILTIN COMMANDS below).


Readline has variables that can be used to further customize its
behavior.  A variable may be set in the
inputrc file with a statement of the form


set variable-name value


Except where noted, readline variables can take the values
On or
Off (without regard to case).
Unrecognized variable names are ignored.
When a variable value is read, empty or null values, "on" (case-insensitive),
and "1" are equivalent to On.  All other values are equivalent to
Off.
The variables and their default values are:




Readline implements a facility similar in spirit to the conditional
compilation features of the C preprocessor which allows key
bindings and variable settings to be performed as the result
of tests.  There are four parser directives used.



$if Bash
# Quote the current or previous word
"\C-xq": "\eb\"\ef\""
$endif



$include  /etc/inputrc


Readline provides commands for searching through the command history
(see
 HISTORY below) for lines containing a specified string.
There are two search modes:
incremental and
non-incremental. 

Incremental searches begin before the user has finished typing the
search string.
As each character of the search string is typed, readline displays
the next entry from the history matching the string typed so far.
An incremental search requires only as many characters as needed to
find the desired history entry.
The characters present in the value of the isearch-terminators
variable are used to terminate an incremental search.
If that variable has not been assigned a value the Escape and
Control-J characters will terminate an incremental search.
Control-G will abort an incremental search and restore the original
line.
When the search is terminated, the history entry containing the
search string becomes the current line.


To find other matching entries in the history list, type Control-S or
Control-R as appropriate.
This will search backward or forward in the history for the next
entry matching the search string typed so far.
Any other key sequence bound to a readline command will terminate
the search and execute that command.
For instance, a newline will terminate the search and accept
the line, thereby executing the command from the history list.


Readline remembers the last incremental search string.  If two
Control-Rs are typed without any intervening characters defining a
new search string, any remembered search string is used.


Non-incremental searches read the entire search string before starting
to search for matching history lines.  The search string may be
typed by the user or be part of the contents of the current line.


The following is a list of the names of the commands and the default
key sequences to which they are bound.
Command names without an accompanying key sequence are unbound by default.
In the following descriptions, point refers to the current cursor
position, and mark refers to a cursor position saved by the
set-mark command.
The text between the point and mark is referred to as the region.


















When word completion is attempted for an argument to a command for
which a completion specification (a compspec) has been defined
using the complete builtin (see
 SHELL BUILTIN COMMANDS below), the programmable completion facilities are invoked.


First, the command name is identified.
If a compspec has been defined for that command, the
compspec is used to generate the list of possible completions for the word.
If the command word is a full pathname, a compspec for the full
pathname is searched for first.
If no compspec is found for the full pathname, an attempt is made to
find a compspec for the portion following the final slash.


Once a compspec has been found, it is used to generate the list of
matching words.
If a compspec is not found, the default bash completion as
described above under Completing is performed.


First, the actions specified by the compspec are used.
Only matches which are prefixed by the word being completed are
returned.
When the
-f or
-d option is used for filename or directory name completion, the shell
variable
 FIGNORE is used to filter the matches.


Any completions specified by a filename expansion pattern to the
-G option are generated next.
The words generated by the pattern need not match the word
being completed.
The
 GLOBIGNORE shell variable is not used to filter the matches, but the
 FIGNORE variable is used.


Next, the string specified as the argument to the -W option
is considered.
The string is first split using the characters in the
 IFS special variable as delimiters.
Shell quoting is honored.
Each word is then expanded using
brace expansion, tilde expansion, parameter and variable expansion,
command substitution, and arithmetic expansion,
as described above under
 EXPANSION. The results are split using the rules described above under
Word Splitting.
The results of the expansion are prefix-matched against the word being
completed, and the matching words become the possible completions.


After these matches have been generated, any shell function or command
specified with the -F and -C options is invoked.
When the command or function is invoked, the
 COMP_LINE and
 COMP_POINT variables are assigned values as described above under
Shell Variables.
If a shell function is being invoked, the
 COMP_WORDS and
 COMP_CWORD variables are also set.
When the function or command is invoked, the first argument is the
name of the command whose arguments are being completed, the
second argument is the word being completed, and the third argument
is the word preceding the word being completed on the current command line.
No filtering of the generated completions against the word being completed
is performed; the function or command has complete freedom in generating
the matches.


Any function specified with -F is invoked first.
The function may use any of the shell facilities, including the
compgen builtin described below, to generate the matches.
It must put the possible completions in the
 COMPREPLY array variable.


Next, any command specified with the -C option is invoked
in an environment equivalent to command substitution.
It should print a list of completions, one per line, to the
standard output.
Backslash may be used to escape a newline, if necessary.


After all of the possible completions are generated, any filter
specified with the -X option is applied to the list.
The filter is a pattern as used for pathname expansion; a &
in the pattern is replaced with the text of the word being completed.
A literal & may be escaped with a backslash; the backslash
is removed before attempting a match.
Any completion that matches the pattern will be removed from the list.
A leading ! negates the pattern; in this case any completion
not matching the pattern will be removed.


Finally, any prefix and suffix specified with the -P and -S
options are added to each member of the completion list, and the result is
returned to the readline completion code as the list of possible
completions.


If the previously-applied actions do not generate any matches, and the
-o dirnames option was supplied to complete when the
compspec was defined, directory name completion is attempted.


If the -o plusdirs option was supplied to complete when the
compspec was defined, directory name completion is attempted and any
matches are added to the results of the other actions.


By default, if a compspec is found, whatever it generates is returned
to the completion code as the full set of possible completions.
The default bash completions are not attempted, and the readline
default of filename completion is disabled.
If the -o bashdefault option was supplied to complete when
the compspec was defined, the bash default completions are attempted
if the compspec generates no matches.
If the -o default option was supplied to complete when the
compspec was defined, readline’s default completion will be performed
if the compspec (and, if attempted, the default bash completions)
generate no matches.


When a compspec indicates that directory name completion is desired,
the programmable completion functions force readline to append a slash
to completed names which are symbolic links to directories, subject to 
the value of the mark-directories readline variable, regardless
of the setting of the mark-symlinked-directories readline variable.


On startup, the history is initialized from the file named by
the variable
 HISTFILE (default ~/.bash_history).
The file named by the value of
 HISTFILE is truncated, if necessary, to contain no more than
the number of lines specified by the value of
 HISTFILESIZE. When an interactive shell exits, the last
 $HISTSIZE lines are copied from the history list to
 $HISTFILE. If the
histappend shell option is enabled
(see the description of
shopt under
 SHELL BUILTIN COMMANDS below), the lines are appended to the history file,
otherwise the history file is overwritten.
If
 HISTFILE is unset, or if the history file is unwritable, the history is
not saved.  After saving the history, the history file is truncated
to contain no more than
 HISTFILESIZE lines.  If
 HISTFILESIZE is not set, no truncation is performed.


The builtin command
fc (see
 SHELL BUILTIN COMMANDS below) may be used to list or edit and re-execute a portion of
the history list.
The
history builtin may be used to display or modify the history list and
manipulate the history file.
When using command-line editing, search commands
are available in each editing mode that provide access to the
history list.


The shell allows control over which commands are saved on the history
list.  The
 HISTCONTROL and
 HISTIGNORE variables may be set to cause the shell to save only a subset of the
commands entered.
The
cmdhist shell option, if enabled, causes the shell to attempt to save each
line of a multi-line command in the same history entry, adding
semicolons where necessary to preserve syntactic correctness.
The
lithist shell option causes the shell to save the command with embedded newlines
instead of semicolons.  See the description of the
shopt builtin below under
 SHELL BUILTIN COMMANDS for information on setting and unsetting shell options.


The shell supports a history expansion feature that
is similar to the history expansion in
csh. This section describes what syntax features are available.  This
feature is enabled by default for interactive shells, and can be
disabled using the
+H option to the
set builtin command (see
 SHELL BUILTIN COMMANDS below).  Non-interactive shells do not perform history expansion
by default.


History expansions introduce words from the history list into
the input stream, making it easy to repeat commands, insert the
arguments to a previous command into the current input line, or
fix errors in previous commands quickly.


History expansion is performed immediately after a complete line
is read, before the shell breaks it into words.
It takes place in two parts.
The first is to determine which line from the history list
to use during substitution.
The second is to select portions of that line for inclusion into
the current one.
The line selected from the history is the event,
and the portions of that line that are acted upon are words.
Various modifiers are available to manipulate the selected words.
The line is broken into words in the same fashion as when reading input,
so that several metacharacter-separated words surrounded by
quotes are considered one word.
History expansions are introduced by the appearance of the
history expansion character, which is ! by default.
Only backslash (\) and single quotes can quote
the history expansion character.


Several characters inhibit history expansion if found immediately
following the history expansion character, even if it is unquoted:
space, tab, newline, carriage return, and =.
If the extglob shell option is enabled, ( will also
inhibit expansion.


Several shell options settable with the
shopt builtin may be used to tailor the behavior of history expansion.
If the
histverify shell option is enabled (see the description of the
shopt builtin), and
readline is being used, history substitutions are not immediately passed to
the shell parser.
Instead, the expanded line is reloaded into the
readline editing buffer for further modification.
If
readline is being used, and the
histreedit shell option is enabled, a failed history substitution will be reloaded
into the
readline editing buffer for correction.
The
-p option to the
history builtin command may be used to see what a history expansion will
do before using it.
The
-s option to the
history builtin may be used to add commands to the end of the history list
without actually executing them, so that they are available for
subsequent recall.


The shell allows control of the various characters used by the
history expansion mechanism (see the description of
histchars above under
Shell Variables). 

An event designator is a reference to a command line entry in the
history list.




Word designators are used to select desired words from the event.
A
: separates the event specification from the word designator.
It may be omitted if the word designator begins with a
^, $, *, -, or
%. Words are numbered from the beginning of the line,
with the first word being denoted by 0 (zero).
Words are inserted into the current line separated by single spaces.




After the optional word designator, there may appear a sequence of
one or more of the following modifiers, each preceded by a ‘:’.






Unless otherwise noted, each builtin command documented in this
section as accepting options preceded by
- accepts
-- to signify the end of the options.
For example, the :, true, false, and test builtins
do not accept options.
Also, please note that while executing in non-interactive mode and while in
posix mode, any special builtin (like ., :, break,
continue, eval, exec, exit, export,
readonly, return, set, shift, source,
times, trap, unset) exiting with a non-zero status
causes the shell to stop execution.




Note aliases are not expanded by default in non-interactive shell, and it can be enabled by setting the
expand_aliases shell option using
shopt. 

The matches will be generated in the same way as if the programmable
completion code had generated them directly from a completion specification
with the same flags.
If word is specified, only those completions matching word
will be displayed.


The return value is true unless an invalid option is supplied, or no
matches were generated.


The process of applying these completion specifications when word completion
is attempted is described above under Programmable Completion.


Other options, if specified, have the following meanings.
The arguments to the -G, -W, and -X options
(and, if necessary, the -P and -S options)
should be quoted to protect them from expansion before the
complete builtin is invoked.


The
-n option suppresses
the command numbers when listing.  The
-r option reverses the order of
the commands.  If the
-l option is given,
the commands are listed on
standard output.  Otherwise, the editor given by
ename is invoked
on a file containing those commands.  If
ename is not given, the
value of the
 FCEDIT variable is used, and
the value of
 EDITOR if
 FCEDIT is not set.  If neither variable is set,
vi
is used.  When editing is complete, the edited commands are
echoed and executed.


In the second form, command is re-executed after each instance
of pat is replaced by rep.
A useful alias to use with this is

r=’fc -s’,
so that typing

r cc
runs the last command beginning with

cc
and typing

r
re-executes the last command.


If the first form is used, the return value is 0 unless an invalid
option is encountered or
first or
last specify history lines out of range.
If the
-e option is supplied, the return value is the value of the last
command executed or failure if an error occurs with the temporary
file of commands.  If the second form is used, the return status
is that of the command re-executed, unless
cmd does not specify a valid history line, in which case
fc returns failure.


When the end of options is encountered, getopts exits with a
return value greater than zero.
OPTIND is set to the index of the first non-option argument,
and name is set to ?.


getopts normally parses the positional parameters, but if more arguments are
given in
args, getopts parses those instead.


getopts can report errors in two ways.  If the first character of
optstring is a colon,
silent error reporting is used.  In normal operation diagnostic messages
are printed when invalid options or missing option arguments are
encountered.
If the variable
 OPTERR is set to 0, no error messages will be displayed, even if the first
character of
optstring is not a colon.


If an invalid option is seen,
getopts places ? into
name and, if not silent,
prints an error message and unsets
 OPTARG. If
getopts is silent,
the option character found is placed in
 OPTARG and no diagnostic message is printed.


If a required argument is not found, and
getopts is not silent,
a question mark (?) is placed in
name,  OPTARG is unset, and a diagnostic message is printed.
If
getopts is silent, then a colon (:) is placed in
name and
 OPTARG is set to the option character found.


getopts returns true if an option, specified or unspecified, is found.
It returns false if the end of options is encountered or an
error occurs.


If the
-x option is supplied,
jobs replaces any
jobspec found in
command or
args with the corresponding process group ID, and executes
command passing it
args, returning its exit status.


The -v option causes the output to be assigned to the variable
var rather than being printed to the standard output.


The format is reused as necessary to consume all of the arguments.
If the format requires more arguments than are supplied, the
extra format specifications behave as if a zero value or null string, as
appropriate, had been supplied.  The return value is zero on success,
non-zero on failure.




The return status when listing options is zero if all optnames
are enabled, non-zero otherwise.  When setting or unsetting options,
the return status is zero unless an optname is not a valid shell
option.


The list of shopt options is:






Expressions may be combined using the following operators, listed
in decreasing order of precedence.





If
bash is started with the name
rbash, or the
-r option is supplied at invocation,
the shell becomes restricted.
A restricted shell is used to
set up an environment more controlled than the standard shell.
It behaves identically to
bash with the exception that the following are disallowed or not performed:



 When a command that is found to be a shell script is executed
(see
 COMMAND EXECUTION above),

rbash turns off any restrictions in the shell spawned to execute the
script.



Chet Ramey, Case Western Reserve University

chet@po.cwru.edu


Once you have determined that a bug actually exists, use the
bashbug command to submit a bug report.
If you have a fix, you are encouraged to mail that as well!
Suggestions and ‘philosophical’ bug reports may be mailed
to bug-bash@gnu.org or posted to the Usenet
newsgroup
gnu.bash.bug. 

ALL bug reports should include:




Comments and bug reports concerning
this manual page should be directed to
chet@po.cwru.edu. 

It’s too big and too slow.


There are some subtle differences between
bash and traditional versions of
sh, mostly because of the
 POSIX specification.


Aliases are confusing in some uses.


Shell builtin commands and functions are not stoppable/restartable.


Compound commands and command sequences of the form ‘a ; b ; c’
are not handled gracefully when process suspension is attempted.
When a process is stopped, the shell immediately executes the next
command in the sequence.
It suffices to place the sequence of commands between
parentheses to force it into a subshell, which may be stopped as
a unit.


Commands inside of $(...) command substitution are not
parsed until substitution is attempted.  This will delay error
reporting until some time after the command is entered.  For example,
unmatched parentheses, even inside shell comments, will result in
error messages while the construct is being read.


Array variables may not (yet) be exported.


When breaking out of multiple loops, if the outermost loop
consists of more than one command, the exit status of break and continue
is lost.













Advertisements


    129 Lectures 
     23 hours 

 Eduonix Learning Solutions

    5 Lectures 
     4.5 hours 

 Frahaan Hussain

    35 Lectures 
     2 hours 

 Pradeep D

    41 Lectures 
     2.5 hours 

 Musab Zayadneh

    46 Lectures 
     4 hours 

 GUHARAJANM

    6 Lectures 
     4 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page