要学习ksh,最好的方法莫过于man ksh,这样才能系统的彻底的了解ksh。以下是我学习ksh的总结:
1. Definitions (请耐心的看懂这一小节,这是其它小节的基础)
1) metacharacter: is one of the following characters:
; & ( ) | < > NEWLINE SPACE TAB
2) blank: is a TAB or a SPACE.
3) indentifier; is a sequence of letters, digits, or underscores starting with a sequence of
letter or underscore. Identifiers are used as names for functions and variables.
4) word: is a sequence of characters separated by on or more non-quoted metacharacters.
5) command: is a sequence of characters in the syntax of the shell language. The shell reads
each command and carries out the desired action either directly or by invoking separate utili
6) special-command: is a command that is carried out by the shell without creating a separate
process. Most special commands can be implemented as separate utilities, except for documented
side effects.
7) simple-command: is a sequence of blank-separated words which may be preceded by a variable
assignment list. (command name)The first word specifies the name of the command to be executed.
Except as specified below, the remaining words are passed as arguments to the invoked command.
The command name is passed as argument 0. (command value)The value of a simple-command is its
exit status if it terminates normally. If it terminates abnormally due to receipt of a signal,
the value is the signal number plus 128. Obviously, normal exit status values 129 to 255 cannot
be distinguished from abnormal exit caused by receiving signal numbers 1 to 127. exit status value
can't greater than 255.
8) pipeline: is a sequence of one or more commands separated by |. The standard output of each
command but the last is connected by pipe to the standard input of the next command. Each command
is run as a separate process; the shell waits for the last command to terminate. The exit status
of a pipeline is the exit status of the last command.
9) list: is a sequence of one or more pipelines separated by ; & && or ||, and optionally terminated
by ; & or |&. Of these five symbols, ; & and |& have equal precedence, which is lower than that of
&& and ||. The symbols && and || also have equal precedence. A semicolon(;) causes sequential
execution of the preceding pipleline; an ampersand(&) causes asynchronous execution of the
preceding pipeline(that is, the shell does not wait for that pipeline to finish). The symbol |&
causes asynchronous execution of the preceding command or pipeline with a two-way with pipe
established to the parent shell. The standard input and output of the spawned command can be
written to and read from by the parent shell using the -p option of the special commands read
and print described in Special Commands. The symbol && (||) causes the list following it to be
executed only if the preceding pipeline returns 0 (or a no-zero) value. An arbitrary number of
new-lines may appear in a list, instead of a semicolon, to delimit a command.
2. Command
A command is either a simple-command or one of the following. Unless stated, the value returned
by a command is that of the last simple-command executed in the command.
10) for indentifier [ in word ... ]; do list ; done
Each time a for command is excuted, indentifier is set to the next word taken from the in word
list. If in word ...is omitted, then the for command executes the do list once for each positional
parameter that is set. Execution ends when there are no more words in the list.
examples:
IFS=,
for i in a,b,c
do
echo $i
done #测试没通过
11) select identifier [ in word ... ] ; do list ; done
A select command prints to standard error (file descriptor 2), the set of words, each output line
preceded by a number. If in word ... is omitted, then the positional parameters are used instead.
The PS3 prompt is printed and a line is read from the standard input. If this line starts with the
number of one of the listed words, then the value of the variable identifier is set to the word
corresponding to this number. If this line is empty the selection list is printed again. Oterwise
the value of the variable identifier is set to NULL. The contents of the line read from standard
input is saved in the shell vairable REPLY. The list is executed for each selection until a break
or EOF is encountered. If the REPLY variable is set to NULL by the execution of list, then the
selection list is printed before displaying the PS3 prompt for the next selection.
12) case word in [ pattern [ | pattern ] ) list ;; ] ... esac
A case command the list associated with the first pattern that matches the word.
13) if list ; then list ; [ elif list; then list; ...] [else list;] fi
The list following if is executed and, if it returns an exit status 0, the list following the
first then is executed. Otherwise, the list following elif is executed and, if its value is 0,
the list following the next then is executed. Failling that, the else list is executed. If no
else list or then list is executed, then the if command returns 0 exit status.
14) while list ; do list ; done
until list ; do list ; done
A while command repeatedly executes the while list and, if the exit status of the last command
in the list is 0, executes the do list; otherwise the loop terminates. If no commands in the do
list are executed, then the while command returns 0 exit status.
until may be used in place of while to negate the loop termination test.
15) (list): Execute list in separate environment.
16) {list}: list is simply executed(none-name funtion). Notice that, unlike the metacharacters ( and
), { and } reserved words and must occur at the beginning of a line or after a ; in order to be
recognized.
17) [[expression]]: Evaluates expression and returns 0 exit status when expression is true.
18) function identifier { list ;}
identifier() { list ;}
Define a function which is referenced by identifier. The body of the function is the list of
commands between { and }.
19) time pipeline: The pipeline is executed and the elapsed time as well as the user and system
time are printed to standard error.
20) The following reserved words are only recognized as the first word of a command and when not
quoted:
! if then else elsif fi case
esac for while until do done { }
function select time [[ ]]
4) Comments
A word beginning with # causes that word and all the following characters up to a new-line to be
ignored.
5) Aliasing
The first word of each command is replaced by the text of an alias if an alias for this word has
been defined. An alias name consists of any number of characters excluding metacharacters, qutoing
characters, file expansion characters, parameter and command substitution characters, and =. The
replacement string can contain any valid shell script including the metacharacters listed above.
Aliasing is performed when scripts are read, not while they are executed. Therefore, for an alias
to take affect, the alias defintion command has to be executed before the command which references
the alias is read.
6) Tilds Substituions
After alias substitution is performed, each word is checked to see if it begins with an unquoted ~.
If it does, then the word up to a / is checked to see if it matched a user name. If a match is found,
the ~ and the matched login name are replaced by the login directory of the matched user. This is
called a tidle substitution. If no match is found, the original text is left unchanged. A ~ by itself
, or in front of a /, is replaced by $HOME. A ~ followed by a + or - is replaced by $PWD and $OLDPWD,
respectively.
In addition, tilde substitution is attempted when the value of a variable assignment begins with a ~.
examples:
cd ~
cd ~root/var
cd ~-
cd ~+
a=~
7) Tilde Expansion
A tilde-prefix consists of an unquoted tilde character at the beginning of a word, followed by all of
the characters preceding the first unquoted slash in the word, or all the characters in the word if
there is no slash. In an assignment, multiple tilde-prefixes can be used: at the beginning of the
word (that is, following the equal sign of the assignment), following any unquoted colon or both. A
tilde-prefix in an assignment is terminated by the first unquoted colon or slash. If none of the
characters in the tilde-prefix are quoted, the charachters in the tilde-prefix following the tilde
are treated as a possible login name from the user database.
PATH=$(printf %s ~appadm/jjx:~root/bin)
for Dir in ~appadm/jjx ~root/bin .
do
PATH=${PATH:+$PATH:}$Dir
done
is eligible for tilbe expansion because tilde follows a colon and none of the relevant charachters is
quoted.
Notice that expressions in operands such as :
make -k numble LIBDIR=~chet/lib
do not qualify as shell variable assignments and tilde expansion is not performed ( unless the command
does so itself, which make does not).
8) Command Substitution
The standard output from a command enclosed in parenthesis preceded by a dollar sign (that is,
$(command)) or a pair of grave accents(``) may be used as part or all of a word. Trailing new-lines are
removed. In the second (archaic) form, the string between the backquotes is processed for special
quoting characters before the command is executed. The command substitution $(cat file) can be replaced
by the equivalent but faster $(<file). Command substitution of most special commands that do not
perform input/output redirection are carried out without creating a separate process.
Command substitution allows the output of a command to be substituted in place of the command name
itself. Command substitution occurs when the command is enclosed as follows:
$(command) or `command`
The shell will expand the command substitution by executing command in a subshell environment and
replacing the command substituion with the standard output of the command, removing sequences of one or
more newline characters before the end of the substitution. Embedded newline characters before the end
of the output will not be removed; however, they may be treated as field delimiters and eliminated
during field splitting.
Within the backquoted style of command substitution, backslash shall retain its literal meaning, except
when followed by:
$ ` /
(dollar-sign, backquote, backslash).
With the $(command) form, all characters following the open parenthesis to the matching closing
parenthesis constitute the command.
If the command substitution consists of a single subshell, such as:
$( (command) )
a portable application must separate the $( and ( into two tokens (that is, separate them with white
space). This is required to avoid any ambiguities with arithmetic expansion.
9) Arithmetic Expansion Substitution
An arithmetic expression enclosed in double parentheses preceded by a dollar sign( $((arithmetic-
expression)) ) is replaced by the value of the arithmetic expression.
The expression is treated as if it were in double-quotes, except that a double-quote inside expression
is not treated specially. The arithmetic expression will be processed according to the rules of the
ISO C with the following exceptions:
Only integer arithmetic is required.
The sizeof() operator and the prefix and postfix ++ and -- operators are not required.
Selection, iteration, and jump statements are not supported.
/usr/bin/ksh adn /usr/bin/rksh treat prefix 0 through 9 as decimal constants. See the examples
bellow:
Command Result in /bin/ksh Result in /usr/xpg4/bin/sh
echo $((019+10)) 29 error
echo $((010+10)) 20 error
[ 10 -le $((011)) ] true false
10) Process Substitution
This feature is available in SunOS that support the /dev/fd directory for naming open files. Each
command argument of the form <(list) or >(list) will run process list asynchronously connected to some
file in /dev/fd. The name of this file will become the argument to the command. If the form with > is
selected, then writing on this file will provide input for list. If < is used, then the file passed as
an argument will contain the output of the list process. For examples:
paste <(cut -f1 file1) <(cut -f3 file2) | tee >(process1) >(process2)
cut 命令会产生输出,这个输出会写入/dv/fd的一个文件,这样两个cut命令会产生两个临时文件,这两个临时文件中做为paste
命令的参数。 tee命令可以用多个文件为做为参数,tee命令会将tee命令的得到的内容复制到这多个文件中去,这多个文件同时又
做为process1和process2的input.
因此一个命令需要另一个命令的输出文件做为参数可以使用command1 <(command2)
一个命令需要另一个命令的输出文件做为输入可以使用command1 >(command2)
Notice that the file, which is passed as an argument to the command, is a unix pipe(2) so programs that
expect to lseek(2) on the file will not work.
11) Parameter Substitution
${paramter}
The value, if any, of paramter will be substituted. The parameter name or symbol can be enclosed in
braces, which are optional except for positional parameters with more than on digit or when parameter
is followed by a character that could be interpreted as part of the name.
If the parameter name or symbol is not enclosed in braces, the expansion will use the longest valid
name whether or not the symbol represented by that name exists.
In addition, a parameter expasion can be modified by using one of the following formats. In each case
that a value of word is needed(based on the state of parameter , as described below), word will be
subjected to tilde expansion, parameter expansion, command substitition and arithmetic expansion. If
word is not needed, it will not be expaned. The } character that delimits the following parameter
expansion modifications is determined as described previously in this section and in dquote. (For
example, ${foo-bar}xyz} would result in the expansion of foo followed by the string xyz} if foo is set,
else the string barxyz}).
${parameter:-word}
Use default values. If paramter is unset or null, the expansion of word will be substituted;
otherwise, the value of parameter will be substituted.
${parameter:+[word]}
Use Alternative Value. If parameter is unset or null, null will be substituted. Otherwise, the
expansion of word will be substituted.
${parameter:=word}
Assign Default Values. If parameter is unset or null, the expansion of word will be assign to
parameter. In all cases, the final value of parameter will be substituted. Only variables, not
positional parameters or specail parameters, can be assigned in this way.
${parameter:?[word]}
Indicate Error if parameter is Null or Unset. If parameter is unset or null, the expansion of
word (or a message indicating it is unset if word is omitted) will be written to standard error
and the shell will exit with a non-zero exit status. Otherwise, the value of parameter will be
substituted. An interactive shell need not exit.
In the parameter expansion shown previously, use of the colon in the format results in a test for a
parameter that is unset or null. Omission of the colon results in a test for a paramter that is only
unset. The following two tables summarize the effect of the colon:
${#parameter}
String Length. The length in characters of the value of parameter. If parameter is * or @, then
all the positionnal parameters, starting with $1, are substituted (separated by a field
separator character).
The following four varieties of parameter expansion provide for substring processing. In each case,
pattern matching notation, rather than regular expression notation, will be used to evaluate the
the patterns. If parameter is * or @, then all the posistional parameters, starting with $1, are
substituted (separated by a field separator charater). Enclosing the full paramter expansion string in
double-quotes will not cause the following four varieties of pattern characters to be quoted, whereas
quoting characters within the braces will have this effect.
${paramter%word}
Remove Smallest Suffix Pattern. The word will be expanded to produce a pattern. The parameter
expansion then will result in paramter, with the smallest portion of the suffix matched by the
pattern deleted.
${paramter%%word}
Remove Largest Suffix Pattern. The word will be expanded to produce a pattern. The parameter
expansion then will result in paramter, with the Largest portion of the suffix matched by the
pattern deleted.
${paramter#word}
Remove Smallest Prefix Pattern. The word will be expanded to produce a pattern. The parameter
expansion then will result in paramter, with the smallest portion of the prefix matched by the
pattern deleted.
${paramter##word}
Remove Largest Prefix Pattern. The word will be expanded to produce a pattern. The parameter
expansion then will result in paramter, with the Largest portion of the Prefix matched by the
pattern deleted.
Examples:
x=file.c
echo ${x%.c}.o
file.o
x=posix/src/std
echo ${x%%/*}
posix
Parameters Set by Shell
The following parameters are automatically set by the shell:
# The number of positional parameters in decimal.
- Flags supplied to the shell on invocation or by the set command. example: set -x; echo $-; isxm
? The decimal value returned by the last executed command.
$ The proccess number of this shell.
_ Initially, the value of _ is an absolute pathname of the shell or script being executed
as passed in the environment. Subsequently it is the value of the last argument of the
previous command. This parameter is not set for commands which are asynchronous. This
parameter is also used to hold the name of the matching MAIL file when checking for mail.
! The Process number of the last background command invoked.
ERRNO The value of errno as set by the most recently failed system call.
LINENO The line number of the current line within the script or function being executed.
OLDPWD The previous working directory set by the cd command.
OPTARG The value of the last option argument processed by the getopts special command.
OPTIND The index of the last option argument processed by the getopts special command.
PPID The process number of the parent of the shell.
PWD The present working directory set by the cd command.
RANDOM Each time this vairable is referenced, a random integer, uniformly distributed between 0
and 32767, is generated. The sequence of random numbers can be initialized by assigning
a numeric valu to RANDOM.
REPLY This variable is set by the select statemnt and by the read special command when no
arguments are supplied.
SECONDS Each time this variable is referenced, the number of seconds since shell invocation is
returned. If this vairable is assigned a value, then the value returned upon reference
will be the value that was assigned plus the number of seconds since the assignment.
Variable Used by Shell
PPID
PS1
PS2
PS3
PS4
SHELL
TMOUT
...
12) Blank Interpretation
After parameter and command substitution, the results of substitutions are scanned for the filed
separator characters(those found in IFS) and split into distinct arguments where such characters
are found. Explicit null arguments ("") or ('') are retained. Implicit null arguments(those
resulting from parameters that have no values) are removed.
13) File Name Generation
Following substitution, each command word is scanned for the characters *, ?, and [ unless the
-f option has been set. If one of these characters appears, the word is regarded as a pattern.
The world is replaced with lexicographically sorted file names that match the pattern. If no
file name is found that matches the pattern, the word is left unchanged. When a pattern is used
for file name generation, the character period (.) at the start of a file name or immediately
following a /, as well as the character / itself, must be matched with explicityly. A file name
beginning with a period will not be matched with a pattern with period inside parentheses. That
is, ls .@(r*) would locate a file named .restore, but ls @(.r*) would not. In other instances of
pattern matching, the / and . are not treated specially.
* Matches any string, including the null string.
? Matches any single character.
[...] Matches any one of the enclosed characters. A pair of characters separated by - matches
any character lexically between the pair, inclusive. If the first character following the
opening "[" is a "!", then any character not enclosed is matched. A - can be included in
the character set by putting it as the fist or last character.
A pattern-list is a list of one or more patterns separated from each other with a |. Composite
patterns can be formed with one or more of the following:
?(pattern-list) Optionally matches any one of the given patterns.
*(pattern-list) Matches zero or more occurrences of the given patterns.
+(pattern-list) Matches one or more occurrences of the given patterns.
@(pattern-list) Matches exactly on of the given patterns.
!(pattern-list) Matches anything, except one of the given patterns.
14) Quoting
Each of the metacharacters listed above(see Definistions) has a special meaning to the shell and causes
termination of a word unless quoted. A character may be quoted (that is, made to stand for itself) by
preceding it with a /. The pair /NEWLINE is removed. All characters enclosed between a pair of single
quote marks are quoted. A single quote can not appear within single quotes. Inside double quote marks,
parameter and command substitution occur and / quotes the characters /, `(backquote), ", and $. The
meaning of $* and $@ identical when not quoted or when used as a paramter assignment value or as a file
name. However, when used as a command argument, "$*" is equivalent to "$1d$2d...", where d is the first
character of the IFS variable, whereas "$@" is equivalent to "$1" "$2".... The special meaning of
reserved words or aliases can be removed by quoting any charachter of the reserved word. The
recognition of function names or sepcial command names listed below cannot be altered by quoting them.
15) Arithmetic Evaluation
An ability to perform integer arithmetic is provided with the special command let. Evaluatiions are
performed using long artihmetic. Constants are of the form [ base# ] n where base is a decimal number
between two and thirty-six representing the arithmetic base and n is a number in that base. If base
is omitted then base 10 is used.
An arithmetic expression uses the same syntax, precedence, and associativity of expression as the C
language. All the integeral operators, other than ++, =; ?: and , are supported. Vairables can be
referenced by name within an arithmetic expression without using the parameter substitution syntax.
When a variable is referenced, its value is evaluated as an arithmetic expression.
Since may of the arithmetic operators require quoting, an alternative form of the let command is
provided. For any command which begins with a ((, all the characters until a matching )) are treated
as a quoted expression. More preciselly, ((...)) is equivalent to let "...".
16) Prompting
When used interactively, the shell prompts with the parameter expanded value of PS1 before reading a
command. If at any time a new-line is typed and further input is needed to complete a command, then
the secondary prompt (that is, the value of PS2) is issued.
17) Conditional Expressions
A conditional expression is used with the [[ compound command to test attributes of files and to
compare strings. Word splitting and file name generation are not performed on the words between [[ and
]]. (?) Each expression can be constructed from one or more of the following unary or binary
expressions:
-a file:
True, if file exists.
-b file:
True, if file exists and is a block special file.
-c file:
True, if file exists and is a character special file.
-d file
True, if file exists and is a directory.
-e file
True, if file exists.
-f file
True, if file exists and is an ordinary file.
-g file
True, if file exists and is has its setgid bit set.
-k file
True, if file exists and is has its sticky bit set.
-n string
True, if length of string is non-zero.
-o option
True, if option named option is on.
-p file
True, if file exists and is a fifo special file or a pipe.
-r file
True, if file exists and is readable by current process.
-s file
True, if file exists and has size greater than zero.
-t fildes
True, if file descriptor number fildes is open and associated with a terminal device.
-u file
True, if file exists and has its setuid bit set.
-w file
True, if file exists and is writable by current process.
-x file
True, is file exists and is executable by current process. if file exists and is a directory,
then the current process has permission to search in the directory.
-z string
True, if length of string is zero.
-L file
True, if file exists and is a symbolic link.
-O file
True, if file exists and is owned by the effective user id of this process.
-G file
True, if file exists and its group matches the effective group id of this process.
-S file
True, if file exists and is a socket.
file1 -nt file2
True, if file1 exists and is newer than file2.
file1 -ot file2
True, if file1 exists and is older then file2.
file1 -ef file2
true, if file1 and file2 exsit and refer to the same file.
string
true, if the string is not the null string.
string = pattern
true, if string matches pattern.
string != pattern
true, if string does not matches pattern.
string1 = string2
true, if string1 and string2 are identical.
string1 != string2
true, if string1 and string2 are not identical.
string < string2
true, if string1 comes before string2 based on strings interpreted as appropriate to the local
setting for category LC_COLLATE.
string > string2
true, if string2 comes after string2....
exp1 -eq exp2
true, if exp1 is equal to exp2.
exp1 -ne exp2
ture, if exp1 is not equal to exp2.
exp1 -lt exp2
true, if exp1 is less than exp2.
exp1 -gt exp2
true, if exp1 is greater than exp2.
exp1 -le exp2
ture, if exp1 is less than or equal to exp2.
exp1 -ge exp2
true, if exp1 is greater than or equal to exp2.
In each of the above expressions, if file is of the form /dev/fd/n, where n is an integer, then the
test is appied to the open file whose descriptor number is n.
A compound expression can be constructed from these primitives by using any of the following, listed in
decreasing order of precedence.
(expression)
True, if expression is true, Used to group expressions.
! expression
True, if expression is false.
expression1 && expression2
True, if expression1 and expression2 are both true.
expression1 || expression2
True, if expression1 or expression2 is true.
18) Input/Output
Before a command is executed, its input and output may be redirected using a special notation
interpreted by the shell. The following may appear anywhere in a simple-command or may precede or
follow a command and are not passed on to the invoked command. Command and parameter substitution
occur before word or digit is used except as noted below. File name generation occurs only if the
pattern matches a single file, and blank interpretation is not performed.
<word
Use file word as standard input (file descriptor 0).
>word
Use file word as standard output (file descriptor 1). If the file does not exist then it is
created. If the file exists, and the noclobber option is on, this causes an error; otherwise,
it is truncated to zero length.
>|word
Sames as >, except that is overrides the noclobber option.
>>word
Use file word as standard output. If the file exists, output is appended to it (by first
seeking to the EOR). Otherwise, the file is created.
<>word
Open file word for reading and writing as standard input.
<< [-]word
The shell input is read up to a line that is the same as word, or to and EOF. No parameter
substitution, command substitution, or file name generation is performed on word. The resulting
document, called a here-document, becomes the standard input. If - is appended to <<, then all
leading tabs are stripped from word and from the document.
<&digit
The standard input is duplicated from file descriptor digit. Similarly for the standard output
using >&digit.
<&-
The standard input is closed. similarly for the standard output using >&-.
<&p The input from the co-process is moved to standard input.
>&p The output to the co-process is moved to standard output.
If one of the above is preceded by a digit, then the file descriptor number refered to is that
specified by the digit (instead of the default 0 or 1). For example:
... 2>&1
means file descriptor 2 is to be opened for writing as duplicate of file descriptor 1.
The order in which redirctions are specified is significant. The shell evaluates each redirection in
terms of the (file descriptor, file) association at the time of evaluation. For example:
... 1>fname 2>&1
first associates file descriptor 1 with file fname. It then associates file descriptor 2 with file
associated with file descriptor 1( that is, fname). If the order of redirections were reversed, file
descriptor 2 would be associated with the terminal and then file descriptor 1 would be assocated with
file fname. So file descirptor just like point in C language, and the duplication of file descriptor
only duplicate the point which point to the given file.
If a command is followed by & and job control is not active, then the default standard input for the
command is the empty file /dev/null. Otherwise, the environment for the execution of a commmand
contains the file descriptors of the invoking shell as modified by input/output specifications.
19) Functions
The function reserved word, described in the commands section above, is used to define shell functions.
Shell functions are read in and stored internally. Alias names are resolved when the function is read.
Functions are executed like commands with the arguments passed as positional parameters.
Functions execute in the same process as the caller and share all files and present working directory
with the caller. Traps caught by the caller are reset to their default action inside the function. A
trap condition that is not caught or ignored by the function causes the function to terminate and the
condition to be passed on to the caller.
A trap on EXIT set inside a function is executed after the function complete in the environment of the
caller.
functions declared as:
function func
func()
Ordinarily, variable are shared between the calling program and the function. However, the typeset
special command used(typeset name=value) within a function defines local variables whose scope
includes the current function and all functions it calls.
The special command return is used to return from function calls. Errors within functions return
control to the caller.
The names of all functions can be listed with typeset +f. typeset -f lists all function names as well
as the text of all functions. typeset -f function-names lists the text of the named function only.
Functions can be undefined with the -f option of the unset special command. (notice that, the command
have to be performed by the format as below: . command. that is, execute command by preceding it with
a dot, that is meaning after reading the complete file, then execute the file).
Ordinarily, functions are unset when the shell executes a shell script. The -xf option of typeset
command allows a function to be exported to scripts that are executed without a separate invocation of
the shell. Functions that need to be defined across separate invocations of the shell should be
specified in the ENV file with the -xf option of typeset.
Function Definition Command
A function is a user-defined name that is used as a simple command to call a compound command with new
postional parameters. A function is defined with a function definition command.
The format of a function definition command is as follows:
fname() compound-command [io-redirect ...]
When the function is declared, none of the expansions in wordexp will be performed on the text in
compound-command or io-redirect; all expansions will be performed as normal each time the function is
called. Similarly, the optional io-redirect redirections and any variable assignments with commpound-
command will be performed during the execution of the function itself, not the function definition.
The compound-command will be executed whenever the function name is specified as the name of a simple
command. The operands to the command temporarily will become the positional parameters during the
execution of the compound-command; the special parameter # will also be changed to reflect the number
of operands. The special parameter 0 will be unchanged. When the function completes, the values of the
positional parameters and the special parameter # will be restored to the values they had before the
function was executed. If the special built-in return is executed in the compound-command, the function
will complete and execution will resume with the next command after the function call.
An example of how a function definition can be used wherever a simple command is allowed:
[ "$i" = yes ] && foo() {
ls -l
}
The exit status of a funciton definition will be 0 if the function was declared successfully; otherwise
it will be greater than zero. The exit status of a function invocation will be the exit status of the
last command executed by the function.
20) Signals
The INT and QUIT signals for an invoked command are ignored if the command is followed by & and the
monitor option is not active. Otherwise, signals have the values inherited by the shell from its parent
21) Execution
Each time a command is executed, the above substitutions are carried out. If the command name matches
on of the Special cmmands listed below, it is executed within the current shell process. Next, the
command name is checked to see if it matches one of the user defined functions. If it does, the
positional parameters are saved and then reset to the arguments of the function call. When the function
completes or issues a return, the positional parameter list is restored and any trap set on EXIT within
the function is executed. The value of a function is the value of the last command executed. A function
is also executed in the current shell process. If a command name is not a special command or a user
defined function, a process is created and an attampt is made to execute the command via exec.
22) Specail Commands
The following simple-commands are executed in the shell process. Input/Output redirection is permitted.
Unless otherwise indicated, the output is written on file descriptor 1 and the exit status, when there
is no syntax error, is 0. Commands that are preceded by one or two * are treated specially in the
following ways: