Shell 内建命令--Shell Builtin Commands

夹谷和裕
2023-12-01

shell中的内建命令, 函数和外部命令

Shell识别三种基本命令:内建命令、Shell函数以及外部命令:
(1)内建命令就是由Shell本身所执行的命令。
   有些命令是由于其必要性才内建的,例如cd用来改变目录,read会将来自用户(和文件)的输入数据传给Shell外亮。
   另一种内建命令的存在则是为了效率,其中最典型的就是test命令,编写脚本时经常会用到它。另外还有I/O命令,例如echo于printf.
(2)Shell函数是功能健全的一系列程序代码,以Shell语言写成,它们可以像命令那样引用。
(3)外部命令就是由Shell副本(新的进程)所执行的命令,基本的过程如下:
   a. 建立一个新的进程。此进程即为Shell的一个副本。
   b. 在新的进程里,在PATH变量内所列出的目录中,寻找特定的命令。
      /bin:/usr/bin:/usr/X11R6/bin:/usr/local/bin为PATH变量典型的默认值。
      当命令名称包含有斜杠(/)符号时,将略过路径查找步骤。
   c. 在新的进程里,以所找到的新程序取代执行中的Shell程序并执行。
   d. 程序完成后,最初的Shell会接着从终端读取下一条命令,和执行脚本里的下一条命令。

使用type可以查看是否是内建命令:
  type (不带参数)会显示命令是内建命令还是外部命令
       -t :file 外部命令;alias 命令别名;builtin 内置命令
       -a :会将命令PATH路径显示出来
如何执行交互式命令:
用户在命令行输入命令后,一般情况下Shell会fork并exec该命令,但是Shell的内建命令例外,执行内建命令相当于调用Shell进程中的一个函数,并不创建新的进程.
比如:cd、alias、umask、exit等命令即是内建命令,凡是用which命令查不到程序文件所在位置的命令都是内建命令,内建命令没有单独的man手册,要在man手册中查看内建命令,应该man bash-builtins,内建命令虽然不创建新的进程,但也会有Exit Status,通常也用0表示成功非零表示失败,虽然内建命令不创建新的进程,但执行结束后也会有一个状态码,也可以用特殊变量$?读出


4 Shell Builtin Commands

Builtin commands are contained within the shell itself.When the name of a builtin command is used as the first word of a simple command (see Simple Commands), the shell executes the command directly, without invoking another program. Builtin commands are necessary to implement functionality impossible or inconvenient to obtain with separate utilities.

This section briefly describes the builtins which Bash inherits from the Bourne Shell, as well as the builtin commands which are unique to or have been extended in Bash.

Several builtin commands are described in other chapters: builtin commands which provide the Bash interface to the job control facilities (see Job Control Builtins), the directory stack (seeDirectory Stack Builtins), the command history (see Bash History Builtins), and the programmable completion facilities (see Programmable Completion Builtins).

Many of the builtins have been extended by POSIX or Bash.

Unless otherwise noted, each builtin command documented as accepting options preceded by ‘-’ accepts ‘--’ to signify the end of the options. The :truefalse, and test builtins do not accept options and do not treat ‘--’ specially. The exitlogoutbreakcontinuelet, and shift builtins accept and process arguments beginning with ‘-’ without requiring ‘--’. Other builtins that accept arguments but are not specified as accepting options interpret arguments beginning with ‘-’ as invalid options and require ‘--’ to prevent this interpretation.


4.1 Bourne Shell Builtins

The following shell builtin commands are inherited from the Bourne Shell. These commands are implemented as specified by the POSIX standard.

(a colon)
: [arguments]

Do nothing beyond expanding arguments and performing redirections. The return status is zero.

(a period)
. filename [arguments]

Read and execute commands from the filename argument in the current shell context. If filename does not contain a slash, the PATH variable is used to find filename. When Bash is not in POSIXmode, the current directory is searched if filename is not found in $PATH. If any arguments are supplied, they become the positional parameters when filename is executed. Otherwise the positional parameters are unchanged. The return status is the exit status of the last command executed, or zero if no commands are executed. If filename is not found, or cannot be read, the return status is non-zero. This builtin is equivalent to source.

break
break [n]

Exit from a forwhileuntil, or select loop. If n is supplied, the nth enclosing loop is exited. n must be greater than or equal to 1. The return status is zero unless n is not greater than or equal to 1.

cd
cd [-L|[-P [-e]]] [directory]

Change the current working directory to directory. If directory is not given, the value of the HOME shell variable is used. If the shell variable CDPATH exists, it is used as a search path. Ifdirectory begins with a slash, CDPATH is not used.

The -P option means to not follow symbolic links; symbolic links are followed by default or with the -L option. If the -e option is supplied with -P and the current working directory cannot be successfully determined after a successful directory change, cd will return an unsuccessful status. If directory is ‘-’, it is equivalent to $OLDPWD.

If a non-empty directory name from CDPATH is used, or if ‘-’ is the first argument, and the directory change is successful, the absolute pathname of the new working directory is written to the standard output.

The return status is zero if the directory is successfully changed, non-zero otherwise.

continue
continue [n]

Resume the next iteration of an enclosing forwhileuntil, or select loop. If n is supplied, the execution of the nth enclosing loop is resumed. n must be greater than or equal to 1. The return status is zero unless n is not greater than or equal to 1.

eval
eval [arguments]

The arguments are concatenated together into a single command, which is then read and executed, and its exit status returned as the exit status of eval. If there are no arguments or only empty arguments, the return status is zero.

exec
exec [-cl] [-a name] [command [arguments]]

If command is supplied, it replaces the shell without creating a new process. If the -l option is supplied, the shell places a dash at the beginning of the zeroth argument passed to command. This is what the login program does. The -c option causes command to be executed with an empty environment. If -a is supplied, the shell passes name as the zeroth argument to command. If nocommand is specified, redirections may be used to affect the current shell environment. If there are no redirection errors, the return status is zero; otherwise the return status is non-zero.

exit
exit [n]

Exit the shell, returning a status of n to the shell’s parent. If n is omitted, the exit status is that of the last command executed. Any trap on EXIT is executed before the shell terminates.

export
export [-fn] [-p] [name[=value]]

Mark each name to be passed to child processes in the environment. If the -f option is supplied, the names refer to shell functions; otherwise the names refer to shell variables. The -noption means to no longer mark each name for export. If no names are supplied, or if the -p option is given, a list of exported names is displayed. The -p option displays output in a form that may be reused as input. If a variable name is followed by =value, the value of the variable is set to value.

The return status is zero unless an invalid option is supplied, one of the names is not a valid shell variable name, or -f is supplied with a name that is not a shell function.

getopts
getopts optstring name [args]

getopts is used by shell scripts to parse positional parameters. optstring contains the option characters to be recognized; if a character is followed by a colon, the option is expected to have an argument, which should be separated from it by white space. The colon (‘:’) and question mark (‘?’) may not be used as option characters. Each time it is invoked, getopts places the next option in the shell variable name, initializing name if it does not exist, and the index of the next argument to be processed into the variable OPTINDOPTIND is initialized to 1 each time the shell or a shell script is invoked. When an option requires an argument, getopts places that argument into the variable OPTARG. The shell does not reset OPTIND automatically; it must be manually reset between multiple calls to getopts within the same shell invocation if a new set of parameters is to be used.

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 argsgetopts 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 OPTARGand no diagnostic message is printed.

If a required argument is not found, and getopts is not silent, a question mark (‘?’) is placed in nameOPTARG 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.

hash
hash [-r] [-p filename] [-dt] [name]

Each time hash is invoked, it remembers the full pathnames of the commands specified as name arguments, so they need not be searched for on subsequent invocations. The commands are found by searching through the directories listed in $PATH. Any previously-remembered pathname is discarded. The -p option inhibits the path search, and filename is used as the location of name. The -roption causes the shell to forget all remembered locations. The -d option causes the shell to forget the remembered location of each name. If the -t option is supplied, the full pathname to which each name corresponds is printed. If multiple name arguments are supplied with -t the name is printed before the hashed full pathname. The -l option causes output to be displayed in a format that may be reused as input. If no arguments are given, or if only -l is supplied, information about remembered commands is printed. The return status is zero unless a name is not found or an invalid option is supplied.

pwd
pwd [-LP]

Print the absolute pathname of the current working directory. If the -P option is supplied, the pathname printed will not contain symbolic links. If the -L option is supplied, the pathname printed may contain symbolic links. The return status is zero unless an error is encountered while determining the name of the current directory or an invalid option is supplied.

readonly
readonly [-aAf] [-p] [name[=value]] …

Mark each name as readonly. The values of these names may not be changed by subsequent assignment. If the -f option is supplied, each name refers to a shell function. The -a option means eachname refers to an indexed array variable; the -A option means each name refers to an associative array variable. If both options are supplied, -A takes precedence. If no name arguments are given, or if the -p option is supplied, a list of all readonly names is printed. The other options may be used to restrict the output to a subset of the set of readonly names. The -p option causes output to be displayed in a format that may be reused as input. If a variable name is followed by =value, the value of the variable is set to value. The return status is zero unless an invalid option is supplied, one of the name arguments is not a valid shell variable or function name, or the -f option is supplied with a name that is not a shell function.

return
return [n]

Cause a shell function to exit with the return value n. If n is not supplied, the return value is the exit status of the last command executed in the function. This may also be used to terminate execution of a script being executed with the . (or source) builtin, returning either n or the exit status of the last command executed within the script as the exit status of the script. Any command associated with the RETURN trap is executed before execution resumes after the function or script. The return status is non-zero if return is used outside a function and not during the execution of a script by . or source.

shift
shift [n]

Shift the positional parameters to the left by n. The positional parameters from n+1 … $# are renamed to $1 … $#-n. Parameters represented by the numbers $# to $#-n+1 are unset. n must be a non-negative number less than or equal to $#. If n is zero or greater than $#, the positional parameters are not changed. If n is not supplied, it is assumed to be 1. The return status is zero unless n is greater than $# or less than zero, non-zero otherwise.

test [

Evaluate a conditional expression expr. Each operator and operand must be a separate argument. Expressions are composed of the primaries described below in Bash Conditional Expressionstestdoes not accept any options, nor does it accept and ignore an argument of -- as signifying the end of options.

When the [ form is used, the last argument to the command must be a ].

Expressions may be combined using the following operators, listed in decreasing order of precedence. The evaluation depends on the number of arguments; see below. Operator precedence is used when there are five or more arguments.

expr

True if expr is false.

expr )

Returns the value of expr. This may be used to override the normal precedence of operators.

expr1 -a expr2

True if both expr1 and expr2 are true.

expr1 -o expr2

True if either expr1 or expr2 is true.

The test and [ builtins evaluate conditional expressions using a set of rules based on the number of arguments.

0 arguments

The expression is false.

1 argument

The expression is true if and only if the argument is not null.

2 arguments

If the first argument is ‘!’, the expression is true if and only if the second argument is null. If the first argument is one of the unary conditional operators (see Bash Conditional Expressions), the expression is true if the unary test is true. If the first argument is not a valid unary operator, the expression is false.

3 arguments

The following conditions are applied in the order listed. If the second argument is one of the binary conditional operators (see Bash Conditional Expressions), the result of the expression is the result of the binary test using the first and third arguments as operands. The ‘-a’ and ‘-o’ operators are considered binary operators when there are three arguments. If the first argument is ‘!’, the value is the negation of the two-argument test using the second and third arguments. If the first argument is exactly ‘(’ and the third argument is exactly ‘)’, the result is the one-argument test of the second argument. Otherwise, the expression is false.

4 arguments

If the first argument is ‘!’, the result is the negation of the three-argument expression composed of the remaining arguments. Otherwise, the expression is parsed and evaluated according to precedence using the rules listed above.

5 or more arguments

The expression is parsed and evaluated according to precedence using the rules listed above.

When used with test or ‘[’, the ‘<’ and ‘>’ operators sort lexicographically using ASCII ordering.

times
times

Print out the user and system times used by the shell and its children. The return status is zero.

trap
trap [-lp] [arg] [sigspec …]

The commands in arg are to be read and executed when the shell receives signal sigspec. If arg is absent (and there is a single sigspec) or equal to ‘-’, each specified signal’s disposition is reset to the value it had when the shell was started. If arg is the null string, then the signal specified by each sigspec is ignored by the shell and commands it invokes. Ifarg is not present and -p has been supplied, the shell displays the trap commands associated with each sigspec. If no arguments are supplied, or only -p is given, trap prints the list of commands associated with each signal number in a form that may be reused as shell input. The -l option causes the shell to print a list of signal names and their corresponding numbers. Eachsigspec is either a signal name or a signal number. Signal names are case insensitive and the SIG prefix is optional.

If a sigspec is 0 or EXITarg is executed when the shell exits. If a sigspec is DEBUG, the command arg is executed before every simple command, for command, case command, select command, every arithmetic for command, and before the first command executes in a shell function. Refer to the description of the extdebug option to the shopt builtin (see The Shopt Builtin) for details of its effect on the DEBUG trap. If a sigspec is RETURN, the command arg is executed each time a shell function or a script executed with the . or source builtins finishes executing.

If a sigspec is ERR, the command arg is executed whenever a simple command has a non-zero exit status, subject to the following conditions. The ERR trap is not executed if the failed command is part of the command list immediately following an until or while keyword, part of the test following the if or elif reserved words, part of a command executed in a && or || list, or if the command’s return status is being inverted using !. These are the same conditions obeyed by the errexit option.

Signals ignored upon entry to the shell cannot be trapped or reset. Trapped signals that are not being ignored are reset to their original values in a subshell or subshell environment when one is created.

The return status is zero unless a sigspec does not specify a valid signal.

umask
umask [-p] [-S] [mode]

Set the shell process’s file creation mask to mode. If mode begins with a digit, it is interpreted as an octal number; if not, it is interpreted as a symbolic mode mask similar to that accepted by the chmod command. If mode is omitted, the current value of the mask is printed. If the -S option is supplied without a mode argument, the mask is printed in a symbolic format. If the -p option is supplied, and mode is omitted, the output is in a form that may be reused as input. The return status is zero if the mode is successfully changed or if no mode argument is supplied, and non-zero otherwise.

Note that when the mode is interpreted as an octal number, each number of the umask is subtracted from 7. Thus, a umask of 022 results in permissions of 755.

unset
unset [-fv] [name]

Each variable or function name is removed. If no options are supplied, or the -v option is given, each name refers to a shell variable. If the -f option is given, the names refer to shell functions, and the function definition is removed. Readonly variables and functions may not be unset. The return status is zero unless a name is readonly.


4.2 Bash Builtin Commands

This section describes builtin commands which are unique to or have been extended in Bash. Some of these commands are specified in the POSIX standard.

alias
alias [-p] [name[=value] …]

Without arguments or with the -p option, alias prints the list of aliases on the standard output in a form that allows them to be reused as input. If arguments are supplied, an alias is defined for each name whose value is given. If no value is given, the name and value of the alias is printed. Aliases are described in Aliases.

bind
bind [-m keymap] [-lpsvPSV]
bind [-m keymap] [-q function] [-u function] [-r keyseq]
bind [-m keymap] -f filename
bind [-m keymap] -x keyseq:shell-command
bind [-m keymap] keyseq:function-name
bind readline-command

Display current Readline (see Command Line Editing) key and function bindings, bind a key sequence to a Readline function or macro, or set a Readline variable. Each non-option argument is a command as it would appear in a Readline initialization file (see Readline Init File), but each binding or command must be passed as a separate argument; e.g., ‘"\C-x\C-r":re-read-init-file’.

Options, if supplied, have the following meanings:

-m keymap

Use keymap as the keymap to be affected by the subsequent bindings. Acceptable keymap names are emacsemacs-standardemacs-metaemacs-ctlxvivi-movevi-command, and vi-insertvi is equivalent to vi-commandemacs is equivalent to emacs-standard.

-l

List the names of all Readline functions.

-p

Display Readline function names and bindings in such a way that they can be used as input or in a Readline initialization file.

-P

List current Readline function names and bindings.

-v

Display Readline variable names and values in such a way that they can be used as input or in a Readline initialization file.

-V

List current Readline variable names and values.

-s

Display Readline key sequences bound to macros and the strings they output in such a way that they can be used as input or in a Readline initialization file.

-S

Display Readline key sequences bound to macros and the strings they output.

-f filename

Read key bindings from filename.

-q function

Query about which keys invoke the named function.

-u function

Unbind all keys bound to the named function.

-r keyseq

Remove any current binding for keyseq.

-x keyseq:shell-command

Cause shell-command to be executed whenever keyseq is entered. When shell-command is executed, the shell sets the READLINE_LINE variable to the contents of the Readline line buffer and the READLINE_POINT variable to the current location of the insertion point. If the executed command changes the value of READLINE_LINE or READLINE_POINT, those new values will be reflected in the editing state.

The return status is zero unless an invalid option is supplied or an error occurs.

builtin
builtin [shell-builtin [args]]

Run a shell builtin, passing it args, and return its exit status. This is useful when defining a shell function with the same name as a shell builtin, retaining the functionality of the builtin within the function. The return status is non-zero if shell-builtin is not a shell builtin command.

caller
caller [expr]

Returns the context of any active subroutine call (a shell function or a script executed with the . or source builtins).

Without exprcaller displays the line number and source filename of the current subroutine call. If a non-negative integer is supplied as exprcaller displays the line number, subroutine name, and source file corresponding to that position in the current execution call stack. This extra information may be used, for example, to print a stack trace. The current frame is frame 0.

The return value is 0 unless the shell is not executing a subroutine call or expr does not correspond to a valid position in the call stack.

command
command [-pVv] command [arguments …]

Runs command with arguments ignoring any shell function named command. Only shell builtin commands or commands found by searching the PATH are executed. If there is a shell function named ls, running ‘command ls’ within the function will execute the external command ls instead of calling the function recursively. The -p option means to use a default value for PATH that is guaranteed to find all of the standard utilities. The return status in this case is 127 if command cannot be found or an error occurred, and the exit status of command otherwise.

If either the -V or -v option is supplied, a description of command is printed. The -v option causes a single word indicating the command or file name used to invoke command to be displayed; the -V option produces a more verbose description. In this case, the return status is zero if command is found, and non-zero if not.

declare
declare [-aAfFilrtux] [-p] [name[=value] …]

Declare variables and give them attributes. If no names are given, then display the values of variables instead.

The -p option will display the attributes and values of each name. When -p is used with name arguments, additional options are ignored.

When -p is supplied without name arguments, declare will display the attributes and values of all variables having the attributes specified by the additional options. If no other options are supplied with -pdeclare will display the attributes and values of all shell variables. The -f option will restrict the display to shell functions.

The -F option inhibits the display of function definitions; only the function name and attributes are printed. If the extdebug shell option is enabled using shopt (see The Shopt Builtin), the source file name and line number where the function is defined are displayed as well. -F implies -f.

The -g option forces variables to be created or modified at the global scope, even when declare is executed in a shell function. It is ignored in all other cases.

The following options can be used to restrict output to variables with the specified attributes or to give variables attributes:

-a

Each name is an indexed array variable (see Arrays).

-A

Each name is an associative array variable (see Arrays).

-f

Use function names only.

-i

The variable is to be treated as an integer; arithmetic evaluation (see Shell Arithmetic) is performed when the variable is assigned a value.

-l

When the variable is assigned a value, all upper-case characters are converted to lower-case. The upper-case attribute is disabled.

-r

Make names readonly. These names cannot then be assigned values by subsequent assignment statements or unset.

-t

Give each name the trace attribute. Traced functions inherit the DEBUG and RETURN traps from the calling shell. The trace attribute has no special meaning for variables.

-u

When the variable is assigned a value, all lower-case characters are converted to upper-case. The lower-case attribute is disabled.

-x

Mark each name for export to subsequent commands via the environment.

Using ‘+’ instead of ‘-’ turns off the attribute instead, with the exceptions that ‘+a’ may not be used to destroy an array variable and ‘+r’ will not remove the readonly attribute. When used in a function, declare makes each name local, as with the local command, unless the ‘-g’ option is used. If a variable name is followed by =value, the value of the variable is set to value.

The return status is zero unless an invalid option is encountered, an attempt is made to define a function using ‘-f foo=bar’, an attempt is made to assign a value to a readonly variable, an attempt is made to assign a value to an array variable without using the compound assignment syntax (see Arrays), one of the names is not a valid shell variable name, an attempt is made to turn off readonly status for a readonly variable, an attempt is made to turn off array status for an array variable, or an attempt is made to display a non-existent function with -f.

echo
echo [-neE] [arg …]

Output the args, separated by spaces, terminated with a newline. The return status is always 0. If -n is specified, the trailing newline is suppressed. If the -e option is given, interpretation of the following backslash-escaped characters is enabled. The -E option disables the interpretation of these escape characters, even on systems where they are interpreted by default. The xpg_echo shell option may be used to dynamically determine whether or not echo expands these escape characters by default. echo does not interpret -- to mean the end of options.

echo interprets the following escape sequences:

\a

alert (bell)

\b

backspace

\c

suppress further output

\e \E

escape

\f

form feed

\n

new line

\r

carriage return

\t

horizontal tab

\v

vertical tab

\\

backslash

\0nnn

the eight-bit character whose value is the octal value nnn (zero to three octal digits)

\xHH

the eight-bit character whose value is the hexadecimal value HH (one or two hex digits)

\uHHHH

the Unicode (ISO/IEC 10646) character whose value is the hexadecimal value HHHH (one to four hex digits)

\UHHHHHHHH

the Unicode (ISO/IEC 10646) character whose value is the hexadecimal value HHHHHHHH (one to eight hex digits)

enable
enable [-a] [-dnps] [-f filename] [name …]

Enable and disable builtin shell commands. Disabling a builtin allows a disk command which has the same name as a shell builtin to be executed without specifying a full pathname, even though the shell normally searches for builtins before disk commands. If -n is used, the names become disabled. Otherwise names are enabled. For example, to use the test binary found via $PATHinstead of the shell builtin version, type ‘enable -n test’.

If the -p option is supplied, or no name arguments appear, a list of shell builtins is printed. With no other arguments, the list consists of all enabled shell builtins. The -a option means to list each builtin with an indication of whether or not it is enabled.

The -f option means to load the new builtin command name from shared object filename, on systems that support dynamic loading. The -d option will delete a builtin loaded with -f.

If there are no options, a list of the shell builtins is displayed. The -s option restricts enable to the POSIX special builtins. If -s is used with -f, the new builtin becomes a special builtin (see Special Builtins).

The return status is zero unless a name is not a shell builtin or there is an error loading a new builtin from a shared object.

help
help [-dms] [pattern]

Display helpful information about builtin commands. If pattern is specified, help gives detailed help on all commands matching pattern, otherwise a list of the builtins is printed.

Options, if supplied, have the following meanings:

-d

Display a short description of each pattern

-m

Display the description of each pattern in a manpage-like format

-s

Display only a short usage synopsis for each pattern

The return status is zero unless no command matches pattern.

let
let expression [expression]

The let builtin allows arithmetic to be performed on shell variables. Each expression is evaluated according to the rules given below in Shell Arithmetic. If the last expression evaluates to 0, let returns 1; otherwise 0 is returned.

local
local [option] name[=value] …

For each argument, a local variable named name is created, and assigned value. The option can be any of the options accepted by declarelocal can only be used within a function; it makes the variable name have a visible scope restricted to that function and its children. The return status is zero unless local is used outside a function, an invalid name is supplied, or name is a readonly variable.

logout
logout [n]

Exit a login shell, returning a status of n to the shell’s parent.

mapfile
mapfile [-n count] [-O origin] [-s count] [-t] [-u fd] [
-C callback] [-c quantum] [array]

Read lines from the standard input into the indexed array variable array, or from file descriptor fd if the -u option is supplied. The variable MAPFILE is the default array. Options, if supplied, have the following meanings:

-n

Copy at most count lines. If count is 0, all lines are copied.

-O

Begin assigning to array at index origin. The default index is 0.

-s

Discard the first count lines read.

-t

Remove a trailing newline from each line read.

-u

Read lines from file descriptor fd instead of the standard input.

-C

Evaluate callback each time quantumP lines are read. The -c option specifies quantum.

-c

Specify the number of lines read between each call to callback.

If -C is specified without -c, the default quantum is 5000. When callback is evaluated, it is supplied the index of the next array element to be assigned and the line to be assigned to that element as additional arguments. callback is evaluated after the line is read but before the array element is assigned.

If not supplied with an explicit origin, mapfile will clear array before assigning to it.

mapfile returns successfully unless an invalid option or option argument is supplied, array is invalid or unassignable, or array is not an indexed array.

printf
printf [-v var] format [arguments]

Write the formatted arguments to the standard output under the control of the format. The -v option causes the output to be assigned to the variable var rather than being printed to the standard output.

The format is a character string which contains three types of objects: plain characters, which are simply copied to standard output, character escape sequences, which are converted and copied to the standard output, and format specifications, each of which causes printing of the next successive argument. In addition to the standard printf(1) formats, printf interprets the following extensions:

%b

causes printf to expand backslash escape sequences in the corresponding argument, (except that ‘\c’ terminates output, backslashes in ‘\'’, ‘\"’, and ‘\?’ are not removed, and octal escapes beginning with ‘\0’ may contain up to four digits).

%q

causes printf to output the corresponding argument in a format that can be reused as shell input.

%(datefmt)T

causes printf to output the date-time string resulting from using datefmt as a format string for strftime(3). The corresponding argument is an integer representing the number of seconds since the epoch. Two special argument values may be used: -1 represents the current time, and -2 represents the time the shell was invoked.

Arguments to non-string format specifiers are treated as C language constants, except that a leading plus or minus sign is allowed, and if the leading character is a single or double quote, the value is the ASCII value of the following character.

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.

read
read [-ers] [-a aname] [-d delim] [-i text] [-n nchars] [-N nchars] [-p prompt] [-t timeout] [-u fd] [name …]

One line is read from the standard input, or from the file descriptor fd supplied as an argument to the -u option, and the first word is assigned to the first name, the second word to the second name, and so on, with leftover words and their intervening separators assigned to the last name. If there are fewer words read from the input stream than names, the remaining names are assigned empty values. The characters in the value of the IFS variable are used to split the line into words. The backslash character ‘\’ may be used to remove any special meaning for the next character read and for line continuation. If no names are supplied, the line read is assigned to the variable REPLY. The return code is zero, unless end-of-file is encountered, read times out (in which case the return code is greater than 128), or an invalid file descriptor is supplied as the argument to -u.

Options, if supplied, have the following meanings:

-a aname

The words are assigned to sequential indices of the array variable aname, starting at 0. All elements are removed from aname before the assignment. Other name arguments are ignored.

-d delim

The first character of delim is used to terminate the input line, rather than newline.

-e

Readline (see Command Line Editing) is used to obtain the line. Readline uses the current (or default, if line editing was not previously active) editing settings.

-i text

If Readline is being used to read the line, text is placed into the editing buffer before editing begins.

-n nchars

read returns after reading nchars characters rather than waiting for a complete line of input, but honor a delimiter if fewer than nchars characters are read before the delimiter.

-N nchars

read returns after reading exactly nchars characters rather than waiting for a complete line of input, unless EOF is encountered or read times out. Delimiter characters encountered in the input are not treated specially and do not cause read to return until nchars characters are read.

-p prompt

Display prompt, without a trailing newline, before attempting to read any input. The prompt is displayed only if input is coming from a terminal.

-r

If this option is given, backslash does not act as an escape character. The backslash is considered to be part of the line. In particular, a backslash-newline pair may not be used as a line continuation.

-s

Silent mode. If input is coming from a terminal, characters are not echoed.

-t timeout

Cause read to time out and return failure if a complete line of input is not read within timeout seconds. timeout may be a decimal number with a fractional portion following the decimal point. This option is only effective if read is reading input from a terminal, pipe, or other special file; it has no effect when reading from regular files. If timeout is 0, read returns success if input is available on the specified file descriptor, failure otherwise. The exit status is greater than 128 if the timeout is exceeded.

-u fd

Read input from file descriptor fd.

readarray
readarray [-n count] [-O origin] [-s count] [-t] [-u fd] [
-C callback] [-c quantum] [array]

Read lines from the standard input into the indexed array variable array, or from file descriptor fd if the -u option is supplied.

A synonym for mapfile.

source
source filename

A synonym for . (see Bourne Shell Builtins).

type
type [-afptP] [name …]

For each name, indicate how it would be interpreted if used as a command name.

If the -t option is used, type prints a single word which is one of ‘alias’, ‘function’, ‘builtin’, ‘file’ or ‘keyword’, if name is an alias, shell function, shell builtin, disk file, or shell reserved word, respectively. If the name is not found, then nothing is printed, and type returns a failure status.

If the -p option is used, type either returns the name of the disk file that would be executed, or nothing if -t would not return ‘file’.

The -P option forces a path search for each name, even if -t would not return ‘file’.

If a command is hashed, -p and -P print the hashed value, not necessarily the file that appears first in $PATH.

If the -a option is used, type returns all of the places that contain an executable named file. This includes aliases and functions, if and only if the -p option is not also used.

If the -f option is used, type does not attempt to find shell functions, as with the command builtin.

The return status is zero if all of the names are found, non-zero if any are not found.

typeset
typeset [-afFrxi] [-p] [name[=value] …]

The typeset command is supplied for compatibility with the Korn shell; however, it has been deprecated in favor of the declare builtin command.

ulimit
ulimit [-abcdefilmnpqrstuvxHST] [limit]

ulimit provides control over the resources available to processes started by the shell, on systems that allow such control. If an option is given, it is interpreted as follows:

-S

Change and report the soft limit associated with a resource.

-H

Change and report the hard limit associated with a resource.

-a

All current limits are reported.

-b

The maximum socket buffer size.

-c

The maximum size of core files created.

-d

The maximum size of a process’s data segment.

-e

The maximum scheduling priority ("nice").

-f

The maximum size of files written by the shell and its children.

-i

The maximum number of pending signals.

-l

The maximum size that may be locked into memory.

-m

The maximum resident set size (many systems do not honor this limit).

-n

The maximum number of open file descriptors (most systems do not allow this value to be set).

-p

The pipe buffer size.

-q

The maximum number of bytes in POSIX message queues.

-r

The maximum real-time scheduling priority.

-s

The maximum stack size.

-t

The maximum amount of cpu time in seconds.

-u

The maximum number of processes available to a single user.

-v

The maximum amount of virtual memory available to the shell, and, on some systems, to its children.

-x

The maximum number of file locks.

-T

The maximum number of threads.

If limit is given, it is the new value of the specified resource; the special limit values hardsoft, and unlimited stand for the current hard limit, the current soft limit, and no limit, respectively. A hard limit cannot be increased by a non-root user once it is set; a soft limit may be increased up to the value of the hard limit. Otherwise, the current value of the soft limit for the specified resource is printed, unless the -H option is supplied. When setting new limits, if neither -H nor -S is supplied, both the hard and soft limits are set. If no option is given, then -f is assumed. Values are in 1024-byte increments, except for -t, which is in seconds, -p, which is in units of 512-byte blocks, and -n and -u, which are unscaled values.

The return status is zero unless an invalid option or argument is supplied, or an error occurs while setting a new limit.

unalias
unalias [-a] [name … ]

Remove each name from the list of aliases. If -a is supplied, all aliases are removed. Aliases are described in Aliases.


转自:http://www.gnu.org/software/bash/manual/bashref.html#Shell-Builtin-Commands

 类似资料: