Go to the first, previous, next, last section, table of contents.


there exists a Sept 06 version at http://www.gnu.org/software/bash/manual/bashref.html.gz

Basic Shell Features

Shell Operation

  1. Reads its input from
    1. a file,
    2. a string supplied as an argument to the -c invocation option, or
    3. the user's terminal.
  2. Breaks the input into words and operators.
    Tokens are separated by metacharacters. (after alias expansion ).
  3. Parses the tokens into simple and compound commands.
  4. Performs the various shell expansions ( brace, tilde, parameter and variable, command substitution, arithmetic, word splitting and filename ), breaking the expanded tokens into lists of filenames, commands and arguments.
  5. Performs redirections of input/output units (and removes the redirection operators and their operands from the argument list).
  6. Executes the command .
  7. Waits for the command to complete (unless asynchronous execution is reqeusted) and collects its exit status .

Quoting

Quoting can be used to disable special treatment of certain characters, to prevent reserved words from being recognized, or to prevent parameter expansion.

Escape Character

A backslash ( \ ) is the escape character.

apostrophe

Enclosing characters in ' preserves the literal values.
  > echo '$?' is $?
   $? is 0

For example: to have grep command locate lines containing the three characters (@) use:
   > grep '(@)' filename
An apostrophe may not occur between apostrophes, even when preceded by a \.
       > grep 'don\'t' file will wait for closing apost.

The ` character encloses a command and is not considered a quoting character.

Double Quotes

Enclosing characters in " preserves the literal value, with the exception of $ , `, and \ .
$ and ` retain special meaning within double quotes .
The backslash retains its special meaning only when followed by : $, `, ", \, or newline.
Within ", backslashes that are followed by one of these characters are removed.
Backslashes preceding characters without a special meaning are left unmodified.
A " may be quoted within "s by preceding it with a backslash.

For example: to have grep locate lines containing use "TITLE" when use:
grep "use \"TITLE\" when" filename

* and @ have special meaning within quotes .

ANSI-C Quoting

A word of the form $'string' expands to string,
with backslash-escaped characters replaced with
\b backspace x'08'
\\ backslash
\n newline x'0A'
\r carriage return x'0D'
\t horizontal tab x'09'
\f form feed x'0C'
\v vertical tab x'0B'
\e ESCape character x'1B' frequently used to "lead-in" for a terminal specific function (not ANSI C)
\a alert (bell) x'07'
\' single quote
\ooo the eight-bit character whose value is the octal value ooo
\xXX  the eight-bit character whose value is the hexadecimal value XX  
\cca control-c character

A new-line character is \n or \013 or \x0A or \cJ (i.e. ctrl-J )

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

example:
echo $'\a12\bAB'
1AB

beep is sounded, 12 is displayed, a backspace positions at the 2
then the A is placed over the 2, obscuring the 2, then a B is displayed, resulting in 1AB.

An alternate method is to prevent the shell from processing the \ by escaping it with another \
( i.e. echo \\a12\\bAB ).

echo $'\a' Sounds the alert tone.

Locale-Specific Translation

A double-quoted string preceded by $ 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.

example: echo $LOCALE QQ(_) eh wot?

Comments

# causes remaining characters on that line to be ignored.
In a non-interactive shell
( or an interactive shell in which the interactive_comments option to the shopt builtin is enabled),
.

Commands

Simple Commands

A sequence of words separated by blanks, terminated by a control operator.
The first word generally specifies a command to be executed.
For example to list the files in the current directory in long format:
ls -l
produces the output:
total 88
-rwxr-xr-x    1 realger1 realger1    11747 Nov 14 19:47 a.out
-rw-r--r--    1 realger1 realger1      211 Nov 14 19:24 buff.c
-rw-r--r--    1 realger1 realger1      591 Nov 14 19:52 buff.s
-rw-r--r--    1 realger1 realger1        0 Oct 11 17:49 lx
drwx------    2 realger1 realger1     4096 Oct 30 01:42 logs
-rw-r--r--    1 realger1 realger1        0 Oct 13 15:49 lynx.cfg
lrwxrwxrwx    1 root     root           11 Dec 19  2004 www -> public_html

Commands may be on a single line seperated by ; or on seperate lines.

Pipelines

A sequence of simple commands separated by |. Pipelines are one of the most power features of unix shells.
The output of one command is directly input to the next command.
For example to cut the type, mod bit display, links, owner and group columns from the ls -l use:
ls -l | cut -c35-
produces the output:
 11747 Nov 14 19:47 a.out
     211 Nov 14 19:24 buff.c
     591 Nov 14 19:52 buff.s
       0 Oct 11 17:49 lx
    4096 Oct 30 01:42 logs
       0 Oct 13 15:49 lynx.cfg
      11 Dec 19  2004 www -> public_html

The shell waits for each of the commands in the pipeline to complete,
unless the pipeline is to be executed asynchronously ,

Each command in a pipeline is executed in its own subshell .
The exit status of a pipeline is the exit status of the last command in the pipeline.
If ! precedes the pipeline, the exit status is the negation of the exit status of the last command.


Lists of Commands

A list is a sequence of one or more pipelines separated by one of the operators
    ;     &     &&     ||
terminated by
    ;     & or a newline.
Of these list operators && and || have equal precedence,
followed by ; and & which have equal precedence.

 ;
Commands separated by a ; are executed sequentially; the shell waits for each command to terminate.
This is the same as having commands on seperate lines, i.e. terminated by a newline.
The return status is the exit status of the last command executed.

 &

When a command is terminated with & , the shell executes the command asynchronously in a subshell.
This is known as executing the command in the background.
The shell does not wait for the command to finish
The return status is 0 .
The standard input for asynchronous commands is /dev/null in the absence of any explicit redirections.

 && AND lists
 || OR lists.

An AND list has the form: command1 && command2
command2 is executed if, and only if, command1 returns an exit status of zero.

try_to_do_stuff && do_more_stuff_since_it_is_going_well

An OR list has the form: command1 || command2
command2 is executed if, and only if, command1 returns a non-zero exit status.

try_to_do_stuff || clean_up_mess_from_failured_stuff

The return status of AND lists and OR lists is the exit status of the last command executed in the list.

Compound Commands

The string compare == and != operators treat the string on the right of the operator as a pattern and matched according to the Pattern Matching rules.
If the option nocasematch is enabled, the match is performed without regard to the case of alphabetic characters.
The return value is 0 when the compare is true.
Any part of the pattern may be quoted to force it to be matched as a string. as -f must be unquoted to be recognized as primaries.

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.

The match operator, =~ 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 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 BASH_REMATCH[0] is the portion of the string matching the entire regular expression.
The BASH_REMATCH[n] is the portion of the string matching the nth parenthesized subexpression.

=~ has same precedence as == and !=.

Expressions may be combined using the following operators (in decreasing order of precedence):
( expression ) Returns the value of expression. Used to override the normal precedence of operators that make up expression.
! expression True if expression is false.
expression1 && expression2 True if both expression1 and expression2 are true.
expression1 || expression2 True if either expression1 or expression2 is true.

The && and || operators do not evaluate expression2 if the value of expression1 is sufficient to determine the return value of the entire conditional expression.

Looping Constructs

for

for name [ in words ] ; do command-list ; done
If in words is omitted, for executes command-list once for each positional
parameter that is set.
The exit status is the exit status of the last command that executes.
If the expansion of words is an empty list, no commands are executed, and the return status is 0!
for ODDNUM in 1 3 5 7 ; do echo $ODDNUM ;done

alternate format:
for (( expr-init ; expr-test ; expr-incr )) ; do command-list ; done

results not 0 results 0
  • command-list is executed
  • processing continues with
    the command after the done.
  • expr-incr is evaluated and
    processing continues with the expr-test
  • A 1 is used if an expr is ommited.
    The return value is the exit status of the last command in list that is executed, or false if any of the expressions is invalid.

    until

    while

    until test-commands; do commands; done
    
    while test-commands
     do 
    commands
    …
    done
    
    As long as test-commands has an exit status which is
    not zero zero
    execute commands
    The return status is the exit status of the last command executed in commands;

    case

    case word in [ [(] pattern1  [… | patternn] ) command-list ;;] esac

    selectively execute the command-list corresponding to the first pattern that matches word.
    The | is used to separate multiple patterns, and the ) operator terminates a pattern list.
    A list of patterns and an associated command-list is known as a clause.
    Each clause must be terminated with ;;.
    word undergoes tilde expansion, parameter expansion, command substitution, arithmetic expansion, and
    quote removal before matching is attempted.
    pattern undergoes tilde expansion, parameter expansion, command substitution, and arithmetic expansion.
    There may be an arbitrary number of case clauses, each terminated by a ;;.
    The first pattern that matches determines the command-list that is executed.
    Example:
    The code:
    echo  Enter the name of an animal: 
    read ANIMAL
    echo  The $ANIMAL has 
    case $ANIMAL in
      horse | dog | cat) echo  four ;;
      man   | kangaroo ) echo  two ;;
                      *) echo  an unknown number of;;
    esac
    echo  legs.
    
    running code
     Enter the name of an animal:
    cat
    The cat has
    four
    legs.
    
    The return status is 0 if no pattern is matched.
    Otherwise, the return status is the exit status of the command-list executed. (Which might be zero!)

    if

    simple else - if
    if tests; then
        true-commands;
        [else false-commands;]
    fi
    if tests; then
        true-commands;
      elif more-tests; then
            more-true-commands;
        [else false-commands;]
    fi

    The test list is executed, then upon a return status of

  • zero, the true-command list is executed.
  • non-zero each elif list is executed in turn,
      and if its exit status is zero, the corresponding more-true-commands is executed
    and the command completes.
    If "else false-commands" is present, and the final command in the final if or elif clause has a non-zero exit status,
    then false-commands is executed.
    The return status is the exit status of the last command executed, or zero if no condition tested true.

    n.b. if needs  space before [ and
    [ x
    comparison y ] needs spaces around comparison
    examples:

    
    
        ./myscript.sh
        RC=$?
        if [ $RC -ne 0 ]; then echo myscript failed exit status= $RC ; fi
    
        ./yourscript.sh
        if [ $? -eq 0 ]; then echo yourscript worked, no cleanup needed; exit; fi
    
        if [ $? ]; then echo  always true ; fi (remind me why this is?)
    
    

    if [ -z "$PS1" ]; then echo This shell is not interactive else echo This shell is interactive fi

    The very simple (but not as clear) If first command works, execute second command ./setup.sh && ./process.sh IF first command fails, execute second command ./checkIt || { echo "checkIt failed" ; exit 1; }

    (see Lists of Commands )

    select

    generates menus.

    select name [in words]; do commands; done

    1. The list of words is expanded, generating a list of items.
    2. These items are printed on the standard error output stream, each preceded by a number. If the in words is omitted, the positional parameters are printed, as if in "$@" had been specifed.
    3. The PS3 prompt is then displayed and a line is read from the standard input.
    4. If the line consists of a number corresponding to one of the displayed words, then the value of name is set to that word. If the line is empty, the words and prompt are displayed again.
    5. Other values causes name to be set to null.
    6. If EOF is read, the select command completes. The line read is saved in the variable REPLY.
    7. The commands are executed after each selection until a break or return command is executed, at which point the select command completes.


    (( arithmetic_expression ))

    is evaluated according to the rules of Shell Arithmetic .
    If the value of the expression is non-zero, the return status is 0

    This is equivalent to

    let "expression"

    [[ conditional_expression ]]

    returns a status of 0 or 1 .
    Expressions are composed of the primaries described in section Conditional Expressions.
    Word splitting and filename expansion are not performed on the words between the [[ and ]];
    tilde, parameter and variable expansion, arithmetic expansion, command substitution, process substitution, and quote removal are performed.

    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 in section Pattern Matching. The return value is 0 if the string matches or does not match the pattern, respectively, and 1 otherwise. Any part of the pattern may be quoted to force it to be matched as a string. Expressions may be combined using the following operators, listed in decreasing order of precedence:

    ( expression )
    Returns the value of expression. This may be used to override the normal precedence of operators.
    ! expression
    True if expression is false.
    expression1 && expression2
    True if both expression1 and expression2 are true.
    expression1 || expression2
    True if either expression1 or expression2 is true.
    The && and || commands do not execute expression2 if the value of expression1 is sufficient to determine the return value of the entire conditional expression.

    Grouping Commands

    When a list of commands to be executed as a unit, grouped, redirections may be applied to the entire command list.
    (  list  )
    
    Parentheses cause the commands to be executed in a new subshell.
    Variable assignments do not remain in effect after the subshell completes.
    {  list  ;  }
    
    Curly braces cause the list to be executed in the current shell context.
    The semicolon is required.
    Braces are reserved words and must be separated from the list by blanks.

    The exit status of a group is the exit status of list .

    Functions

    A way to group commands for later execution using a single name executed like a command.
    Shell functions are executed in the current shell context; no new process is created to interpret them.

    Functions are declared using :
    [ function ] func () { command-list; }

    This defines a shell function named func.
    The reserved word function is optional.
    If the function reserved word is supplied, the parentheses are optional.
    The body of the function is the command-list between { and }.
    This list is executed whenever func is specified as the name of a command.
    The exit status of a function is the exit status of the last command executed in the body.

    When a function is executed, the arguments to the function become the positional parameters during its execution.
    The special parameter $#, the number of positional parameters, is updated to reflect the change. Positional parameter $0 is unchanged.

    If the builtin command return is executed in a function, the function completes and execution resumes with the next command after the function call. 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.
    If a numeric argument is given to return, that is the function's return status; otherwise it is the status of the last command executed.

    The status of a simple command is its exit status as provided by the POSIX.1 waitpid function, or 128+n if the command was terminated by signal??(_) n.

    Variables local to the function may be declared with the local builtin. These variables are visible only to the function and the commands it invokes.

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

    Shell Parameters

    A parameter is an entity that stores values. It can be a name, a number, or one of the special characters below. For the shell's purposes, a variable is a parameter denoted by a name.

    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.

    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 . If the variable has its integer attribute set (see declare Builtin Commands), then value is subject to arithmetic expansion even if the $((...)) expansion is not used (see Arithmetic Expansion).
    Word splitting is not performed, with the exception of "$@" .
    Filename expansion is not performed.

    Positional Parameters

    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 parameter N may be referenced as ${N}.
    Positional parameters may not be assigned to with assignment statements.
    The positional parameters are temporarily replaced when a shell function is executed (see Shell Functions).

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


    Special Parameters

    May only be referenced; assignment to them is not allowed.
    $* positional parameters, starting from one. When the expansion occurs within double quotes, it expands to a single word with the value of each parameter separated by the first character of the IFS special variable.
    That is, $* is equivalent to "$1c$2c...", where c is the first character of the value of the IFS variable.
    If IFS is unset, the parameters are separated by spaces.
    If IFS is null, the parameters are joined without intervening separators.
    $@ each parameter expands to a separate word.
    That is, $@ is equivalent to "$1" "$2" ….
    When there are no positional parameters, "$@" and $@ expand to nothing (i.e., they are removed).
    $# number of positional parameters
    $? exit status of the most recently executed foreground pipeline.
    N.B. As an arithmetic item, i.e. use:   if [ $? -gt 0 ]; then ... to test.
    $- current option flags as specified upon invocation, by the set builtin command, or those set by the shell itself (such as the -i option).
    $$ process ID of the shell. In a () subshell, it expands to the process ID of the invoking shell, not the subshell.
    $!process ID of the most recently executed background (asynchronous) command.
    $0 name of the shell or shell script. This is set at shell initialization. If Bash is invoked with a file of commands (see Shell Scripts), $0 is set to the name of that file. If Bash is started with the -c option (see Invoking Bash), then $0 is set to the first argument after the string to be executed, if one is present. Otherwise, it is set to the filename used to invoke Bash, as given by argument zero.
    $_At shell startup, set to the absolute filename of the shell or shell script being executed as passed in the argument list.
    Subsequently, expands to the last argument to the previous command, after expansion. Also set to the full pathname of each command executed and placed in the environment exported to that command.
    When checking mail, this parameter holds the name of the mail file.

    Expansions

    Expansions, substitution and splitting are performed on the command line after it has been split into tokens.

    1. brace expansion
    2. tilde expansion
    3. parameter and variable expansion
    4. command substitution
    5. arithmetic expansion
    6. word splitting
    7. filename expansion

    On some systems process substitution is performed at the same time as parameter, variable, and arithmetic expansion and command substitution.

    brace expansion, word splitting, filename expansion and "$@" can change the number of words of the expansion. Special Parameters and "${name[@]}" (see Arrays).

    After all expansions, Quote Removal is performed.

    Brace Expansion

    A mechanism by which arbitrary strings may be generated.
    Patterns to be brace expanded are in the form [preamble] { string[,…] } [postamble].
    The preamble is prepended to each string contained within the braces, then the postamble is 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,

    echo a{d,c,b}e
    ade ace abe

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

    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}
    expands to:
    mkdir /usr/local/src/bash/old
    mkdir /usr/local/src/bash/new
    mkdir /usr/local/src/bash/dist
    mkdir /usr/local/src/bash/bugs
    

    or

    chown root /usr/{ucb/{ex,edit},lib/{ex?.?*,how_ex}}
    

    When a word begins with a tilde (~), the next characters, up to a /, (or all characters, if there is no / ) are refered to as hdir†  
    ~hdir is replaced with the home directory of the user from (/etc/passwd).

      echo ~mjones  
      /users/mjones
      If the login-name is null, the tilde is replaced with the value of HOME .
      echo ~
      /users/jsmith  

    When the backquote (`) form of substitution is used, backslash(\) retains its literal meaning except for \\, \$ or \`
    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 filename expansion are not performed on the results.

    Arithmetic Expansion

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

    $(( expression ))
    

    expression 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, command substitution, and quote removal. Arithmetic substitutions may be nested.

    The evaluation is performed according to the rules
    If the expression is invalid, Bash displays a message indicating failure to the standard error and no substitution occurs.

    Process Substitution

    Takes the form   <(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.
    >(list) form : writing to the file will provide input for list.
    <(list) form : the file passed as an argument should be read to obtain the output of list.

    Process substitution is performed simultaneously with parameter and variable expansion, command substitution, and arithmetic expansion.

    Word Splitting

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

    Each character of $IFS is a delimiter, and splits the results of the other expansions into words.
    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 '') 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.
    If no expansion occurs, no splitting is performed.

    Filename Expansion (globbing)

    After word splitting, words containing , ?, (, or [ are patterns     (-f supresses this).
    These are replaced with an alphabetically sorted list of matching file names. ( abc* does not mean anything that starts with abc )
    If no matching file names are found the word is left unchanged unless nullglob is disabled, then the word is removed.
    If nocaseglob is enabled, the match is case insenitive.
    The dot ( ., the hidden file prefix) must be matched explicitly, unless dotglob is set. A dot not as a prefix is not treated specially.
    The directory indicators . and .. are always ignored
    The slash ( directory prefix) must always be matched explicitly.

    Filenames that match one of the patterns in GLOBIGNORE are removed from the list of matches.
    Setting GLOBIGNORE implies dotglob, so filenames beginning with a . will match. To get the old behavior of ignoring filenames beginning with a ., make .* one of the patterns in GLOBIGNORE.
    dotglob is disabled when GLOBIGNORE is unset.

    ls u* lists files beginning with lower case u
    ls [uU]*  lists files beginning with lower case u OR upper case U

    Pattern Matching

    Any character in a pattern, other than the special pattern characters , matches itself.
    NULL may not occur in a pattern.
    The special pattern characters must be quoted or escaped if they are to be matched literally.

    The special pattern characters have the following meanings: A ] may be matched by including it as the first character in the set.
      In the default C locale, [a-dx-z] is equivalent to [abcdxyz]. Some locales sort characters in dictionary order, in which case [a-dx-z] might be equivalent to [aBbCcDdxXyYz]. To force the use of the C locale set the LC_COLLATEor LC_ALL environment variable to C.
    * Matches any string, including the null string.
    ? Matches any single character.
    [...] Matches any one of the enclosed characters,
    ex: [Dd][Gg]erman .

    [a-z] denotes a range; any character that sorts between them, inclusive, is matched
    A - may be matched by including it as the first or last character in the set.
    If the first character following the [ is a ! or a ^ then any character not enclosed is matched.
    ex: [!~!@#$%^&*()_+|\=-{}:"';?><,./`,]
    EXCLUDES all non-alphanumeric characters.
    [:class:]character classes are where class is one of the following :
    alpha digit alnum ascii cntrl graph print punct blank space lower upper word xdigit
    A character class matches any character belonging to that class.
    The word character class matches letters, digits, and the character _
      ex: [:alpha:] or [:space:].
    [=c=]equivalence class are matches all characters with the same collation weight (as defined by the current locale) as the character c.

    [.symbol.] matches the collating symbol symbol.

    If extglob is enabled using the shopt builtin, several extended pattern matching operators are recognized.

    In the following description, a pattern-list is a list of one or more patterns separated by a |.
    Composite patterns may be formed using one or more of the following sub-patterns:

    ?(pattern-list) Matches zero or one occurrence of the patterns.
    *(pattern-list) Matches zero or more "
    +(pattern-list) Matches one or more "
    @(pattern-list) Matches exactly one "
    !(pattern-list) Matches anything except one of the patterns.

    Quote Removal

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


    Redirections

    Before a command is executed, its input and output may be redirected .
    The redirection operators, < for input and > for output, may precede, appear within or follow a command and are processed from left to right.
    The filename following the redirection operator is subjected to brace, tilde, parameter, arithmetic and filename expansion, command substitution and quote removal.
    If it expands to more than one word, Bash reports an error.
    Redirection is used to open and close files for the current shell execution environment.
    A failure to open or create a file causes the redirection to fail.
    Since bash processes redirections before invoking the command, sudo will fail if the output is redirected to a file that is not writable to the invoking user.

    Redirecting Input

                        [n]<filename
    Redirection of input causes filename to be opened for reading.
    Default file descriptor number(n) is 0, standard input.

    Redirecting Output

                        [n]>[|]filename
    Redirection of output causes filename to be opened for writing.
    Default file descriptor (n) is 1, standard output.
    If the file does not exist it is created.
    If it exists it is truncated to zero size.
    If the directory the file is to be created in does not exist; the command is not executed and an error indicating the output file does not exist is displayed.
    Redirection using > to an existing regular file with noclobber set will fail .
    Using >| overwrites the file regardless of noclobber.

    Appending Redirected Output

                        [n]>>filename
    If the file does not exist it is created.

    Redirecting both STDOUT and STDERR

                        &>filename

    The order of redirections is significant.

    ls -l > /tmp/stdout+stderr 2>&1

    directs both standard output and standard error to the file

    ls -l 2>&1 > /tmp/stdout directs only the standard output to the file , because the standard error was duplicated as standard output before the standard output was redirected .

    Redirecting to /dev/null should be avoided. Instead use:

    command > /tmp/$$.1 2> /tmp/$$.2
    if [ $? > 0 | -e /tmp/$$.2 ] ; then echo " error \n"; cat /tmp/$$.2

    which will display the STDERR output if there is an error.

    Here Documents

    Read input from the current source until a line containing only word (with no trailing blanks) is read.
    All of the lines read up to that point are then used as the STDIN for a command.
    The format is:
    <<[-]word
    lines of input

    word

    No parameter expansion, command substitution, filename expansion, or arithmetic 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.
    The pair \newline is ignored, and \ must be used to quote the characters \, $, and `.

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

    cat newfile << ++++
        here is an inpuit line
        and another
        ++++

    Duplicating File Descriptors


     [n]<&fdes

    duplicates input file descriptors.
    If n is not specified, the STDIN (file descriptor 0) is used. If fdes expands to one or more digits, the file descriptor (n) becomes a copy of that file descriptor.
    If the digits in fdes do not specify a file descriptor open for input, a redirection error occurs.
    If fdes evaluates to -, file descriptor n is closed.

    [n]>&fdes duplicates output file descriptors.
    If n is not specified, the standard output (file descriptor 1) is used.
    If the digits in fdes do not specify a file descriptor open for output, a redirection error occurs. As a special case, if n is omitted, and fdes does not expand to one or more digits, STDOUT and STDERR are redirected .

    Moving File Descriptors

    The redirection operator

    [n]<&d-

    moves the file descriptor d to file descriptor n, or the standard input if n is not specified.
    d is closed after being duplicated to n.

    [n]&d-

    moves the file descriptor d to file descriptor n, or the standard output ifd is not specified.

    Opening File Descriptors for Reading and Writing

     [n]<>file
    causes file 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.

    Executing Commands

    Simple Command Expansion

    When a simple command is executed, the shell performs the following expansions, assignments, and redirections, from left to right.

    1. The words that the parser has marked as variable assignments (those preceding the command name) and redirections are saved for later processing.
    2. The words that are not variable assignments or redirections are expanded (see Shell Expansions). If any words remain after expansion, the first word is taken to be the name of the command and the remaining words are the arguments.
    3. Redirections are performed as described above (see Redirections).
    4. The text after the = in each variable assignment undergoes tilde expansion, parameter expansion, command substitution, arithmetic expansion, and quote removal before being assigned to the variable.

    If no command name results, the variable assignments affect the current shell environment. Otherwise, the variables are added to the environment of the executed command and do not affect the current shell environment. If any of the assignments attempts to assign a value to a readonly variable, an error occurs, and the command exits with a non-zero status.

    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.

    Command Search and Execution

    After a command has been split into words, if it results in a simple command and an optional list of arguments, the following actions are taken.

    1. 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 section Shell Functions.
    2. 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.
    3. If the name is neither a shell function nor a builtin, and contains no slashes, Bash searches each element of $PATH for a directory containing an executable file by that name. Bash uses a hash table to remember the full pathnames of executable files to avoid multiple PATH searches (see the description of hash in section Bourne Shell Builtins). 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.
    4. 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 supplied, if any.
    5. 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 and the shell executes it as described in section Shell Scripts.
    6. If the command was not begun asynchronously, the shell waits for the command to complete and collects its exit status.

    Command Execution Environment

    The shell has an execution environment, which consists of the following:

    When a simple command other than a builtin or shell function is to be executed, it is invoked in a separate execution environment that consists of the following. Unless otherwise noted, the values are inherited from the shell.

    A command invoked in this separate environment cannot affect the shell's execution environment.

    Command substitution 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.

    Environment

    When a program is invoked, an array of strings ( NAME=value pairs), the environment, is made available.

    On invocation, the shell marks each parameter export to child processes.
    Executed commands inherit the environment. unset, export and declare add/delete parameters and functions to/from the environment.

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

    With -k (The Set Builtin), 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 path name of the command and is included in the environment.

    Exit Status

    A command which exits with a zero exit status has succeeded.
    A non-zero exit status indicates failure.
    This seemingly counter-intuitive scheme is used so there is
  • one well-defined way to indicate success and
  • a variety of ways to indicate various failure modes.
    When a command terminates on a fatal signal whose number is n,
    Bash uses the value 128+n as the exit status.
    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.

    The exit status is used by the Conditional Constructs and some of the list constructs .

    All builtins return an exit status of 2 to indicate incorrect usage.

    Signals

    SIGQUIT ignored.
    SIGTERM ignored when Bash is interactive, in the absence of any traps,
    kill TERM p does not terminate an interactive shell
    SIGINTcaught and handled (so that wait is interruptible) and
    causes bash to breaks out of any executing loops.
    Ignored by asynchronous commands
    SIGTTIN,
    SIGTTOU, and
    SIGTSTP
    If Job Control is in effect, are ignored
    Commands run as a result of command substitution ignore these keyboard-generated job control signals
    SIGHUP Causes the shell to exit by default. Before exiting, all job are sent SIGHUP . Stopped jobs are first sent SIGCONT to ensure that they receive the SIGHUP.
    To prevent the shell from sending the SIGHUP signal to a particular job, it should be removed from the jobs table with disown (see Job Control) or marked to not receive SIGHUP using disown -h.

    If huponexit is set bash sends SIGHUP to all jobs when an interactive login shell exits.

    If BASH receives a signal, for which a trap has been set, while waiting for a command to complete, the trap will not be executed until the command completes.
    If waiting for an asynchronus command an exit status greater than 128 is set, then trap is executed.

    Commands started by Bash have signal handlers set to the values inherited by the shell from its parent.

    Shell Scripts

    A file containing shell commands.
    Bash reads and executes commands from the file, then exits.
    This mode of operation creates a non-interactive shell.
    used as the option argument when invoking Bash, and neither -c nor -s is supplied (see Invoking Bash).

    The special parameter $0 is set to the name of the file (rather than the name of the shell), and the positional parameters are set to the remaining arguments.

    When Bash finds such a file in the $PATH for a command, it spawns a subshell to execute it. In other words, executing

    filename arguments
    is equivalent to executing
    bash filename arguments

    This subshell initializes itself, so that the effect is as if a new shell had been invoked to interpret the script, with the exception that the locations of commands remembered by the parent (see the description of hash in Bourne Shell Builtins) are retained by the child.

    If the first line of a script begins with #!, the remainder of the line specifies an interpreter for the the script, followed by the arguments.
    A shell script must executable (see chmod +x )