Bash Builtins (Bash Reference Manual)
Next: Modifying Shell Behavior, Previous: Bourne Shell Builtins, Up: Shell Builtin Commands [Contents][Index]
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.
aliasalias [-p] [name[=value] …]
Without arguments or with the
-poption,aliasprints 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 eachnamewhosevalueis given. If novalueis given, the name and value of the alias is printed. Aliases are described in Aliases.bindbind [-m keymap] [-lpsvPSVX] 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 [-m keymap] keyseq: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 keymapUse
keymapas the keymap to be affected by the subsequent bindings. Acceptablekeymapnames areemacs,emacs-standard,emacs-meta,emacs-ctlx,vi,vi-move,vi-command, andvi-insert.viis equivalent tovi-command(vi-moveis also a synonym);emacsis equivalent toemacs-standard.-lList the names of all Readline functions.
-pDisplay Readline function names and bindings in such a way that they can be used as input or in a Readline initialization file.
-PList current Readline function names and bindings.
-vDisplay Readline variable names and values in such a way that they can be used as input or in a Readline initialization file.
-VList current Readline variable names and values.
-sDisplay 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.
-SDisplay Readline key sequences bound to macros and the strings they output.
-f filenameRead key bindings from
filename.-q functionQuery about which keys invoke the named
function.-u functionUnbind all keys bound to the named
function.-r keyseqRemove any current binding for
keyseq.-x keyseq:shell-commandCause
shell-commandto be executed wheneverkeyseqis entered. Whenshell-commandis executed, the shell sets theREADLINE_LINEvariable to the contents of the Readline line buffer and theREADLINE_POINTandREADLINE_MARKvariables to the current location of the insertion point and the saved insertion point (themark), respectively. If the executed command changes the value of any ofREADLINE_LINE,READLINE_POINT, orREADLINE_MARK, those new values will be reflected in the editing state.-XList all key sequences bound to shell commands and the associated commands in a format that can be reused as input.
The return status is zero unless an invalid option is supplied or an error occurs.
builtinbuiltin [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 ifshell-builtinis not a shell builtin command.callercaller [expr]
Returns the context of any active subroutine call (a shell function or a script executed with the
.orsourcebuiltins).Without
expr,callerdisplays the line number and source filename of the current subroutine call. If a non-negative integer is supplied asexpr,callerdisplays 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
exprdoes not correspond to a valid position in the call stack.commandcommand [-pVv] command [arguments …]
Runs
commandwithargumentsignoring any shell function namedcommand. Only shell builtin commands or commands found by searching thePATHare executed. If there is a shell function namedls, running ‘command ls’ within the function will execute the external commandlsinstead of calling the function recursively. The-poption means to use a default value forPATHthat is guaranteed to find all of the standard utilities. The return status in this case is 127 ifcommandcannot be found or an error occurred, and the exit status ofcommandotherwise.If either the
-Vor-voption is supplied, a description ofcommandis printed. The-voption causes a single word indicating the command or file name used to invokecommandto be displayed; the-Voption produces a more verbose description. In this case, the return status is zero ifcommandis found, and non-zero if not.declaredeclare [-aAfFgiIlnrtux] [-p] [name[=value] …]
Declare variables and give them attributes. If no
names are given, then display the values of variables instead.The
-poption will display the attributes and values of eachname. When-pis used withnamearguments, additional options, other than-fand-F, are ignored.When
-pis supplied withoutnamearguments,declarewill display the attributes and values of all variables having the attributes specified by the additional options. If no other options are supplied with-p,declarewill display the attributes and values of all shell variables. The-foption will restrict the display to shell functions.The
-Foption inhibits the display of function definitions; only the function name and attributes are printed. If theextdebugshell option is enabled usingshopt(see The Shopt Builtin), the source file name and line number where eachnameis defined are displayed as well.-Fimplies-f.The
-goption forces variables to be created or modified at the global scope, even whendeclareis executed in a shell function. It is ignored in all other cases.The
-Ioption causes local variables to inherit the attributes (except thenamerefattribute) and value of any existing variable with the samenameat a surrounding scope. If there is no existing variable, the local variable is initially unset.The following options can be used to restrict output to variables with the specified attributes or to give variables attributes:
-aEach
nameis an indexed array variable (see Arrays).-AEach
nameis an associative array variable (see Arrays).-fUse function names only.
-iThe variable is to be treated as an integer; arithmetic evaluation (see Shell Arithmetic) is performed when the variable is assigned a value.
-lWhen the variable is assigned a value, all upper-case characters are converted to lower-case. The upper-case attribute is disabled.
-nGive each
namethenamerefattribute, making it a name reference to another variable. That other variable is defined by the value ofname. All references, assignments, and attribute modifications toname, except for those using or changing the-nattribute itself, are performed on the variable referenced byname’s value. The nameref attribute cannot be applied to array variables.-rMake
names readonly. These names cannot then be assigned values by subsequent assignment statements or unset.-tGive each
namethetraceattribute. Traced functions inherit theDEBUGandRETURNtraps from the calling shell. The trace attribute has no special meaning for variables.-uWhen the variable is assigned a value, all lower-case characters are converted to upper-case. The lower-case attribute is disabled.
-xMark each
namefor export to subsequent commands via the environment.
Using ‘
+’ instead of ‘-’ turns off the attribute instead, with the exceptions that ‘+a’ and ‘+A’ may not be used to destroy array variables and ‘+r’ will not remove the readonly attribute. When used in a function,declaremakes eachnamelocal, as with thelocalcommand, unless the-goption is used. If a variable name is followed by =value, the value of the variable is set tovalue.When using
-aor-Aand the compound assignment syntax to create array variables, additional attributes do not take effect until subsequent assignments.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 thenamesis 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.echoecho [-neE] [arg …]
Output the
args, separated by spaces, terminated with a newline. The return status is 0 unless a write error occurs. If-nis specified, the trailing newline is suppressed. If the-eoption is given, interpretation of the following backslash-escaped characters is enabled. The-Eoption disables the interpretation of these escape characters, even on systems where they are interpreted by default. Thexpg_echoshell option may be used to dynamically determine whether or notechoexpands these escape characters by default.echodoes not interpret--to mean the end of options.echointerprets the following escape sequences:\aalert (bell)
\bbackspace
\csuppress further output
\e
\Eescape
\fform feed
\nnew line
\rcarriage return
\thorizontal tab
\vvertical tab
\\backslash
\0nnnthe eight-bit character whose value is the octal value
nnn(zero to three octal digits)\xHHthe eight-bit character whose value is the hexadecimal value
HH(one or two hex digits)\uHHHHthe Unicode (ISO/IEC 10646) character whose value is the hexadecimal value
HHHH(one to four hex digits)\UHHHHHHHHthe Unicode (ISO/IEC 10646) character whose value is the hexadecimal value
HHHHHHHH(one to eight hex digits)
enableenable [-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
-nis used, thenames become disabled. Otherwisenames are enabled. For example, to use thetestbinary found via$PATHinstead of the shell builtin version, type ‘enable -n test’.If the
-poption is supplied, or nonamearguments appear, a list of shell builtins is printed. With no other arguments, the list consists of all enabled shell builtins. The-aoption means to list each builtin with an indication of whether or not it is enabled.The
-foption means to load the new builtin commandnamefrom shared objectfilename, on systems that support dynamic loading. The-doption will delete a builtin loaded with-f.If there are no options, a list of the shell builtins is displayed. The
-soption restrictsenableto the POSIX special builtins. If-sis used with-f, the new builtin becomes a special builtin (see Special Builtins).The return status is zero unless a
nameis not a shell builtin or there is an error loading a new builtin from a shared object.helphelp [-dms] [pattern]
Display helpful information about builtin commands. If
patternis specified,helpgives detailed help on all commands matchingpattern, otherwise a list of the builtins is printed.Options, if supplied, have the following meanings:
-dDisplay a short description of each
pattern-mDisplay the description of each
patternin a manpage-like format-sDisplay only a short usage synopsis for each
pattern
The return status is zero unless no command matches
pattern.letlet expression [expression …]
The
letbuiltin allows arithmetic to be performed on shell variables. Eachexpressionis evaluated according to the rules given below in Shell Arithmetic. If the lastexpressionevaluates to 0,letreturns 1; otherwise 0 is returned.locallocal [option] name[=value] …
For each argument, a local variable named
nameis created, and assignedvalue. Theoptioncan be any of the options accepted bydeclare.localcan only be used within a function; it makes the variablenamehave a visible scope restricted to that function and its children. Ifnameis ‘-’, the set of shell options is made local to the function in whichlocalis invoked: shell options changed using thesetbuiltin inside the function are restored to their original values when the function returns. The restore is effected as if a series ofsetcommands were executed to restore the values that were in place before the function. The return status is zero unlesslocalis used outside a function, an invalidnameis supplied, ornameis a readonly variable.logoutlogout [n]
Exit a login shell, returning a status of
nto the shell’s parent.mapfilemapfile [-d delim] [-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 descriptorfdif the-uoption is supplied. The variableMAPFILEis the defaultarray. Options, if supplied, have the following meanings:-dThe first character of
delimis used to terminate each input line, rather than newline. Ifdelimis the empty string,mapfilewill terminate a line when it reads a NUL character.-nCopy at most
countlines. Ifcountis 0, all lines are copied.-OBegin assigning to
arrayat indexorigin. The default index is 0.-sDiscard the first
countlines read.-tRemove a trailing
delim(default newline) from each line read.-uRead lines from file descriptor
fdinstead of the standard input.-CEvaluate
callbackeach timequantumlines are read. The-coption specifiesquantum.-cSpecify the number of lines read between each call to
callback.
If
-Cis specified without-c, the default quantum is 5000. Whencallbackis 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.callbackis evaluated after the line is read but before the array element is assigned.If not supplied with an explicit origin,
mapfilewill cleararraybefore assigning to it.mapfilereturns successfully unless an invalid option or option argument is supplied,arrayis invalid or unassignable, orarrayis not an indexed array.printfprintf [-v var] format [arguments]
Write the formatted
argumentsto the standard output under the control of theformat. The-voption causes the output to be assigned to the variablevarrather than being printed to the standard output.The
formatis 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 successiveargument. In addition to the standardprintf(1)formats,printfinterprets the following extensions:%bCauses
printfto expand backslash escape sequences in the correspondingargumentin the same way asecho -e(see Bash Builtins).%qCauses
printfto output the correspondingargumentin a format that can be reused as shell input.%(datefmt)TCauses
printfto output the date-time string resulting from usingdatefmtas a format string forstrftime(3). The correspondingargumentis 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. If no argument is specified, conversion behaves as if -1 had been given. This is an exception to the usualprintfbehavior.
The %b, %q, and %T directives all use the field width and precision arguments from the format specification and write that many bytes from (or use that wide a field for) the expanded argument, which usually contains more characters than the original.
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
formatis reused as necessary to consume all of thearguments. If theformatrequires moreargumentsthan 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.readread [-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
fdsupplied as an argument to the-uoption, split into words as described above in Word Splitting, and the first word is assigned to the firstname, the second word to the secondname, and so on. If there are more words than names, the remaining words and their intervening delimiters are assigned to the lastname. 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 theIFSvariable are used to split the line into words using the same rules the shell uses for expansion (described above in Word Splitting). The backslash character ‘\’ may be used to remove any special meaning for the next character read and for line continuation.Options, if supplied, have the following meanings:
-a anameThe words are assigned to sequential indices of the array variable
aname, starting at 0. All elements are removed fromanamebefore the assignment. Othernamearguments are ignored.-d delimThe first character of
delimis used to terminate the input line, rather than newline. Ifdelimis the empty string,readwill terminate a line when it reads a NUL character.-eReadline (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, but uses Readline’s default filename completion.
-i textIf Readline is being used to read the line,
textis placed into the editing buffer before editing begins.-n ncharsreadreturns after readingncharscharacters rather than waiting for a complete line of input, but honors a delimiter if fewer thanncharscharacters are read before the delimiter.-N ncharsreadreturns after reading exactlyncharscharacters rather than waiting for a complete line of input, unless EOF is encountered orreadtimes out. Delimiter characters encountered in the input are not treated specially and do not causereadto return untilncharscharacters are read. The result is not split on the characters inIFS; the intent is that the variable is assigned exactly the characters read (with the exception of backslash; see the-roption below).-p promptDisplay
prompt, without a trailing newline, before attempting to read any input. The prompt is displayed only if input is coming from a terminal.-rIf 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 then be used as a line continuation.
-sSilent mode. If input is coming from a terminal, characters are not echoed.
-t timeoutCause
readto time out and return failure if a complete line of input (or a specified number of characters) is not read withintimeoutseconds.timeoutmay be a decimal number with a fractional portion following the decimal point. This option is only effective ifreadis reading input from a terminal, pipe, or other special file; it has no effect when reading from regular files. Ifreadtimes out,readsaves any partial input read into the specified variablename. Iftimeoutis 0,readreturns immediately, without trying to read any data. The exit status is 0 if input is available on the specified file descriptor, non-zero otherwise. The exit status is greater than 128 if the timeout is exceeded.-u fdRead input from file descriptor
fd.
If no
names are supplied, the line read, without the ending delimiter but otherwise unmodified, is assigned to the variableREPLY. The exit status is zero, unless end-of-file is encountered,readtimes out (in which case the status is greater than 128), a variable assignment error (such as assigning to a readonly variable) occurs, or an invalid file descriptor is supplied as the argument to-u.readarrayreadarray [-d delim] [-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 descriptorfdif the-uoption is supplied.A synonym for
mapfile.sourcesource filename
A synonym for
.(see Bourne Shell Builtins).typetype [-afptP] [name …]
For each
name, indicate how it would be interpreted if used as a command name.If the
-toption is used,typeprints a single word which is one of ‘alias’, ‘function’, ‘builtin’, ‘file’ or ‘keyword’, ifnameis an alias, shell function, shell builtin, disk file, or shell reserved word, respectively. If thenameis not found, then nothing is printed, andtypereturns a failure status.If the
-poption is used,typeeither returns the name of the disk file that would be executed, or nothing if-twould not return ‘file’.The
-Poption forces a path search for eachname, even if-twould not return ‘file’.If a command is hashed,
-pand-Pprint the hashed value, which is not necessarily the file that appears first in$PATH.If the
-aoption is used,typereturns all of the places that contain an executable namedfile. This includes aliases and functions, if and only if the-poption is not also used.If the
-foption is used,typedoes not attempt to find shell functions, as with thecommandbuiltin.The return status is zero if all of the
namesare found, non-zero if any are not found.typesettypeset [-afFgrxilnrtux] [-p] [name[=value] …]
The
typesetcommand is supplied for compatibility with the Korn shell. It is a synonym for thedeclarebuiltin command.ulimitulimit [-HS] -a ulimit [-HS] [-bcdefiklmnpqrstuvxPRT] [limit]
ulimitprovides 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:-SChange and report the soft limit associated with a resource.
-HChange and report the hard limit associated with a resource.
-aAll current limits are reported; no limits are set.
-bThe maximum socket buffer size.
-cThe maximum size of core files created.
-dThe maximum size of a process’s data segment.
-eThe maximum scheduling priority ("nice").
-fThe maximum size of files written by the shell and its children.
-iThe maximum number of pending signals.
-kThe maximum number of kqueues that may be allocated.
-lThe maximum size that may be locked into memory.
-mThe maximum resident set size (many systems do not honor this limit).
-nThe maximum number of open file descriptors (most systems do not allow this value to be set).
-pThe pipe buffer size.
-qThe maximum number of bytes in POSIX message queues.
-rThe maximum real-time scheduling priority.
-sThe maximum stack size.
-tThe maximum amount of cpu time in seconds.
-uThe maximum number of processes available to a single user.
-vThe maximum amount of virtual memory available to the shell, and, on some systems, to its children.
-xThe maximum number of file locks.
-PThe maximum number of pseudoterminals.
-RThe maximum time a real-time process can run before blocking, in microseconds.
-TThe maximum number of threads.
If
limitis given, and the-aoption is not used,limitis the new value of the specified resource. The speciallimitvalueshard,soft, andunlimitedstand 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-Hoption is supplied. When more than one resource is specified, the limit name and unit, if appropriate, are printed before the value. When setting new limits, if neither-Hnor-Sis supplied, both the hard and soft limits are set. If no option is given, then-fis assumed. Values are in 1024-byte increments, except for-t, which is in seconds;-R, which is in microseconds;-p, which is in units of 512-byte blocks;-P,-T,-b,-k,-nand-u, which are unscaled values; and, when in POSIX Mode (see Bash POSIX Mode),-cand-f, which are in 512-byte increments.The return status is zero unless an invalid option or argument is supplied, or an error occurs while setting a new limit.
unaliasunalias [-a] [name … ]
Remove each
namefrom the list of aliases. If-ais supplied, all aliases are removed. Aliases are described in Aliases.
Next: Modifying Shell Behavior, Previous: Bourne Shell Builtins, Up: Shell Builtin Commands [Contents][Index]