Linux "bash" Command Line Options and Examples
GNU Bourne-Again SHell

Bash is an sh-compatible command language interpreter that executes commands read from the standard input or from a file. Bash also incorporates useful features from the Korn and C shells (ksh and csh). Bash is intended to be a conformant implementation of the Shell and Utilities portion of the IEEE POSIX specification (IEEE Standard 1003.


Usage:

bash [options] [command_string | file]


COPYRIGHT
    Bash is Copyright (C) 1989-2016 by the Free Software Foundation, Inc.






Command Line Options:

-i
If the -i option is present, the shell is interactive.
bash -i ...
-l
Make bash act as if it had been invoked as a login shell (see INVOCATION below).
bash -l ...
-r
If the -r option is present, the shell becomes restricted (see RESTRICTED SHELL below).
bash -r ...
-v
Print shell input lines as they are read.
bash -v ...
-x
Print commands and their arguments as they are executed.
bash -x ...
-+]O
shopt_option is one of the shell options accepted by the shopt builtin (see SHELL BUILTIN COMMANDS below). If shopt_optionis present, -O sets the value of that option; +O unsets it. If shopt_option is not supplied, the names and values of theshell options accepted by shopt are printed on the standard output. If the invocation option is +O, the output is dis‐played in a format that may be reused as input.
bash -+]O ...
--debugger
Arrange for the debugger profile to be executed before the shell starts. Turns on extended debugging mode (see the descrip‐tion of the extdebug option to the shopt builtin below).
bash --debugger ...
--dump-po-strings
Equivalent to -D, but the output is in the GNU gettext po (portable object) file format.
bash --dump-po-strings ...
--dump-strings
Equivalent to -D.
bash --dump-strings ...
--help
Display a usage message on standard output and exit successfully.
bash --help ...
--rcfile
Execute commands from file instead of the system wide initialization file /etc/bash.bashrc and the standard personal initial‐ization file ~/.bashrc if the shell is interactive (see INVOCATION below).
bash --rcfile ...
--login
Equivalent to -l.
bash --login ...
--noediting
Do not use the GNU readline library to read command lines when the shell is interactive.
bash --noediting ...
--noprofile
Do not read either the system-wide startup file /etc/profile or any of the personal initialization files ~/.bash_profile,~/.bash_login, or ~/.profile. By default, bash reads these files when it is invoked as a login shell (see INVOCATION below).
bash --noprofile ...
--posix
Change the behavior of bash where the default operation differs from the POSIX standard to match the standard (posix mode).See SEE ALSO below for a reference to a document that details how posix mode affects bash's behavior.
bash --posix ...
--restricted
The shell becomes restricted (see RESTRICTED SHELL below).
bash --restricted ...
--verbose
Equivalent to -v.
bash --verbose ...
--version
Show version information for this instance of bash on the standard output and exit successfully.ARGUMENTSIf arguments remain after option processing, and neither the -c nor the -s option has been supplied, the first argument is assumed tobe the name of a file containing shell commands. If bash is invoked in this fashion, $0 is set to the name of the file, and thepositional parameters are set to the remaining arguments. Bash reads and executes commands from this file, then exits. Bash's exitstatus is the exit status of the last command executed in the script. If no commands are executed, the exit status is 0. An attemptis first made to open the file in the current directory, and, if no file is found, then the shell searches the directories in PATHfor the script.INVOCATIONA login shell is one whose first character of argument zero is a -, or one started with the --login option.An interactive shell is one started without non-option arguments (unless -s is specified) and without the -c option whose standardinput and error are both connected to terminals (as determined by isatty(3)), or one started with the -i option. PS1 is set and $-includes i if bash is interactive, allowing a shell script or a startup file to test this state.The following paragraphs describe how bash executes its startup files. If any of the files exist but cannot be read, bash reports anerror. Tildes are expanded in filenames as described below under Tilde Expansion in the EXPANSION section.When bash is invoked as an interactive login shell, or as a non-interactive shell with the --login option, it first reads and exe‐cutes commands from the file /etc/profile, if that file exists. After reading that file, it looks for ~/.bash_profile,~/.bash_login, and ~/.profile, in that order, and reads and executes commands from the first one that exists and is readable. The
bash --version ...
-1
Any element of an array may be referenced using ${name[subscript]}. The braces are required to avoid conflicts with pathname expan‐sion. If subscript is @ or *, the word expands to all members of name. These subscripts differ only when the word appears withindouble quotes. If the word is double-quoted, ${name[*]} expands to a single word with the value of each array member separated bythe first character of the IFS special variable, and ${name[@]} expands each element of name to a separate word. When there are noarray members, ${name[@]} expands to nothing. If the double-quoted expansion occurs within a word, the expansion of the first param‐eter is joined with the beginning part of the original word, and the expansion of the last parameter is joined with the last part ofthe original word. This is analogous to the expansion of the special parameters * and @ (see Special Parameters above).${#name[subscript]} expands to the length of ${name[subscript]}. If subscript is * or @, the expansion is the number of elements inthe array. If the subscript used to reference an element of an indexed array evaluates to a number less than zero, it is interpretedas relative to one greater than the maximum index of the array, so negative indices count back from the end of the array, and anindex of -1 references the last element.Referencing an array variable without a subscript is equivalent to referencing the array with a subscript of 0. Any reference to avariable using a valid subscript is legal, and bash will create an array if necessary.An array variable is considered set if a subscript has been assigned a value. The null string is a valid value.It is possible to obtain the keys (indices) of an array as well as the values. ${!name[@]} and ${!name[*]} expand to the indicesassigned in array variable name. The treatment when in double quotes is similar to the expansion of the special parameters @ and *within double quotes.The unset builtin is used to destroy arrays. unset name[subscript] destroys the array element at index subscript. Negative sub‐scripts to indexed arrays are interpreted as described above. Care must be taken to avoid unwanted side effects caused by pathnameexpansion. unset name, where name is an array, or unset name[subscript], where subscript is * or @, removes the entire array.The declare, local, and readonly builtins each accept a -a option to specify an indexed array and a -A option to specify an associa‐tive array. If both options are supplied, -A takes precedence. The read builtin accepts a -a option to assign a list of words readfrom the standard input to an array. The set and declare builtins display array values in a way that allows them to be reused asassignments.EXPANSIONExpansion is performed on the command line after it has been split into words. There are seven kinds of expansion performed: braceexpansion, tilde expansion, parameter and variable expansion, command substitution, arithmetic expansion, word splitting, and path‐name expansion.The order of expansions is: brace expansion; tilde expansion, parameter and variable expansion, arithmetic expansion, and commandsubstitution (done in a left-to-right fashion); word splitting; and pathname expansion.On systems that can support it, there is an additional expansion available: process substitution. This is performed at the same timeas tilde, parameter, variable, and arithmetic expansion and command substitution.After these expansions are performed, quote characters present in the original word are removed unless they have been quoted them‐selves (quote removal).Only brace expansion, word splitting, and pathname expansion can change the number of words of the expansion; other expansions expanda single word to a single word. The only exceptions to this are the expansions of "$@" and "${name[@]}" as explained above (seePARAMETERS).Brace ExpansionBrace expansion is a mechanism by which arbitrary strings may be generated. This mechanism is similar to pathname expansion, but thefilenames generated need not exist. Patterns to be brace expanded take the form of an optional preamble, followed by either a seriesof comma-separated strings or a sequence expression between a pair of braces, followed by an optional postscript. The preamble isprefixed to each string contained within the braces, and the postscript is then appended to each resulting string, expanding left toright.Brace expansions may be nested. The results of each expanded string are not sorted; left to right order is preserved. For example,a{d,c,b}e expands into `ade ace abe'.A sequence expression takes the form {x..y[..incr]}, where x and y are either integers or single characters, and incr, an optionalincrement, is an integer. When integers are supplied, the expression expands to each number between x and y, inclusive. Suppliedintegers may be prefixed with 0 to force each term to have the same width. When either x or y begins with a zero, the shell attemptsto force all generated terms to contain the same number of digits, zero-padding where necessary. When characters are supplied, theexpression expands to each character lexicographically between x and y, inclusive, using the default C locale. Note that both x andy must be of the same type. When the increment is supplied, it is used as the difference between each term. The default incrementis 1 or -1 as appropriate.Brace expansion is performed before any other expansions, and any characters special to other expansions are preserved in the result.It is strictly textual. Bash does not apply any syntactic interpretation to the context of the expansion or the text between thebraces.A correctly-formed brace expansion must contain unquoted opening and closing braces, and at least one unquoted comma or a validsequence expression. Any incorrectly formed brace expansion is left unchanged. A { or , may be quoted with a backslash to preventits being considered part of a brace expression. To avoid conflicts with parameter expansion, the string ${ is not considered eligi‐ble for brace expansion.This construct is typically used as shorthand when the common prefix of the strings to be generated is longer than in the above exam‐ple:mkdir /usr/local/src/bash/{old,new,dist,bugs}orchown root /usr/{ucb/{ex,edit},lib/{ex?.?*,how_ex}}Brace expansion introduces a slight incompatibility with historical versions of sh. sh does not treat opening or closing braces spe‐cially when they appear as part of a word, and preserves them in the output. Bash removes braces from words as a consequence ofbrace expansion. For example, a word entered to sh as file{1,2} appears identically in the output. The same word is output as file1file2 after expansion by bash. If strict compatibility with sh is desired, start bash with the +B option or disable brace expansionwith the +B option to the set command (see SHELL BUILTIN COMMANDS below).Tilde ExpansionIf a word begins with an unquoted tilde character (`~'), all of the characters preceding the first unquoted slash (or all characters,if there is no unquoted slash) are considered a tilde-prefix. If none of the characters in the tilde-prefix are quoted, the charac‐ters in the tilde-prefix following the tilde are treated as a possible login name. If this login name is the null string, the tildeis replaced with the value of the shell parameter HOME. If HOME is unset, the home directory of the user executing the shell is sub‐stituted instead. Otherwise, the tilde-prefix is replaced with the home directory associated with the specified login name.If the tilde-prefix is a `~+', the value of the shell variable PWD replaces the tilde-prefix. If the tilde-prefix is a `~-', thevalue of the shell variable OLDPWD, if it is set, is substituted. If the characters following the tilde in the tilde-prefix consistof a number N, optionally prefixed by a `+' or a `-', the tilde-prefix is replaced with the corresponding element from the directorystack, as it would be displayed by the dirs builtin invoked with the tilde-prefix as an argument. If the characters following thetilde in the tilde-prefix consist of a number without a leading `+' or `-', `+' is assumed.If the login name is invalid, or the tilde expansion fails, the word is unchanged.Each variable assignment is checked for unquoted tilde-prefixes immediately following a : or the first =. In these cases, tildeexpansion is also performed. Consequently, one may use filenames with tildes in assignments to PATH, MAILPATH, and CDPATH, and theshell assigns the expanded value.Parameter ExpansionThe `$' character introduces parameter expansion, command substitution, or arithmetic expansion. The parameter name or symbol to beexpanded may be enclosed in braces, which are optional but serve to protect the variable to be expanded from characters immediatelyfollowing it which could be interpreted as part of the name.When braces are used, the matching ending brace is the first `}' not escaped by a backslash or within a quoted string, and not withinan embedded arithmetic expansion, command substitution, or parameter expansion.${parameter}The value of parameter is substituted. The braces are required when parameter is a positional parameter with more than onedigit, or when parameter is followed by a character which is not to be interpreted as part of its name. The parameter is ashell parameter as described above PARAMETERS) or an array reference (Arrays).If the first character of parameter is an exclamation point (!), and parameter is not a nameref, it introduces a level of variableindirection. Bash uses the value of the variable formed from the rest of parameter as the name of the variable; this variable isthen expanded and that value is used in the rest of the substitution, rather than the value of parameter itself. This is known asindirect expansion. If parameter is a nameref, this expands to the name of the variable referenced by parameter instead of perform‐ing the complete indirect expansion. The exceptions to this are the expansions of ${!prefix*} and ${!name[@]} described below. Theexclamation point must immediately follow the left brace in order to introduce indirection.In each of the cases below, word is subject to tilde expansion, parameter expansion, command substitution, and arithmetic expansion.When not performing substring expansion, using the forms documented below (e.g., :-), bash tests for a parameter that is unset ornull. Omitting the colon results in a test only for a parameter that is unset.${parameter:-word}Use Default Values. If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameteris substituted.${parameter:=word}Assign Default Values. If parameter is unset or null, the expansion of word is assigned to parameter. The value of parameteris then substituted. Positional parameters and special parameters may not be assigned to in this way.${parameter:?word}Display Error if Null or Unset. If parameter is null or unset, the expansion of word (or a message to that effect if word isnot present) is written to the standard error and the shell, if it is not interactive, exits. Otherwise, the value of parame‐ter is substituted.${parameter:+word}Use Alternate Value. If parameter is null or unset, nothing is substituted, otherwise the expansion of word is substituted.${parameter:offset}${parameter:offset:length}Substring Expansion. Expands to up to length characters of the value of parameter starting at the character specified by off‐set. If parameter is @, an indexed array subscripted by @ or *, or an associative array name, the results differ as describedbelow. If length is omitted, expands to the substring of the value of parameter starting at the character specified by offsetand extending to the end of the value. length and offset are arithmetic expressions (see ARITHMETIC EVALUATION below).If offset evaluates to a number less than zero, the value is used as an offset in characters from the end of the value ofparameter. If length evaluates to a number less than zero, it is interpreted as an offset in characters from the end of thevalue of parameter rather than a number of characters, and the expansion is the characters between offset and that result.Note that a negative offset must be separated from the colon by at least one space to avoid being confused with the :- expan‐sion.If parameter is @, the result is length positional parameters beginning at offset. A negative offset is taken relative to onegreater than the greatest positional parameter, so an offset of -1 evaluates to the last positional parameter. It is anexpansion error if length evaluates to a number less than zero.If parameter is an indexed array name subscripted by @ or *, the result is the length members of the array beginning with${parameter[offset]}. A negative offset is taken relative to one greater than the maximum index of the specified array. Itis an expansion error if length evaluates to a number less than zero.Substring expansion applied to an associative array produces undefined results.Substring indexing is zero-based unless the positional parameters are used, in which case the indexing starts at 1 by default.If offset is 0, and the positional parameters are used, $0 is prefixed to the list.${!prefix*}${!prefix@}Names matching prefix. Expands to the names of variables whose names begin with prefix, separated by the first character ofthe IFS special variable. When @ is used and the expansion appears within double quotes, each variable name expands to a sep‐arate word.${!name[@]}${!name[*]}List of array keys. If name is an array variable, expands to the list of array indices (keys) assigned in name. If name isnot an array, expands to 0 if name is set and null otherwise. When @ is used and the expansion appears within double quotes,each key expands to a separate word.${#parameter}Parameter length. The length in characters of the value of parameter is substituted. If parameter is * or @, the value sub‐stituted is the number of positional parameters. If parameter is an array name subscripted by * or @, the value substitutedis the number of elements in the array. If parameter is an indexed array name subscripted by a negative number, that numberis interpreted as relative to one greater than the maximum index of parameter, so negative indices count back from the end ofthe array, and an index of -1 references the last element.${parameter#word}${parameter##word}Remove matching prefix pattern. The word is expanded to produce a pattern just as in pathname expansion. If the patternmatches the beginning of the value of parameter, then the result of the expansion is the expanded value of parameter with theshortest matching pattern (the ``#'' case) or the longest matching pattern (the ``##'' case) deleted. If parameter is @ or *,the pattern removal operation is applied to each positional parameter in turn, and the expansion is the resultant list. Ifparameter is an array variable subscripted with @ or *, the pattern removal operation is applied to each member of the arrayin turn, and the expansion is the resultant list.${parameter%word}${parameter%%word}Remove matching suffix pattern. The word is expanded to produce a pattern just as in pathname expansion. If the patternmatches a trailing portion of the expanded value of parameter, then the result of the expansion is the expanded value ofparameter with the shortest matching pattern (the ``%'' case) or the longest matching pattern (the ``%%'' case) deleted. Ifparameter is @ or *, the pattern removal operation is applied to each positional parameter in turn, and the expansion is theresultant list. If parameter is an array variable subscripted with @ or *, the pattern removal operation is applied to eachmember of the array in turn, and the expansion is the resultant list.${parameter/pattern/string}Pattern substitution. The pattern is expanded to produce a pattern just as in pathname expansion. Parameter is expanded andthe longest match of pattern against its value is replaced with string. If pattern begins with /, all matches of pattern arereplaced with string. Normally only the first match is replaced. If pattern begins with #, it must match at the beginning ofthe expanded value of parameter. If pattern begins with %, it must match at the end of the expanded value of parameter. Ifstring is null, matches of pattern are deleted and the / following pattern may be omitted. If the nocasematch shell option isenabled, the match is performed without regard to the case of alphabetic characters. If parameter is @ or *, the substitutionoperation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an arrayvariable subscripted with @ or *, the substitution operation is applied to each member of the array in turn, and the expansionis the resultant list.${parameter^pattern}${parameter^^pattern}${parameter,pattern}${parameter,,pattern}Case modification. This expansion modifies the case of alphabetic characters in parameter. The pattern is expanded to pro‐duce a pattern just as in pathname expansion. Each character in the expanded value of parameter is tested against pattern,and, if it matches the pattern, its case is converted. The pattern should not attempt to match more than one character. The^ operator converts lowercase letters matching pattern to uppercase; the , operator converts matching uppercase letters tolowercase. The ^^ and ,, expansions convert each matched character in the expanded value; the ^ and , expansions match andconvert only the first character in the expanded value. If pattern is omitted, it is treated like a ?, which matches everycharacter. If parameter is @ or *, the case modification operation is applied to each positional parameter in turn, and theexpansion is the resultant list. If parameter is an array variable subscripted with @ or *, the case modification operationis applied to each member of the array in turn, and the expansion is the resultant list.${parameter@operator}Parameter transformation. The expansion is either a transformation of the value of parameter or information about parameteritself, depending on the value of operator. Each operator is a single letter:Q The expansion is a string that is the value of parameter quoted in a format that can be reused as input.E The expansion is a string that is the value of parameter with backslash escape sequences expanded as with the $'...'quoting mechansim.P The expansion is a string that is the result of expanding the value of parameter as if it were a prompt string (seePROMPTING below).A The expansion is a string in the form of an assignment statement or declare command that, if evaluated, will recreateparameter with its attributes and value.a The expansion is a string consisting of flag values representing parameter's attributes.If parameter is @ or *, the operation is applied to each positional parameter in turn, and the expansion is the resultantlist. If parameter is an array variable subscripted with @ or *, the case modification operation is applied to each member ofthe array in turn, and the expansion is the resultant list.The result of the expansion is subject to word splitting and pathname expansion as described below.Command SubstitutionCommand substitution allows the output of a command to replace the command name. There are two forms:$(command)or`command`Bash performs the expansion by executing command in a subshell environment and replacing the command substitution with the standardoutput of the command, with any trailing newlines deleted. Embedded newlines are not deleted, but they may be removed during wordsplitting. The command substitution $(cat file) can be replaced by the equivalent but faster $(< file).When the old-style backquote form of substitution is used, backslash retains its literal meaning except when followed by $, `, or \.The first backquote not preceded by a backslash terminates the command substitution. When using the $(command) form, all charactersbetween the parentheses make up the command; none are treated specially.Command substitutions may be nested. To nest when using the backquoted form, escape the inner backquotes with backslashes.If the substitution appears within double quotes, word splitting and pathname expansion are not performed on the results.Arithmetic ExpansionArithmetic expansion allows the evaluation of an arithmetic expression and the substitution of the result. The format for arithmeticexpansion is:$((expression))The old format $[expression] is deprecated and will be removed in upcoming versions of bash.The expression is treated as if it were within double quotes, but a double quote inside the parentheses is not treated specially.All tokens in the expression undergo parameter and variable expansion, command substitution, and quote removal. The result istreated as the arithmetic expression to be evaluated. Arithmetic expansions may be nested.The evaluation is performed according to the rules listed below under ARITHMETIC EVALUATION. If expression is invalid, bash prints amessage indicating failure and no substitution occurs.Process SubstitutionProcess substitution allows a process's input or output to be referred to using a filename. It takes the form of <(list) or >(list).The process list is run asynchronously, and its input or output appears as a filename. This filename is passed as an argument to thecurrent command as the result of the expansion. If the >(list) form is used, writing to the file will provide input for list. Ifthe <(list) form is used, the file passed as an argument should be read to obtain the output of list. Process substitution is sup‐ported on systems that support named pipes (FIFOs) or the /dev/fd method of naming open files.When available, process substitution is performed simultaneously with parameter and variable expansion, command substitution, andarithmetic expansion.Word SplittingThe shell scans the results of parameter expansion, command substitution, and arithmetic expansion that did not occur within doublequotes for word splitting.The shell treats each character of IFS as a delimiter, and splits the results of the other expansions into words using these charac‐ters as field terminators. If IFS is unset, or its value is exactly <space><tab><newline>, the default, then sequences of <space>,<tab>, and <newline> at the beginning and end of the results of the previous expansions are ignored, and any sequence of IFS charac‐ters not at the beginning or end serves to delimit words. If IFS has a value other than the default, then sequences of the white‐space characters space, tab, and newline are ignored at the beginning and end of the word, as long as the whitespace character is inthe value of IFS (an IFS whitespace character). Any character in IFS that is not IFS whitespace, along with any adjacent IFS white‐space characters, delimits a field. A sequence of IFS whitespace characters is also treated as a delimiter. If the value of IFS isnull, no word splitting occurs.Explicit null arguments ("" or '') are retained and passed to commands as empty strings. Unquoted implicit null arguments, resultingfrom the expansion of parameters that have no values, are removed. If a parameter with no value is expanded within double quotes, anull argument results and is retained and passed to a command as an empty string. When a quoted null argument appears as part of aword whose expansion is non-null, the null argument is removed. That is, the word -d'' becomes -d after word splitting and nullargument removal.Note that if no expansion occurs, no splitting is performed.Pathname ExpansionAfter word splitting, unless the -f option has been set, bash scans each word for the characters *, ?, and [. If one of these char‐acters appears, then the word is regarded as a pattern, and replaced with an alphabetically sorted list of filenames matching thepattern (see Pattern Matching below). If no matching filenames are found, and the shell option nullglob is not enabled, the word isleft unchanged. If the nullglob option is set, and no matches are found, the word is removed. If the failglob shell option is set,and no matches are found, an error message is printed and the command is not executed. If the shell option nocaseglob is enabled,the match is performed without regard to the case of alphabetic characters. Note that when using range expressions like [a-z] (seebelow), letters of the other case may be included, depending on the setting of LC_COLLATE. When a pattern is used for pathnameexpansion, the character ``.'' at the start of a name or immediately following a slash must be matched explicitly, unless the shelloption dotglob is set. When matching a pathname, the slash character must always be matched explicitly. In other cases, the ``.''character is not treated specially. See the description of shopt below under SHELL BUILTIN COMMANDS for a description of the nocase‐glob, nullglob, failglob, and dotglob shell options.The GLOBIGNORE shell variable may be used to restrict the set of filenames matching a pattern. If GLOBIGNORE is set, each matchingfilename that also matches one of the patterns in GLOBIGNORE is removed from the list of matches. If the nocaseglob option is set,the matching against the patterns in GLOBIGNORE is performed without regard to case. The filenames ``.'' and ``..'' are alwaysignored when GLOBIGNORE is set and not null. However, setting GLOBIGNORE to a non-null value has the effect of enabling the dotglobshell option, so all other filenames beginning with a ``.'' will match. To get the old behavior of ignoring filenames beginningwith a ``.'', make ``.*'' one of the patterns in GLOBIGNORE. The dotglob option is disabled when GLOBIGNORE is unset. The patternmatching honors the setting of the extglob shell option.Pattern MatchingAny character that appears in a pattern, other than the special pattern characters described below, matches itself. The NUL charac‐ter may not occur in a pattern. A backslash escapes the following character; the escaping backslash is discarded when matching. Thespecial pattern characters must be quoted if they are to be matched literally.The special pattern characters have the following meanings:* Matches any string, including the null string. When the globstar shell option is enabled, and * is used in a pathnameexpansion context, two adjacent *s used as a single pattern will match all files and zero or more directories and sub‐directories. If followed by a /, two adjacent *s will match only directories and subdirectories.? Matches any single character.[...] Matches any one of the enclosed characters. A pair of characters separated by a hyphen denotes a range expression; anycharacter that falls between those two characters, inclusive, using the current locale's collating sequence and charac‐ter set, is matched. If the first character following the [ is a ! or a ^ then any character not enclosed is matched.The sorting order of characters in range expressions is determined by the current locale and the values of the LC_COL‐LATE or LC_ALL shell variables, if set. To obtain the traditional interpretation of range expressions, where [a-d] isequivalent to [abcd], set value of the LC_ALL shell variable to C, or enable the globasciiranges shell option. A - maybe matched by including it as the first or last character in the set. A ] may be matched by including it as the firstcharacter in the set.Within [ and ], character classes can be specified using the syntax [:class:], where class is one of the followingclasses defined in the POSIX standard:alnum alpha ascii blank cntrl digit graph lower print punct space upper word xdigitA character class matches any character belonging to that class. The word character class matches letters, digits, andthe character _.Within [ and ], an equivalence class can be specified using the syntax [=c=], which matches all characters with thesame collation weight (as defined by the current locale) as the character c.Within [ and ], the syntax [.symbol.] matches the collating symbol symbol.If the extglob shell option is enabled using the shopt builtin, several extended pattern matching operators are recognized. In thefollowing description, a pattern-list is a list of one or more patterns separated by a |. Composite patterns may be formed using oneor more of the following sub-patterns:?(pattern-list)Matches zero or one occurrence 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 one of the given patterns!(pattern-list)Matches anything except one of the given patternsQuote RemovalAfter the preceding expansions, all unquoted occurrences of the characters \, ', and " that did not result from one of the aboveexpansions are removed.REDIRECTIONBefore a command is executed, its input and output may be redirected using a special notation interpreted by the shell. Redirectionallows commands' file handles to be duplicated, opened, closed, made to refer to different files, and can change the files the com‐mand reads from and writes to. Redirection may also be used to modify file handles in the current shell execution environment. Thefollowing redirection operators may precede or appear anywhere within a simple command or may follow a command. Redirections areprocessed in the order they appear, from left to right.Each redirection that may be preceded by a file descriptor number may instead be preceded by a word of the form {varname}. In thiscase, for each redirection operator except >&- and <&-, the shell will allocate a file descriptor greater than or equal to 10 andassign it to varname. If >&- or <&- is preceded by {varname}, the value of varname defines the file descriptor to close.In the following descriptions, if the file descriptor number is omitted, and the first character of the redirection operator is <,the redirection refers to the standard input (file descriptor 0). If the first character of the redirection operator is >, the redi‐rection refers to the standard output (file descriptor 1).The word following the redirection operator in the following descriptions, unless otherwise noted, is subjected to brace expansion,tilde expansion, parameter and variable expansion, command substitution, arithmetic expansion, quote removal, pathname expansion, andword splitting. If it expands to more than one word, bash reports an error.Note that the order of redirections is significant. For example, the commandls > dirlist 2>&1directs both standard output and standard error to the file dirlist, while the commandls 2>&1 > dirlistdirects only the standard output to file dirlist, because the standard error was duplicated from the standard output before the stan‐dard output was redirected to dirlist.Bash handles several filenames specially when they are used in redirections, as described in the following table. If the operatingsystem on which bash is running provides these special files, bash will use them; otherwise it will emulate them internally with thebehavior described below./dev/fd/fdIf fd is a valid integer, file descriptor fd is duplicated./dev/stdinFile descriptor 0 is duplicated./dev/stdoutFile descriptor 1 is duplicated./dev/stderrFile descriptor 2 is duplicated./dev/tcp/host/portIf host is a valid hostname or Internet address, and port is an integer port number or service name, bash attempts toopen the corresponding TCP socket./dev/udp/host/portIf host is a valid hostname or Internet address, and port is an integer port number or service name, bash attempts toopen the corresponding UDP socket.A failure to open or create a file causes the redirection to fail.Redirections using file descriptors greater than 9 should be used with care, as they may conflict with file descriptors the shelluses internally.Note that the exec builtin command can make redirections take effect in the current shell.Redirecting InputRedirection of input causes the file whose name results from the expansion of word to be opened for reading on file descriptor n, orthe standard input (file descriptor 0) if n is not specified.The general format for redirecting input is:[n]<wordRedirecting OutputRedirection of output causes the file whose name results from the expansion of word to be opened for writing on file descriptor n, orthe standard output (file descriptor 1) if n is not specified. If the file does not exist it is created; if it does exist it istruncated to zero size.The general format for redirecting output is:[n]>wordIf the redirection operator is >, and the noclobber option to the set builtin has been enabled, the redirection will fail if the filewhose name results from the expansion of word exists and is a regular file. If the redirection operator is >|, or the redirectionoperator is > and the noclobber option to the set builtin command is not enabled, the redirection is attempted even if the file namedby word exists.Appending Redirected OutputRedirection of output in this fashion causes the file whose name results from the expansion of word to be opened for appending onfile descriptor n, or the standard output (file descriptor 1) if n is not specified. If the file does not exist it is created.The general format for appending output is:[n]>>wordRedirecting Standard Output and Standard ErrorThis construct allows both the standard output (file descriptor 1) and the standard error output (file descriptor 2) to be redirectedto the file whose name is the expansion of word.There are two formats for redirecting standard output and standard error:&>wordand>&wordOf the two forms, the first is preferred. This is semantically equivalent to>word 2>&1When using the second form, word may not expand to a number or -. If it does, other redirection operators apply (see DuplicatingFile Descriptors below) for compatibility reasons.Appending Standard Output and Standard ErrorThis construct allows both the standard output (file descriptor 1) and the standard error output (file descriptor 2) to be appendedto the file whose name is the expansion of word.The format for appending standard output and standard error is:&>>wordThis is semantically equivalent to>>word 2>&1(see Duplicating File Descriptors below).Here DocumentsThis type of redirection instructs the shell to read input from the current source until a line containing only delimiter (with notrailing blanks) is seen. All of the lines read up to that point are then used as the standard input (or file descriptor n if n isspecified) for a command.The format of here-documents is:[n]<<[-]wordhere-documentdelimiterNo parameter and variable expansion, command substitution, arithmetic expansion, or pathname expansion is performed on word. If anypart of word is quoted, the delimiter is the result of quote removal on word, and the lines in the here-document are not expanded.If word is unquoted, all lines of the here-document are subjected to parameter expansion, command substitution, and arithmetic expan‐sion, the character sequence \<newline> is ignored, and \ must be used to quote the characters \, $, and `.If the redirection operator is <<-, then all leading tab characters are stripped from input lines and the line containing delimiter.This allows here-documents within shell scripts to be indented in a natural fashion.Here StringsA variant of here documents, the format is:[n]<<<wordThe word undergoes brace expansion, tilde expansion, parameter and variable expansion, command substitution, arithmetic expansion,and quote removal. Pathname expansion and word splitting are not performed. The result is supplied as a single string, with a new‐line appended, to the command on its standard input (or file descriptor n if n is specified).Duplicating File DescriptorsThe redirection operator[n]<&wordis used to duplicate input file descriptors. If word expands to one or more digits, the file descriptor denoted by n is made to be acopy of that file descriptor. If the digits in word do not specify a file descriptor open for input, a redirection error occurs. Ifword evaluates to -, file descriptor n is closed. If n is not specified, the standard input (file descriptor 0) is used.The operator[n]>&wordis used similarly to duplicate output file descriptors. If n is not specified, the standard output (file descriptor 1) is used. Ifthe digits in word do not specify a file descriptor open for output, a redirection error occurs. If word evaluates to -, filedescriptor n is closed. As a special case, if n is omitted, and word does not expand to one or more digits or -, the standard outputand standard error are redirected as described previously.Moving File DescriptorsThe redirection operator[n]<&digit-moves the file descriptor digit to file descriptor n, or the standard input (file descriptor 0) if n is not specified. digit isclosed after being duplicated to n.Similarly, the redirection operator[n]>&digit-moves the file descriptor digit to file descriptor n, or the standard output (file descriptor 1) if n is not specified.Opening File Descriptors for Reading and WritingThe redirection operator[n]<>wordcauses the file whose name is the expansion of word to be opened for both reading and writing on file descriptor n, or on filedescriptor 0 if n is not specified. If the file does not exist, it is created.ALIASESAliases allow a string to be substituted for a word when it is used as the first word of a simple command. The shell maintains alist of aliases that may be set and unset with the alias and unalias builtin commands (see SHELL BUILTIN COMMANDS below). The firstword of each simple command, if unquoted, is checked to see if it has an alias. If so, that word is replaced by the text of thealias. The characters /, $, `, and = and any of the shell metacharacters or quoting characters listed above may not appear in analias name. The replacement text may contain any valid shell input, including shell metacharacters. The first word of the replace‐ment text is tested for aliases, but a word that is identical to an alias being expanded is not expanded a second time. This meansthat one may alias ls to ls -F, for instance, and bash does not try to recursively expand the replacement text. If the last charac‐ter of the alias value is a blank, then the next command word following the alias is also checked for alias expansion.Aliases are created and listed with the alias command, and removed with the unalias command.There is no mechanism for using arguments in the replacement text. If arguments are needed, a shell function should be used (seeFUNCTIONS below).Aliases are not expanded when the shell is not interactive, unless the expand_aliases shell option is set using shopt (see thedescription of shopt under SHELL BUILTIN COMMANDS below).The rules concerning the definition and use of aliases are somewhat confusing. Bash always reads at least one complete line of inputbefore executing any of the commands on that line. Aliases are expanded when a command is read, not when it is executed. Therefore,an alias definition appearing on the same line as another command does not take effect until the next line of input is read. Thecommands following the alias definition on that line are not affected by the new alias. This behavior is also an issue when func‐tions are executed. Aliases are expanded when a function definition is read, not when the function is executed, because a functiondefinition is itself a command. As a consequence, aliases defined in a function are not available until after that function is exe‐cuted. To be safe, always put alias definitions on a separate line, and do not use alias in compound commands.For almost every purpose, aliases are superseded by shell functions.FUNCTIONSA shell function, defined as described above under SHELL GRAMMAR, stores a series of commands for later execution. When the name ofa shell function is used as a simple command name, the list of commands associated with that function name is executed. Functionsare executed in the context of the current shell; no new process is created to interpret them (contrast this with the execution of ashell script). When a function is executed, the arguments to the function become the positional parameters during its execution.The special parameter # is updated to reflect the change. Special parameter 0 is unchanged. The first element of the FUNCNAME vari‐able is set to the name of the function while the function is executing.All other aspects of the shell execution environment are identical between a function and its caller with these exceptions: the DEBUGand RETURN traps (see the description of the trap builtin under SHELL BUILTIN COMMANDS below) are not inherited unless the functionhas been given the trace attribute (see the description of the declare builtin below) or the -o functrace shell option has beenenabled with the set builtin (in which case all functions inherit the DEBUG and RETURN traps), and the ERR trap is not inheritedunless the -o errtrace shell option has been enabled.Variables local to the function may be declared with the local builtin command. Ordinarily, variables and their values are sharedbetween the function and its caller.The FUNCNEST variable, if set to a numeric value greater than 0, defines a maximum function nesting level. Function invocations thatexceed the limit cause the entire command to abort.If the builtin command return is executed in a function, the function completes and execution resumes with the next command after thefunction call. Any command associated with the RETURN trap is executed before execution resumes. When a function completes, thevalues of the positional parameters and the special parameter # are restored to the values they had prior to the function's execu‐tion.Function names and definitions may be listed with the -f option to the declare or typeset builtin commands. The -F option to declareor typeset will list the function names only (and optionally the source file and line number, if the extdebug shell option isenabled). Functions may be exported so that subshells automatically have them defined with the -f option to the export builtin. Afunction definition may be deleted using the -f option to the unset builtin. Note that shell functions and variables with the samename may result in multiple identically-named entries in the environment passed to the shell's children. Care should be taken incases where this may cause a problem.Functions may be recursive. The FUNCNEST variable may be used to limit the depth of the function call stack and restrict the numberof function invocations. By default, no limit is imposed on the number of recursive calls.ARITHMETIC EVALUATIONThe shell allows arithmetic expressions to be evaluated, under certain circumstances (see the let and declare builtin commands, the(( compound command, and Arithmetic Expansion). Evaluation is done in fixed-width integers with no check for overflow, though divi‐sion by 0 is trapped and flagged as an error. The operators and their precedence, associativity, and values are the same as in the Clanguage. The following list of operators is grouped into levels of equal-precedence operators. The levels are listed in order ofdecreasing precedence.id++ id--variable post-increment and post-decrement++id --idvariable pre-increment and pre-decrement
bash -1 ...
-
! ~ logical and bitwise negation** exponentiation* / % multiplication, division, remainder
bash - ...
-a
True if file exists.
bash -a ...
-b
True if file exists and is a block special file.
bash -b ...
-c
True if file exists and is a character special file.
bash -c ...
-d
True if file exists and is a directory.
bash -d ...
-e
True if file exists.
bash -e ...
-f
True if file exists and is a regular file.
bash -f ...
-g
True if file exists and is set-group-id.
bash -g ...
-h
True if file exists and is a symbolic link.
bash -h ...
-k
True if file exists and its ``sticky'' bit is set.
bash -k ...
-p
True if file exists and is a named pipe (FIFO).
bash -p ...
-s
True if file exists and has a size greater than zero.
bash -s ...
-t
fd True if file descriptor fd is open and refers to a terminal.
bash -t ...
-u
True if file exists and its set-user-id bit is set.
bash -u ...
-w
True if file exists and is writable.
bash -w ...
-G
True if file exists and is owned by the effective group id.
bash -G ...
-L
True if file exists and is a symbolic link.
bash -L ...
-N
True if file exists and has been modified since it was last read.
bash -N ...
-O
True if file exists and is owned by the effective user id.
bash -O ...
-S
True if file exists and is a socket.file1 -ef file2True if file1 and file2 refer to the same device and inode numbers.file1 -nt file2True if file1 is newer (according to modification date) than file2, or if file1 exists and file2 does not.file1 -ot file2True if file1 is older than file2, or if file2 exists and file1 does not.
bash -S ...
-o
True if the shell option optname is enabled. See the list of options under the description of the -o option to the setbuiltin below.
bash -o ...
-R
True if the shell variable varname is set and is a name reference.
bash -R ...
-z
True if the length of string is zero.string
bash -z ...
-n
True if the length of string is non-zero.string1 == string2string1 = string2True if the strings are equal. = should be used with the test command for POSIX conformance. When used with the [[ command,this performs pattern matching as described above (Compound Commands).string1 != string2True if the strings are not equal.string1 < string2True if string1 sorts before string2 lexicographically.string1 > string2True if string1 sorts after string2 lexicographically.arg1 OP arg2OP is one of -eq, -ne, -lt, -le, -gt, or -ge. These arithmetic binary operators return true if arg1 is equal to, not equalto, less than, less than or equal to, greater than, or greater than or equal to arg2, respectively. Arg1 and arg2 may be pos‐itive or negative integers.SIMPLE COMMAND EXPANSIONWhen a simple command is executed, the shell performs the following expansions, assignments, and redirections, from left to right.1. The words that the parser has marked as variable assignments (those preceding the command name) and redirections are saved forlater processing.2. The words that are not variable assignments or redirections are expanded. If any words remain after expansion, the first wordis taken to be the name of the command and the remaining words are the arguments.3. Redirections are performed as described above under REDIRECTION.4. The text after the = in each variable assignment undergoes tilde expansion, parameter expansion, command substitution, arith‐metic expansion, and quote removal before being assigned to the variable.If no command name results, the variable assignments affect the current shell environment. Otherwise, the variables are added to theenvironment of the executed command and do not affect the current shell environment. If any of the assignments attempts to assign avalue to a readonly variable, an error occurs, and the command exits with a non-zero status.If no command name results, redirections are performed, but do not affect the current shell environment. A redirection error causesthe command to exit with a non-zero status.If there is a command name left after expansion, execution proceeds as described below. Otherwise, the command exits. If one of theexpansions contained a command substitution, the exit status of the command is the exit status of the last command substitution per‐formed. If there were no command substitutions, the command exits with a status of zero.COMMAND EXECUTIONAfter a command has been split into words, if it results in a simple command and an optional list of arguments, the following actionsare taken.If the command name contains no slashes, the shell attempts to locate it. If there exists a shell function by that name, that func‐tion is invoked as described above in FUNCTIONS. If the name does not match a function, the shell searches for it in the list ofshell builtins. If a match is found, that builtin is invoked.If the name is neither a shell function nor a builtin, and contains no slashes, bash searches each element of the PATH for a direc‐tory containing an executable file by that name. Bash uses a hash table to remember the full pathnames of executable files (see hashunder SHELL BUILTIN COMMANDS below). A full search of the directories in PATH is performed only if the command is not found in thehash table. If the search is unsuccessful, the shell searches for a defined shell function named command_not_found_handle. If thatfunction exists, it is invoked with the original command and the original command's arguments as its arguments, and the function'sexit status becomes the exit status of the shell. If that function is not defined, the shell prints an error message and returns anexit status of 127.If the search is successful, or if the command name contains one or more slashes, the shell executes the named program in a separateexecution environment. Argument 0 is set to the name given, and the remaining arguments to the command are set to the argumentsgiven, if any.If this execution fails because the file is not in executable format, and the file is not a directory, it is assumed to be a shellscript, a file containing shell commands. A subshell is spawned to execute it. This subshell reinitializes itself, so that theeffect is as if a new shell had been invoked to handle the script, with the exception that the locations of commands remembered bythe parent (see hash below under SHELL BUILTIN COMMANDS) are retained by the child.If the program is a file beginning with #!, the remainder of the first line specifies an interpreter for the program. The shell exe‐cutes the specified interpreter on operating systems that do not handle this executable format themselves. The arguments to theinterpreter consist of a single optional argument following the interpreter name on the first line of the program, followed by thename of the program, followed by the command arguments, if any.COMMAND EXECUTION ENVIRONMENTThe shell has an execution environment, which consists of the following:· open files inherited by the shell at invocation, as modified by redirections supplied to the exec builtin· the current working directory as set by cd, pushd, or popd, or inherited by the shell at invocation· the file creation mode mask as set by umask or inherited from the shell's parent· current traps set by trap· shell parameters that are set by variable assignment or with set or inherited from the shell's parent in the environment· shell functions defined during execution or inherited from the shell's parent in the environment· options enabled at invocation (either by default or with command-line arguments) or by set· options enabled by shopt· shell aliases defined with alias· various process IDs, including those of background jobs, the value of $$, and the value of PPIDWhen a simple command other than a builtin or shell function is to be executed, it is invoked in a separate execution environmentthat consists of the following. Unless otherwise noted, the values are inherited from the shell.· the shell's open files, plus any modifications and additions specified by redirections to the command· the current working directory· the file creation mode mask· shell variables and functions marked for export, along with variables exported for the command, passed in the environment· traps caught by the shell are reset to the values inherited from the shell's parent, and traps ignored by the shell areignoredA command invoked in this separate environment cannot affect the shell's execution environment.Command substitution, commands grouped with parentheses, and asynchronous commands are invoked in a subshell environment that is aduplicate of the shell environment, except that traps caught by the shell are reset to the values that the shell inherited from itsparent at invocation. Builtin commands that are invoked as part of a pipeline are also executed in a subshell environment. Changesmade to the subshell environment cannot affect the shell's execution environment.Subshells spawned to execute command substitutions inherit the value of the -e option from the parent shell. When not in posix mode,bash clears the -e option in such subshells.If a command is followed by a & and job control is not active, the default standard input for the command is the empty file/dev/null. Otherwise, the invoked command inherits the file descriptors of the calling shell as modified by redirections.ENVIRONMENTWhen a program is invoked it is given an array of strings called the environment. This is a list of name-value pairs, of the formname=value.The shell provides several ways to manipulate the environment. On invocation, the shell scans its own environment and creates aparameter for each name found, automatically marking it for export to child processes. Executed commands inherit the environment.The export and declare -x commands allow parameters and functions to be added to and deleted from the environment. If the value of aparameter in the environment is modified, the new value becomes part of the environment, replacing the old. The environment inher‐ited by any executed command consists of the shell's initial environment, whose values may be modified in the shell, less any pairsremoved by the unset command, plus any additions via the export and declare -x commands.The environment for any simple command or function may be augmented temporarily by prefixing it with parameter assignments, asdescribed above in PARAMETERS. These assignment statements affect only the environment seen by that command.If the -k option is set (see the set builtin command below), then all parameter assignments are placed in the environment for a com‐mand, not just those that precede the command name.When bash invokes an external command, the variable _ is set to the full filename of the command and passed to that command in itsenvironment.EXIT STATUSThe exit status of an executed command is the value returned by the waitpid system call or equivalent function. Exit statuses fallbetween 0 and 255, though, as explained below, the shell may use values above 125 specially. Exit statuses from shell builtins andcompound commands are also limited to this range. Under certain circumstances, the shell will use special values to indicate spe‐cific failure modes.For the shell's purposes, a command which exits with a zero exit status has succeeded. An exit status of zero indicates success. Anon-zero exit status indicates failure. When a command terminates on a fatal signal N, bash uses the value of 128+N as the exit sta‐tus.If a command is not found, the child process created to execute it returns a status of 127. If a command is found but is not exe‐cutable, the return status is 126.If a command fails because of an error during expansion or redirection, the exit status is greater than zero.Shell builtin commands return a status of 0 (true) if successful, and non-zero (false) if an error occurs while they execute. Allbuiltins return an exit status of 2 to indicate incorrect usage, generally invalid options or missing arguments.Bash itself returns the exit status of the last command executed, unless a syntax error occurs, in which case it exits with a non-zero value. See also the exit builtin command below.SIGNALSWhen bash is interactive, in the absence of any traps, it ignores SIGTERM (so that kill 0 does not kill an interactive shell), andSIGINT is caught and handled (so that the wait builtin is interruptible). In all cases, bash ignores SIGQUIT. If job control is ineffect, bash ignores SIGTTIN, SIGTTOU, and SIGTSTP.Non-builtin commands run by bash have signal handlers set to the values inherited by the shell from its parent. When job control isnot in effect, asynchronous commands ignore SIGINT and SIGQUIT in addition to these inherited handlers. Commands run as a result ofcommand substitution ignore the keyboard-generated job control signals SIGTTIN, SIGTTOU, and SIGTSTP.The shell exits by default upon receipt of a SIGHUP. Before exiting, an interactive shell resends the SIGHUP to all jobs, running orstopped. Stopped jobs are sent SIGCONT to ensure that they receive the SIGHUP. To prevent the shell from sending the signal to aparticular job, it should be removed from the jobs table with the disown builtin (see SHELL BUILTIN COMMANDS below) or marked to notreceive SIGHUP using disown -h.If the huponexit shell option has been set with shopt, bash sends a SIGHUP to all jobs when an interactive login shell exits.If bash is waiting for a command to complete and receives a signal for which a trap has been set, the trap will not be executed untilthe command completes. When bash is waiting for an asynchronous command via the wait builtin, the reception of a signal for which atrap has been set will cause the wait builtin to return immediately with an exit status greater than 128, immediately after which thetrap is executed.JOB CONTROLJob control refers to the ability to selectively stop (suspend) the execution of processes and continue (resume) their execution at alater point. A user typically employs this facility via an interactive interface supplied jointly by the operating system kernel'sterminal driver and bash.The shell associates a job with each pipeline. It keeps a table of currently executing jobs, which may be listed with the jobs com‐mand. When bash starts a job asynchronously (in the background), it prints a line that looks like:[1] 25647indicating that this job is job number 1 and that the process ID of the last process in the pipeline associated with this job is25647. All of the processes in a single pipeline are members of the same job. Bash uses the job abstraction as the basis for jobcontrol.To facilitate the implementation of the user interface to job control, the operating system maintains the notion of a current termi‐nal process group ID. Members of this process group (processes whose process group ID is equal to the current terminal process groupID) receive keyboard-generated signals such as SIGINT. These processes are said to be in the foreground. Background processes arethose whose process group ID differs from the terminal's; such processes are immune to keyboard-generated signals. Only foregroundprocesses are allowed to read from or, if the user so specifies with stty tostop, write to the terminal. Background processes whichattempt to read from (write to when stty tostop is in effect) the terminal are sent a SIGTTIN (SIGTTOU) signal by the kernel's termi‐nal driver, which, unless caught, suspends the process.If the operating system on which bash is running supports job control, bash contains facilities to use it. Typing the suspend char‐acter (typically ^Z, Control-Z) while a process is running causes that process to be stopped and returns control to bash. Typing thedelayed suspend character (typically ^Y, Control-Y) causes the process to be stopped when it attempts to read input from the termi‐nal, and control to be returned to bash. The user may then manipulate the state of this job, using the bg command to continue it inthe background, the fg command to continue it in the foreground, or the kill command to kill it. A ^Z takes effect immediately, andhas the additional side effect of causing pending output and typeahead to be discarded.There are a number of ways to refer to a job in the shell. The character % introduces a job specification (jobspec). Job number nmay be referred to as %n. A job may also be referred to using a prefix of the name used to start it, or using a substring thatappears in its command line. For example, %ce refers to a stopped ce job. If a prefix matches more than one job, bash reports anerror. Using %?ce, on the other hand, refers to any job containing the string ce in its command line. If the substring matches morethan one job, bash reports an error. The symbols %% and %+ refer to the shell's notion of the current job, which is the last jobstopped while it was in the foreground or started in the background. The previous job may be referenced using %-. If there is onlya single job, %+ and %- can both be used to refer to that job. In output pertaining to jobs (e.g., the output of the jobs command),the current job is always flagged with a +, and the previous job with a -. A single % (with no accompanying job specification) alsorefers to the current job.Simply naming a job can be used to bring it into the foreground: %1 is a synonym for ``fg %1'', bringing job 1 from the backgroundinto the foreground. Similarly, ``%1 &'' resumes job 1 in the background, equivalent to ``bg %1''.The shell learns immediately whenever a job changes state. Normally, bash waits until it is about to print a prompt before reportingchanges in a job's status so as to not interrupt any other output. If the -b option to the set builtin command is enabled, bashreports such changes immediately. Any trap on SIGCHLD is executed for each child that exits.If an attempt to exit bash is made while jobs are stopped (or, if the checkjobs shell option has been enabled using the shoptbuiltin, running), the shell prints a warning message, and, if the checkjobs option is enabled, lists the jobs and their statuses.The jobs command may then be used to inspect their status. If a second attempt to exit is made without an intervening command, theshell does not print another warning, and any stopped jobs are terminated.PROMPTINGWhen executing interactively, bash displays the primary prompt PS1 when it is ready to read a command, and the secondary prompt PS2when it needs more input to complete a command. Bash displays PS0 after it reads a command but before executing it. Bash allowsthese prompt strings to be customized by inserting a number of backslash-escaped special characters that are decoded as follows:\a an ASCII bell character (07)\d the date in "Weekday Month Date" format (e.g., "Tue May 26")\D{format}the format is passed to strftime(3) and the result is inserted into the prompt string; an empty format results in alocale-specific time representation. The braces are required\e an ASCII escape character (033)\h the hostname up to the first `.'\H the hostname\j the number of jobs currently managed by the shell\l the basename of the shell's terminal device name\n newline\r carriage return\s the name of the shell, the basename of $0 (the portion following the final slash)\t the current time in 24-hour HH:MM:SS format\T the current time in 12-hour HH:MM:SS format\@ the current time in 12-hour am/pm format\A the current time in 24-hour HH:MM format\u the username of the current user\v the version of bash (e.g., 2.00)\V the release of bash, version + patch level (e.g., 2.00.0)\w the current working directory, with $HOME abbreviated with a tilde (uses the value of the PROMPT_DIRTRIM variable)\W the basename of the current working directory, with $HOME abbreviated with a tilde\! the history number of this command\# the command number of this command\$ if the effective UID is 0, a #, otherwise a $\nnn the character corresponding to the octal number nnn\\ a backslash\[ begin a sequence of non-printing characters, which could be used to embed a terminal control sequence into the prompt\] end a sequence of non-printing charactersThe command number and the history number are usually different: the history number of a command is its position in the history list,which may include commands restored from the history file (see HISTORY below), while the command number is the position in thesequence of commands executed during the current shell session. After the string is decoded, it is expanded via parameter expansion,command substitution, arithmetic expansion, and quote removal, subject to the value of the promptvars shell option (see the descrip‐tion of the shopt command under SHELL BUILTIN COMMANDS below).READLINEThis is the library that handles reading input when using an interactive shell, unless the --noediting option is given at shell invo‐cation. Line editing is also used when using the -e option to the read builtin. By default, the line editing commands are similarto those of Emacs. A vi-style line editing interface is also available. Line editing can be enabled at any time using the -o emacsor -o vi options to the set builtin (see SHELL BUILTIN COMMANDS below). To turn off line editing after the shell is running, use the+o emacs or +o vi options to the set builtin.Readline NotationIn this section, the Emacs-style notation is used to denote keystrokes. Control keys are denoted by C-key, e.g., C-n means Con‐trol-N. Similarly, meta keys are denoted by M-key, so M-x means Meta-X. (On keyboards without a meta key, M-x means ESC x, i.e.,press the Escape key then the x key. This makes ESC the meta prefix. The combination M-C-x means ESC-Control-x, or press the Escapekey then hold the Control key while pressing the x key.)Readline commands may be given numeric arguments, which normally act as a repeat count. Sometimes, however, it is the sign of theargument that is significant. Passing a negative argument to a command that acts in the forward direction (e.g., kill-line) causesthat command to act in a backward direction. Commands whose behavior with arguments deviates from this are noted below.When a command is described as killing text, the text deleted is saved for possible future retrieval (yanking). The killed text issaved in a kill ring. Consecutive kills cause the text to be accumulated into one unit, which can be yanked all at once. Commandswhich do not kill text separate the chunks of text on the kill ring.Readline InitializationReadline is customized by putting commands in an initialization file (the inputrc file). The name of this file is taken from thevalue of the INPUTRC variable. If that variable is unset, the default is ~/.inputrc. When a program which uses the readline librarystarts up, the initialization file is read, and the key bindings and variables are set. There are only a few basic constructsallowed in the readline initialization file. Blank lines are ignored. Lines beginning with a # are comments. Lines beginning witha $ indicate conditional constructs. Other lines denote key bindings and variable settings.The default key-bindings may be changed with an inputrc file. Other programs that use this library may add their own commands andbindings.For example, placing
bash -n ...
-Meta-u:
into the inputrc would make M-C-u execute the readline command universal-argument.The following symbolic character names are recognized: RUBOUT, DEL, ESC, LFD, NEWLINE, RET, RETURN, SPC, SPACE, and TAB.In addition to command names, readline allows keys to be bound to a string that is inserted when the key is pressed (a macro).Readline Key BindingsThe syntax for controlling key bindings in the inputrc file is simple. All that is required is the name of the command or the textof a macro and a key sequence to which it should be bound. The name may be specified in one of two ways: as a symbolic key name,possibly with Meta- or Control- prefixes, or as a key sequence.When using the form keyname:function-name or macro, keyname is the name of a key spelled out in English. For example:Control-u: universal-argumentMeta-Rubout: backward-kill-wordControl-o: "> output"In the above example, C-u is bound to the function universal-argument, M-DEL is bound to the function backward-kill-word, and C-o isbound to run the macro expressed on the right hand side (that is, to insert the text ``> output'' into the line).In the second form, "keyseq":function-name or macro, keyseq differs from keyname above in that strings denoting an entire keysequence may be specified by placing the sequence within double quotes. Some GNU Emacs style key escapes can be used, as in the fol‐lowing example, but the symbolic character names are not recognized."\C-u": universal-argument"\C-x\C-r": re-read-init-file"\e[11~": "Function Key 1"In this example, C-u is again bound to the function universal-argument. C-x C-r is bound to the function re-read-init-file, and ESC[ 1 1 ~ is bound to insert the text ``Function Key 1''.The full set of GNU Emacs style escape sequences is\C- control prefix\M- meta prefix\e an escape character\\ backslash\" literal "\' literal 'In addition to the GNU Emacs style escape sequences, a second set of backslash escapes is available:\a alert (bell)\b backspace\d delete\f form feed\n newline\r carriage return\t horizontal tab\v vertical tab\nnn the eight-bit character whose value is the octal value nnn (one to three digits)\xHH the eight-bit character whose value is the hexadecimal value HH (one or two hex digits)When entering the text of a macro, single or double quotes must be used to indicate a macro definition. Unquoted text is assumed tobe a function name. In the macro body, the backslash escapes described above are expanded. Backslash will quote any other characterin the macro text, including " and '.Bash allows the current readline key bindings to be displayed or modified with the bind builtin command. The editing mode may beswitched during interactive use by using the -o option to the set builtin command (see SHELL BUILTIN COMMANDS below).Readline VariablesReadline has variables that can be used to further customize its behavior. A variable may be set in the inputrc file with a state‐ment of the formset variable-name valueExcept where noted, readline variables can take the values On or Off (without regard to case). Unrecognized variable names areignored. When a variable value is read, empty or null values, "on" (case-insensitive), and "1" are equivalent to On. All other val‐ues are equivalent to Off. The variables and their default values are:bell-style (audible)Controls what happens when readline wants to ring the terminal bell. If set to none, readline never rings the bell. If setto visible, readline uses a visible bell if one is available. If set to audible, readline attempts to ring the terminal'sbell.bind-tty-special-chars (On)If set to On, readline attempts to bind the control characters treated specially by the kernel's terminal driver to theirreadline equivalents.blink-matching-paren (Off)If set to On, readline attempts to briefly move the cursor to an opening parenthesis when a closing parenthesis is inserted.colored-completion-prefix (Off)If set to On, when listing completions, readline displays the common prefix of the set of possible completions using a differ‐ent color. The color definitions are taken from the value of the LS_COLORS environment variable.colored-stats (Off)If set to On, readline displays possible completions using different colors to indicate their file type. The color defini‐tions are taken from the value of the LS_COLORS environment variable.comment-begin (``#'')The string that is inserted when the readline insert-comment command is executed. This command is bound to M-# in emacs modeand to # in vi command mode.completion-display-width (-1)The number of screen columns used to display possible matches when performing completion. The value is ignored if it is lessthan 0 or greater than the terminal screen width. A value of 0 will cause matches to be displayed one per line. The defaultvalue is -1.completion-ignore-case (Off)If set to On, readline performs filename matching and completion in a case-insensitive fashion.completion-map-case (Off)If set to On, and completion-ignore-case is enabled, readline treats hyphens (-) and underscores (_) as equivalent when per‐forming case-insensitive filename matching and completion.completion-prefix-display-length (0)The length in characters of the common prefix of a list of possible completions that is displayed without modification. Whenset to a value greater than zero, common prefixes longer than this value are replaced with an ellipsis when displaying possi‐ble completions.completion-query-items (100)This determines when the user is queried about viewing the number of possible completions generated by the possible-comple‐tions command. It may be set to any integer value greater than or equal to zero. If the number of possible completions isgreater than or equal to the value of this variable, the user is asked whether or not he wishes to view them; otherwise theyare simply listed on the terminal.convert-meta (On)If set to On, readline will convert characters with the eighth bit set to an ASCII key sequence by stripping the eighth bitand prefixing an escape character (in effect, using escape as the meta prefix). The default is On, but readline will set itto Off if the locale contains eight-bit characters.disable-completion (Off)If set to On, readline will inhibit word completion. Completion characters will be inserted into the line as if they had beenmapped to self-insert.echo-control-characters (On)When set to On, on operating systems that indicate they support it, readline echoes a character corresponding to a signal gen‐erated from the keyboard.editing-mode (emacs)Controls whether readline begins with a set of key bindings similar to Emacs or vi. editing-mode can be set to either emacsor vi.enable-bracketed-paste (Off)When set to On, readline will configure the terminal in a way that will enable it to insert each paste into the editing bufferas a single string of characters, instead of treating each character as if it had been read from the keyboard. This can pre‐vent pasted characters from being interpreted as editing commands.enable-keypad (Off)When set to On, readline will try to enable the application keypad when it is called. Some systems need this to enable thearrow keys.enable-meta-key (On)When set to On, readline will try to enable any meta modifier key the terminal claims to support when it is called. On manyterminals, the meta key is used to send eight-bit characters.expand-tilde (Off)If set to On, tilde expansion is performed when readline attempts word completion.history-preserve-point (Off)If set to On, the history code attempts to place point at the same location on each history line retrieved with previous-his‐tory or next-history.history-size (unset)Set the maximum number of history entries saved in the history list. If set to zero, any existing history entries are deletedand no new entries are saved. If set to a value less than zero, the number of history entries is not limited. By default,the number of history entries is set to the value of the HISTSIZE shell variable. If an attempt is made to set history-sizeto a non-numeric value, the maximum number of history entries will be set to 500.horizontal-scroll-mode (Off)When set to On, makes readline use a single line for display, scrolling the input horizontally on a single screen line when itbecomes longer than the screen width rather than wrapping to a new line.input-meta (Off)If set to On, readline will enable eight-bit input (that is, it will not strip the eighth bit from the characters it reads),regardless of what the terminal claims it can support. The name meta-flag is a synonym for this variable. The default isOff, but readline will set it to On if the locale contains eight-bit characters.isearch-terminators (``C-[C-J'')The string of characters that should terminate an incremental search without subsequently executing the character as a com‐mand. If this variable has not been given a value, the characters ESC and C-J will terminate an incremental search.keymap (emacs)Set the current readline keymap. The set of valid keymap names is emacs, emacs-standard, emacs-meta, emacs-ctlx, vi, vi-com‐mand, and vi-insert. vi is equivalent to vi-command; emacs is equivalent to emacs-standard. The default value is emacs; thevalue of editing-mode also affects the default keymap.emacs-mode-string (@)This string is displayed immediately before the last line of the primary prompt when emacs editing mode is active. The valueis expanded like a key binding, so the standard set of meta- and control prefixes and backslash escape sequences is available.Use the \1 and \2 escapes to begin and end sequences of non-printing characters, which can be used to embed a terminal controlsequence into the mode string.keyseq-timeout (500)Specifies the duration readline will wait for a character when reading an ambiguous key sequence (one that can form a completekey sequence using the input read so far, or can take additional input to complete a longer key sequence). If no input isreceived within the timeout, readline will use the shorter but complete key sequence. The value is specified in milliseconds,so a value of 1000 means that readline will wait one second for additional input. If this variable is set to a value lessthan or equal to zero, or to a non-numeric value, readline will wait until another key is pressed to decide which key sequenceto complete.mark-directories (On)If set to On, completed directory names have a slash appended.mark-modified-lines (Off)If set to On, history lines that have been modified are displayed with a preceding asterisk (*).mark-symlinked-directories (Off)If set to On, completed names which are symbolic links to directories have a slash appended (subject to the value ofmark-directories).match-hidden-files (On)This variable, when set to On, causes readline to match files whose names begin with a `.' (hidden files) when performingfilename completion. If set to Off, the leading `.' must be supplied by the user in the filename to be completed.menu-complete-display-prefix (Off)If set to On, menu completion displays the common prefix of the list of possible completions (which may be empty) beforecycling through the list.output-meta (Off)If set to On, readline will display characters with the eighth bit set directly rather than as a meta-prefixed escapesequence. The default is Off, but readline will set it to On if the locale contains eight-bit characters.page-completions (On)If set to On, readline uses an internal more-like pager to display a screenful of possible completions at a time.print-completions-horizontally (Off)If set to On, readline will display completions with matches sorted horizontally in alphabetical order, rather than down thescreen.revert-all-at-newline (Off)If set to On, readline will undo all changes to history lines before returning when accept-line is executed. By default, his‐tory lines may be modified and retain individual undo lists across calls to readline.show-all-if-ambiguous (Off)This alters the default behavior of the completion functions. If set to On, words which have more than one possible comple‐tion cause the matches to be listed immediately instead of ringing the bell.show-all-if-unmodified (Off)This alters the default behavior of the completion functions in a fashion similar to show-all-if-ambiguous. If set to On,words which have more than one possible completion without any possible partial completion (the possible completions don'tshare a common prefix) cause the matches to be listed immediately instead of ringing the bell.show-mode-in-prompt (Off)If set to On, add a character to the beginning of the prompt indicating the editing mode: emacs (@), vi command (:) or viinsertion (+).skip-completed-text (Off)If set to On, this alters the default completion behavior when inserting a single match into the line. It's only active whenperforming completion in the middle of a word. If enabled, readline does not insert characters from the completion that matchcharacters after point in the word being completed, so portions of the word following the cursor are not duplicated.vi-cmd-mode-string ((cmd))This string is displayed immediately before the last line of the primary prompt when vi editing mode is active and in commandmode. The value is expanded like a key binding, so the standard set of meta- and control prefixes and backslash escapesequences is available. Use the \1 and \2 escapes to begin and end sequences of non-printing characters, which can be used toembed a terminal control sequence into the mode string.vi-ins-mode-string ((ins))This string is displayed immediately before the last line of the primary prompt when vi editing mode is active and in inser‐tion mode. The value is expanded like a key binding, so the standard set of meta- and control prefixes and backslash escapesequences is available. Use the \1 and \2 escapes to begin and end sequences of non-printing characters, which can be used toembed a terminal control sequence into the mode string.visible-stats (Off)If set to On, a character denoting a file's type as reported by stat(2) is appended to the filename when listing possible com‐pletions.Readline Conditional ConstructsReadline implements a facility similar in spirit to the conditional compilation features of the C preprocessor which allows key bind‐ings and variable settings to be performed as the result of tests. There are four parser directives used.$if The $if construct allows bindings to be made based on the editing mode, the terminal being used, or the application usingreadline. The text of the test extends to the end of the line; no characters are required to isolate it.mode The mode= form of the $if directive is used to test whether readline is in emacs or vi mode. This may be used in con‐junction with the set keymap command, for instance, to set bindings in the emacs-standard and emacs-ctlx keymaps onlyif readline is starting out in emacs mode.term The term= form may be used to include terminal-specific key bindings, perhaps to bind the key sequences output by theterminal's function keys. The word on the right side of the = is tested against both the full name of the terminal andthe portion of the terminal name before the first -. This allows sun to match both sun and sun-cmd, for instance.applicationThe application construct is used to include application-specific settings. Each program using the readline librarysets the application name, and an initialization file can test for a particular value. This could be used to bind keysequences to functions useful for a specific program. For instance, the following command adds a key sequence thatquotes the current or previous word in bash:$if Bash# Quote the current or previous word"\C-xq": "\eb\"\ef\""$endif$endif This command, as seen in the previous example, terminates an $if command.$else Commands in this branch of the $if directive are executed if the test fails.$includeThis directive takes a single filename as an argument and reads commands and bindings from that file. For example, the fol‐lowing directive would read /etc/inputrc:$include /etc/inputrcSearchingReadline provides commands for searching through the command history (see HISTORY below) for lines containing a specified string.There are two search modes: incremental and non-incremental.Incremental searches begin before the user has finished typing the search string. As each character of the search string is typed,readline displays the next entry from the history matching the string typed so far. An incremental search requires only as manycharacters as needed to find the desired history entry. The characters present in the value of the isearch-terminators variable areused to terminate an incremental search. If that variable has not been assigned a value the Escape and Control-J characters willterminate an incremental search. Control-G will abort an incremental search and restore the original line. When the search is ter‐minated, the history entry containing the search string becomes the current line.To find other matching entries in the history list, type Control-S or Control-R as appropriate. This will search backward or forwardin the history for the next entry matching the search string typed so far. Any other key sequence bound to a readline command willterminate the search and execute that command. For instance, a newline will terminate the search and accept the line, thereby exe‐cuting the command from the history list.Readline remembers the last incremental search string. If two Control-Rs are typed without any intervening characters defining a newsearch string, any remembered search string is used.Non-incremental searches read the entire search string before starting to search for matching history lines. The search string maybe typed by the user or be part of the contents of the current line.Readline Command NamesThe following is a list of the names of the commands and the default key sequences to which they are bound. Command names without anaccompanying key sequence are unbound by default. In the following descriptions, point refers to the current cursor position, andmark refers to a cursor position saved by the set-mark command. The text between the point and mark is referred to as the region.Commands for Movingbeginning-of-line (C-a)Move to the start of the current line.end-of-line (C-e)Move to the end of the line.forward-char (C-f)Move forward a character.backward-char (C-b)Move back a character.forward-word (M-f)Move forward to the end of the next word. Words are composed of alphanumeric characters (letters and digits).backward-word (M-b)Move back to the start of the current or previous word. Words are composed of alphanumeric characters (letters and digits).shell-forward-wordMove forward to the end of the next word. Words are delimited by non-quoted shell metacharacters.shell-backward-wordMove back to the start of the current or previous word. Words are delimited by non-quoted shell metacharacters.clear-screen (C-l)Clear the screen leaving the current line at the top of the screen. With an argument, refresh the current line without clear‐ing the screen.redraw-current-lineRefresh the current line.Commands for Manipulating the Historyaccept-line (Newline, Return)Accept the line regardless of where the cursor is. If this line is non-empty, add it to the history list according to thestate of the HISTCONTROL variable. If the line is a modified history line, then restore the history line to its originalstate.previous-history (C-p)Fetch the previous command from the history list, moving back in the list.next-history (C-n)Fetch the next command from the history list, moving forward in the list.beginning-of-history (M-<)Move to the first line in the history.end-of-history (M->)Move to the end of the input history, i.e., the line currently being entered.reverse-search-history (C-r)Search backward starting at the current line and moving `up' through the history as necessary. This is an incremental search.forward-search-history (C-s)Search forward starting at the current line and moving `down' through the history as necessary. This is an incrementalsearch.non-incremental-reverse-search-history (M-p)Search backward through the history starting at the current line using a non-incremental search for a string supplied by theuser.non-incremental-forward-search-history (M-n)Search forward through the history using a non-incremental search for a string supplied by the user.history-search-forwardSearch forward through the history for the string of characters between the start of the current line and the point. This isa non-incremental search.history-search-backwardSearch backward through the history for the string of characters between the start of the current line and the point. This isa non-incremental search.yank-nth-arg (M-C-y)Insert the first argument to the previous command (usually the second word on the previous line) at point. With an argumentn, insert the nth word from the previous command (the words in the previous command begin with word 0). A negative argumentinserts the nth word from the end of the previous command. Once the argument n is computed, the argument is extracted as ifthe "!n" history expansion had been specified.yank-last-arg (M-., M-_)Insert the last argument to the previous command (the last word of the previous history entry). With a numeric argument,behave exactly like yank-nth-arg. Successive calls to yank-last-arg move back through the history list, inserting the lastword (or the word specified by the argument to the first call) of each line in turn. Any numeric argument supplied to thesesuccessive calls determines the direction to move through the history. A negative argument switches the direction through thehistory (back or forward). The history expansion facilities are used to extract the last word, as if the "!$" history expan‐sion had been specified.shell-expand-line (M-C-e)Expand the line as the shell does. This performs alias and history expansion as well as all of the shell word expansions.See HISTORY EXPANSION below for a description of history expansion.history-expand-line (M-^)Perform history expansion on the current line. See HISTORY EXPANSION below for a description of history expansion.magic-spacePerform history expansion on the current line and insert a space. See HISTORY EXPANSION below for a description of historyexpansion.alias-expand-linePerform alias expansion on the current line. See ALIASES above for a description of alias expansion.history-and-alias-expand-linePerform history and alias expansion on the current line.insert-last-argument (M-., M-_)A synonym for yank-last-arg.operate-and-get-next (C-o)Accept the current line for execution and fetch the next line relative to the current line from the history for editing. Anyargument is ignored.edit-and-execute-command (C-xC-e)Invoke an editor on the current command line, and execute the result as shell commands. Bash attempts to invoke $VISUAL,$EDITOR, and emacs as the editor, in that order.Commands for Changing Textend-of-file (usually C-d)The character indicating end-of-file as set, for example, by ``stty''. If this character is read when there are no characterson the line, and point is at the beginning of the line, Readline interprets it as the end of input and returns EOF.delete-char (C-d)Delete the character at point. If this function is bound to the same character as the tty EOF character, as C-d commonly is,see above for the effects.backward-delete-char (Rubout)Delete the character behind the cursor. When given a numeric argument, save the deleted text on the kill ring.forward-backward-delete-charDelete the character under the cursor, unless the cursor is at the end of the line, in which case the character behind thecursor is deleted.quoted-insert (C-q, C-v)Add the next character typed to the line verbatim. This is how to insert characters like C-q, for example.tab-insert (C-v TAB)Insert a tab character.self-insert (a, b, A, 1, !, ...)Insert the character typed.transpose-chars (C-t)Drag the character before point forward over the character at point, moving point forward as well. If point is at the end ofthe line, then this transposes the two characters before point. Negative arguments have no effect.transpose-words (M-t)Drag the word before point past the word after point, moving point over that word as well. If point is at the end of theline, this transposes the last two words on the line.upcase-word (M-u)Uppercase the current (or following) word. With a negative argument, uppercase the previous word, but do not move point.downcase-word (M-l)Lowercase the current (or following) word. With a negative argument, lowercase the previous word, but do not move point.capitalize-word (M-c)Capitalize the current (or following) word. With a negative argument, capitalize the previous word, but do not move point.overwrite-modeToggle overwrite mode. With an explicit positive numeric argument, switches to overwrite mode. With an explicit non-positivenumeric argument, switches to insert mode. This command affects only emacs mode; vi mode does overwrite differently. Eachcall to readline() starts in insert mode. In overwrite mode, characters bound to self-insert replace the text at point ratherthan pushing the text to the right. Characters bound to backward-delete-char replace the character before point with a space.By default, this command is unbound.Killing and Yankingkill-line (C-k)Kill the text from point to the end of the line.backward-kill-line (C-x Rubout)Kill backward to the beginning of the line.unix-line-discard (C-u)Kill backward from point to the beginning of the line. The killed text is saved on the kill-ring.kill-whole-lineKill all characters on the current line, no matter where point is.kill-word (M-d)Kill from point to the end of the current word, or if between words, to the end of the next word. Word boundaries are thesame as those used by forward-word.backward-kill-word (M-Rubout)Kill the word behind point. Word boundaries are the same as those used by backward-word.shell-kill-wordKill from point to the end of the current word, or if between words, to the end of the next word. Word boundaries are thesame as those used by shell-forward-word.shell-backward-kill-wordKill the word behind point. Word boundaries are the same as those used by shell-backward-word.unix-word-rubout (C-w)Kill the word behind point, using white space as a word boundary. The killed text is saved on the kill-ring.unix-filename-ruboutKill the word behind point, using white space and the slash character as the word boundaries. The killed text is saved on thekill-ring.delete-horizontal-space (M-\)Delete all spaces and tabs around point.kill-regionKill the text in the current region.copy-region-as-killCopy the text in the region to the kill buffer.copy-backward-wordCopy the word before point to the kill buffer. The word boundaries are the same as backward-word.copy-forward-wordCopy the word following point to the kill buffer. The word boundaries are the same as forward-word.yank (C-y)Yank the top of the kill ring into the buffer at point.yank-pop (M-y)Rotate the kill ring, and yank the new top. Only works following yank or yank-pop.Numeric Argumentsdigit-argument (M-0, M-1, ..., M--)Add this digit to the argument already accumulating, or start a new argument. M-- starts a negative argument.universal-argumentThis is another way to specify an argument. If this command is followed by one or more digits, optionally with a leadingminus sign, those digits define the argument. If the command is followed by digits, executing universal-argument again endsthe numeric argument, but is otherwise ignored. As a special case, if this command is immediately followed by a characterthat is neither a digit nor minus sign, the argument count for the next command is multiplied by four. The argument count isinitially one, so executing this function the first time makes the argument count four, a second time makes the argument countsixteen, and so on.Completingcomplete (TAB)Attempt to perform completion on the text before point. Bash attempts completion treating the text as a variable (if the textbegins with $), username (if the text begins with ~), hostname (if the text begins with @), or command (including aliases andfunctions) in turn. If none of these produces a match, filename completion is attempted.possible-completions (M-?)List the possible completions of the text before point.insert-completions (M-*)Insert all completions of the text before point that would have been generated by possible-completions.menu-completeSimilar to complete, but replaces the word to be completed with a single match from the list of possible completions.Repeated execution of menu-complete steps through the list of possible completions, inserting each match in turn. At the endof the list of completions, the bell is rung (subject to the setting of bell-style) and the original text is restored. Anargument of n moves n positions forward in the list of matches; a negative argument may be used to move backward through thelist. This command is intended to be bound to TAB, but is unbound by default.menu-complete-backwardIdentical to menu-complete, but moves backward through the list of possible completions, as if menu-complete had been given anegative argument. This command is unbound by default.delete-char-or-listDeletes the character under the cursor if not at the beginning or end of the line (like delete-char). If at the end of theline, behaves identically to possible-completions. This command is unbound by default.complete-filename (M-/)Attempt filename completion on the text before point.possible-filename-completions (C-x /)List the possible completions of the text before point, treating it as a filename.complete-username (M-~)Attempt completion on the text before point, treating it as a username.possible-username-completions (C-x ~)List the possible completions of the text before point, treating it as a username.complete-variable (M-$)Attempt completion on the text before point, treating it as a shell variable.possible-variable-completions (C-x $)List the possible completions of the text before point, treating it as a shell variable.complete-hostname (M-@)Attempt completion on the text before point, treating it as a hostname.possible-hostname-completions (C-x @)List the possible completions of the text before point, treating it as a hostname.complete-command (M-!)Attempt completion on the text before point, treating it as a command name. Command completion attempts to match the textagainst aliases, reserved words, shell functions, shell builtins, and finally executable filenames, in that order.possible-command-completions (C-x !)List the possible completions of the text before point, treating it as a command name.dynamic-complete-history (M-TAB)Attempt completion on the text before point, comparing the text against lines from the history list for possible completionmatches.dabbrev-expandAttempt menu completion on the text before point, comparing the text against lines from the history list for possible comple‐tion matches.complete-into-braces (M-{)Perform filename completion and insert the list of possible completions enclosed within braces so the list is available to theshell (see Brace Expansion above).Keyboard Macrosstart-kbd-macro (C-x ()Begin saving the characters typed into the current keyboard macro.end-kbd-macro (C-x ))Stop saving the characters typed into the current keyboard macro and store the definition.call-last-kbd-macro (C-x e)Re-execute the last keyboard macro defined, by making the characters in the macro appear as if typed at the keyboard.print-last-kbd-macro ()Print the last keyboard macro defined in a format suitable for the inputrc file.Miscellaneousre-read-init-file (C-x C-r)Read in the contents of the inputrc file, and incorporate any bindings or variable assignments found there.abort (C-g)Abort the current editing command and ring the terminal's bell (subject to the setting of bell-style).do-uppercase-version (M-a, M-b, M-x, ...)If the metafied character x is lowercase, run the command that is bound to the corresponding uppercase character.prefix-meta (ESC)Metafy the next character typed. ESC f is equivalent to Meta-f.undo (C-_, C-x C-u)Incremental undo, separately remembered for each line.revert-line (M-r)Undo all changes made to this line. This is like executing the undo command enough times to return the line to its initialstate.tilde-expand (M-&)Perform tilde expansion on the current word.set-mark (C-@, M-<space>)Set the mark to the point. If a numeric argument is supplied, the mark is set to that position.exchange-point-and-mark (C-x C-x)Swap the point with the mark. The current cursor position is set to the saved position, and the old cursor position is savedas the mark.character-search (C-])A character is read and point is moved to the next occurrence of that character. A negative count searches for previousoccurrences.character-search-backward (M-C-])A character is read and point is moved to the previous occurrence of that character. A negative count searches for subsequentoccurrences.skip-csi-sequenceRead enough characters to consume a multi-key sequence such as those defined for keys like Home and End. Such sequences beginwith a Control Sequence Indicator (CSI), usually ESC-[. If this sequence is bound to "\[", keys producing such sequences willhave no effect unless explicitly bound to a readline command, instead of inserting stray characters into the editing buffer.This is unbound by default, but usually bound to ESC-[.insert-comment (M-#)Without a numeric argument, the value of the readline comment-begin variable is inserted at the beginning of the current line.If a numeric argument is supplied, this command acts as a toggle: if the characters at the beginning of the line do not matchthe value of comment-begin, the value is inserted, otherwise the characters in comment-begin are deleted from the beginning ofthe line. In either case, the line is accepted as if a newline had been typed. The default value of comment-begin causesthis command to make the current line a shell comment. If a numeric argument causes the comment character to be removed, theline will be executed by the shell.glob-complete-word (M-g)The word before point is treated as a pattern for pathname expansion, with an asterisk implicitly appended. This pattern isused to generate a list of matching filenames for possible completions.glob-expand-word (C-x *)The word before point is treated as a pattern for pathname expansion, and the list of matching filenames is inserted, replac‐ing the word. If a numeric argument is supplied, an asterisk is appended before pathname expansion.glob-list-expansions (C-x g)The list of expansions that would have been generated by glob-expand-word is displayed, and the line is redrawn. If a numericargument is supplied, an asterisk is appended before pathname expansion.dump-functionsPrint all of the functions and their key bindings to the readline output stream. If a numeric argument is supplied, the out‐put is formatted in such a way that it can be made part of an inputrc file.dump-variablesPrint all of the settable readline variables and their values to the readline output stream. If a numeric argument is sup‐plied, the output is formatted in such a way that it can be made part of an inputrc file.dump-macrosPrint all of the readline key sequences bound to macros and the strings they output. If a numeric argument is supplied, theoutput is formatted in such a way that it can be made part of an inputrc file.display-shell-version (C-x C-v)Display version information about the current instance of bash.Programmable CompletionWhen word completion is attempted for an argument to a command for which a completion specification (a compspec) has been definedusing the complete builtin (see SHELL BUILTIN COMMANDS below), the programmable completion facilities are invoked.First, the command name is identified. If the command word is the empty string (completion attempted at the beginning of an emptyline), any compspec defined with the -E option to complete is used. If a compspec has been defined for that command, the compspec isused to generate the list of possible completions for the word. If the command word is a full pathname, a compspec for the fullpathname is searched for first. If no compspec is found for the full pathname, an attempt is made to find a compspec for the portionfollowing the final slash. If those searches do not result in a compspec, any compspec defined with the -D option to complete isused as the default.Once a compspec has been found, it is used to generate the list of matching words. If a compspec is not found, the default bash com‐pletion as described above under Completing is performed.First, the actions specified by the compspec are used. Only matches which are prefixed by the word being completed are returned.When the -f or -d option is used for filename or directory name completion, the shell variable FIGNORE is used to filter the matches.Any completions specified by a pathname expansion pattern to the -G option are generated next. The words generated by the patternneed not match the word being completed. The GLOBIGNORE shell variable is not used to filter the matches, but the FIGNORE variableis used.Next, the string specified as the argument to the -W option is considered. The string is first split using the characters in the IFSspecial variable as delimiters. Shell quoting is honored. Each word is then expanded using brace expansion, tilde expansion, param‐eter and variable expansion, command substitution, and arithmetic expansion, as described above under EXPANSION. The results aresplit using the rules described above under Word Splitting. The results of the expansion are prefix-matched against the word beingcompleted, and the matching words become the possible completions.After these matches have been generated, any shell function or command specified with the -F and -C options is invoked. When thecommand or function is invoked, the COMP_LINE, COMP_POINT, COMP_KEY, and COMP_TYPE variables are assigned values as described aboveunder Shell Variables. If a shell function is being invoked, the COMP_WORDS and COMP_CWORD variables are also set. When the func‐tion or command is invoked, the first argument ($1) is the name of the command whose arguments are being completed, the second argu‐ment ($2) is the word being completed, and the third argument ($3) is the word preceding the word being completed on the current com‐mand line. No filtering of the generated completions against the word being completed is performed; the function or command has com‐plete freedom in generating the matches.Any function specified with -F is invoked first. The function may use any of the shell facilities, including the compgen builtindescribed below, to generate the matches. It must put the possible completions in the COMPREPLY array variable, one per array ele‐ment.Next, any command specified with the -C option is invoked in an environment equivalent to command substitution. It should print alist of completions, one per line, to the standard output. Backslash may be used to escape a newline, if necessary.After all of the possible completions are generated, any filter specified with the -X option is applied to the list. The filter is apattern as used for pathname expansion; a & in the pattern is replaced with the text of the word being completed. A literal & may beescaped with a backslash; the backslash is removed before attempting a match. Any completion that matches the pattern will beremoved from the list. A leading ! negates the pattern; in this case any completion not matching the pattern will be removed. Ifthe nocasematch shell option is enabled, the match is performed without regard to the case of alphabetic characters.Finally, any prefix and suffix specified with the -P and -S options are added to each member of the completion list, and the resultis returned to the readline completion code as the list of possible completions.If the previously-applied actions do not generate any matches, and the -o dirnames option was supplied to complete when the compspecwas defined, directory name completion is attempted.If the -o plusdirs option was supplied to complete when the compspec was defined, directory name completion is attempted and anymatches are added to the results of the other actions.By default, if a compspec is found, whatever it generates is returned to the completion code as the full set of possible completions.The default bash completions are not attempted, and the readline default of filename completion is disabled. If the -o bashdefaultoption was supplied to complete when the compspec was defined, the bash default completions are attempted if the compspec generatesno matches. If the -o default option was supplied to complete when the compspec was defined, readline's default completion will beperformed if the compspec (and, if attempted, the default bash completions) generate no matches.When a compspec indicates that directory name completion is desired, the programmable completion functions force readline to append aslash to completed names which are symbolic links to directories, subject to the value of the mark-directories readline variable,regardless of the setting of the mark-symlinked-directories readline variable.There is some support for dynamically modifying completions. This is most useful when used in combination with a default completionspecified with complete -D. It's possible for shell functions executed as completion handlers to indicate that completion should beretried by returning an exit status of 124. If a shell function returns 124, and changes the compspec associated with the command onwhich completion is being attempted (supplied as the first argument when the function is executed), programmable completion restartsfrom the beginning, with an attempt to find a new compspec for that command. This allows a set of completions to be built dynami‐cally as completion is attempted, rather than being loaded all at once.For instance, assuming that there is a library of compspecs, each kept in a file corresponding to the name of the command, the fol‐lowing default completion function would load completions dynamically:_completion_loader(){. "/etc/bash_completion.d/$1.sh" >/dev/null 2>&1 && return 124}complete -D -F _completion_loader -o bashdefault -o defaultHISTORYWhen the -o history option to the set builtin is enabled, the shell provides access to the command history, the list of commands pre‐viously typed. The value of the HISTSIZE variable is used as the number of commands to save in a history list. The text of the lastHISTSIZE commands (default 500) is saved. The shell stores each command in the history list prior to parameter and variable expan‐sion (see EXPANSION above) but after history expansion is performed, subject to the values of the shell variables HISTIGNORE andHISTCONTROL.On startup, the history is initialized from the file named by the variable HISTFILE (default ~/.bash_history). The file named by thevalue of HISTFILE is truncated, if necessary, to contain no more than the number of lines specified by the value of HISTFILESIZE. IfHISTFILESIZE is unset, or set to null, a non-numeric value, or a numeric value less than zero, the history file is not truncated.When the history file is read, lines beginning with the history comment character followed immediately by a digit are interpreted astimestamps for the preceding history line. These timestamps are optionally displayed depending on the value of the HISTTIMEFORMATvariable. When a shell with history enabled exits, the last $HISTSIZE lines are copied from the history list to $HISTFILE. If thehistappend shell option is enabled (see the description of shopt under SHELL BUILTIN COMMANDS below), the lines are appended to thehistory file, otherwise the history file is overwritten. If HISTFILE is unset, or if the history file is unwritable, the history isnot saved. If the HISTTIMEFORMAT variable is set, time stamps are written to the history file, marked with the history comment char‐acter, so they may be preserved across shell sessions. This uses the history comment character to distinguish timestamps from otherhistory lines. After saving the history, the history file is truncated to contain no more than HISTFILESIZE lines. If HISTFILESIZEis unset, or set to null, a non-numeric value, or a numeric value less than zero, the history file is not truncated.The builtin command fc (see SHELL BUILTIN COMMANDS below) may be used to list or edit and re-execute a portion of the history list.The history builtin may be used to display or modify the history list and manipulate the history file. When using command-line edit‐ing, search commands are available in each editing mode that provide access to the history list.The shell allows control over which commands are saved on the history list. The HISTCONTROL and HISTIGNORE variables may be set tocause the shell to save only a subset of the commands entered. The cmdhist shell option, if enabled, causes the shell to attempt tosave each line of a multi-line command in the same history entry, adding semicolons where necessary to preserve syntactic correct‐ness. The lithist shell option causes the shell to save the command with embedded newlines instead of semicolons. See the descrip‐tion of the shopt builtin below under SHELL BUILTIN COMMANDS for information on setting and unsetting shell options.HISTORY EXPANSIONThe shell supports a history expansion feature that is similar to the history expansion in csh. This section describes what syntaxfeatures are available. This feature is enabled by default for interactive shells, and can be disabled using the +H option to theset builtin command (see SHELL BUILTIN COMMANDS below). Non-interactive shells do not perform history expansion by default.History expansions introduce words from the history list into the input stream, making it easy to repeat commands, insert the argu‐ments to a previous command into the current input line, or fix errors in previous commands quickly.History expansion is performed immediately after a complete line is read, before the shell breaks it into words. It takes place intwo parts. The first is to determine which line from the history list to use during substitution. The second is to select portionsof that line for inclusion into the current one. The line selected from the history is the event, and the portions of that line thatare acted upon are words. Various modifiers are available to manipulate the selected words. The line is broken into words in thesame fashion as when reading input, so that several metacharacter-separated words surrounded by quotes are considered one word. His‐tory expansions are introduced by the appearance of the history expansion character, which is ! by default. Only backslash (\) andsingle quotes can quote the history expansion character, but the history expansion character is also treated as quoted if it immedi‐ately precedes the closing double quote in a double-quoted string.Several characters inhibit history expansion if found immediately following the history expansion character, even if it is unquoted:space, tab, newline, carriage return, and =. If the extglob shell option is enabled, ( will also inhibit expansion.Several shell options settable with the shopt builtin may be used to tailor the behavior of history expansion. If the histverifyshell option is enabled (see the description of the shopt builtin below), and readline is being used, history substitutions are notimmediately passed to the shell parser. Instead, the expanded line is reloaded into the readline editing buffer for further modifi‐cation. If readline is being used, and the histreedit shell option is enabled, a failed history substitution will be reloaded intothe readline editing buffer for correction. The -p option to the history builtin command may be used to see what a history expansionwill do before using it. The -s option to the history builtin may be used to add commands to the end of the history list withoutactually executing them, so that they are available for subsequent recall.The shell allows control of the various characters used by the history expansion mechanism (see the description of histchars aboveunder Shell Variables). The shell uses the history comment character to mark history timestamps when writing the history file.Event DesignatorsAn event designator is a reference to a command line entry in the history list. Unless the reference is absolute, events are rela‐tive to the current position in the history list.! Start a history substitution, except when followed by a blank, newline, carriage return, = or ( (when the extglob shell optionis enabled using the shopt builtin).!n Refer to command line n.
bash -Meta-u: ...
-y
* All of the words but the zeroth. This is a synonym for `1-$'. It is not an error to use * if there is just one word in theevent; the empty string is returned in that case.x* Abbreviates x-$.
bash -y ...
--
: [arguments]No effect; the command does nothing beyond expanding arguments and performing any specified redirections. The return statusis zero.. filename [arguments]source filename [arguments]Read and execute commands from filename in the current shell environment and return the exit status of the last command exe‐cuted from filename. If filename does not contain a slash, filenames in PATH are used to find the directory containing file‐name. The file searched for in PATH need not be executable. When bash is not in posix mode, the current directory issearched if no file is found in PATH. If the sourcepath option to the shopt builtin command is turned off, the PATH is notsearched. If any arguments are supplied, they become the positional parameters when filename is executed. Otherwise thepositional parameters are unchanged. If the -T option is enabled, source inherits any trap on DEBUG; if it is not, any DEBUGtrap string is saved and restored around the call to source, and source unsets the DEBUG trap while it executes. If -T is notset, and the sourced file changes the DEBUG trap, the new value is retained when source completes. The return status is thestatus of the last command exited within the script (0 if no commands are executed), and false if filename is not found orcannot be read.alias [-p] [name[=value] ...]Alias with no arguments or with the -p option prints the list of aliases in the form alias name=value on standard output.When arguments are supplied, an alias is defined for each name whose value is given. A trailing space in value causes thenext word to be checked for alias substitution when the alias is expanded. For each name in the argument list for which novalue is supplied, the name and value of the alias is printed. Alias returns true unless a name is given for which no aliashas been defined.bg [jobspec ...]Resume each suspended job jobspec in the background, as if it had been started with &. If jobspec is not present, the shell'snotion of the current job is used. bg jobspec returns 0 unless run when job control is disabled or, when run with job controlenabled, any specified jobspec was not found or was started without job control.bind [-m keymap] [-lpsvPSVX]bind [-m keymap] [-q function] [-u function] [-r keyseq]bind [-m keymap] -f filenamebind [-m keymap] -x keyseq:shell-commandbind [-m keymap] keyseq:function-namebind [-m keymap] keyseq:readline-commandDisplay current readline key and function bindings, bind a key sequence to a readline function or macro, or set a readlinevariable. Each non-option argument is a command as it would appear in .inputrc, but each binding or command must be passed asa separate argument; e.g., '"\C-x\C-r": re-read-init-file'. Options, if supplied, have the following meanings:
bash -- ...
-m
Use keymap as the keymap to be affected by the subsequent bindings. Acceptable keymap names are emacs, emacs-standard,emacs-meta, emacs-ctlx, vi, vi-move, vi-command, and vi-insert. vi is equivalent to vi-command (vi-move is also a syn‐onym); emacs is equivalent to emacs-standard.
bash -m ...
-P
List current readline function names and bindings.
bash -P ...
-V
List current readline variable names and values.
bash -V ...
-q
Query about which keys invoke the named function.
bash -q ...
-X
complete -pr [-DE] [name ...]Specify how arguments to each name should be completed. If the -p option is supplied, or if no options are supplied, existingcompletion specifications are printed in a way that allows them to be reused as input. The -r option removes a completionspecification for each name, or, if no names are supplied, all completion specifications. The -D option indicates that theremaining options and actions should apply to the ``default'' command completion; that is, completion attempted on a commandfor which no completion has previously been defined. The -E option indicates that the remaining options and actions shouldapply to ``empty'' command completion; that is, completion attempted on a blank line.The process of applying these completion specifications when word completion is attempted is described above under Program‐mable Completion.Other options, if specified, have the following meanings. The arguments to the -G, -W, and -X options (and, if necessary, the
bash -X ...
-A
The action may be one of the following to generate a list of possible completions:alias Alias names. May also be specified as -a.arrayvarArray variable names.binding Readline key binding names.builtin Names of shell builtin commands. May also be specified as -b.command Command names. May also be specified as -c.directoryDirectory names. May also be specified as -d.disabledNames of disabled shell builtins.enabled Names of enabled shell builtins.export Names of exported shell variables. May also be specified as -e.file File names. May also be specified as -f.functionNames of shell functions.group Group names. May also be specified as -g.helptopicHelp topics as accepted by the help builtin.hostnameHostnames, as taken from the file specified by the HOSTFILE shell variable.job Job names, if job control is active. May also be specified as -j.keyword Shell reserved words. May also be specified as -k.running Names of running jobs, if job control is active.service Service names. May also be specified as -s.setopt Valid arguments for the -o option to the set builtin.shopt Shell option names as accepted by the shopt builtin.signal Signal names.stopped Names of stopped jobs, if job control is active.user User names. May also be specified as -u.variableNames of all shell variables. May also be specified as -v.
bash -A ...
-C
command is executed in a subshell environment, and its output is used as the possible completions.
bash -C ...
-F
The shell function function is executed in the current shell environment. When the function is executed, the firstargument ($1) is the name of the command whose arguments are being completed, the second argument ($2) is the wordbeing completed, and the third argument ($3) is the word preceding the word being completed on the current commandline. When it finishes, the possible completions are retrieved from the value of the COMPREPLY array variable.
bash -F ...
-W
The wordlist is split using the characters in the IFS special variable as delimiters, and each resultant word isexpanded. The possible completions are the members of the resultant list which match the word being completed.
bash -W ...
-B
The shell performs brace expansion (see Brace Expansion above). This is on by default.
bash -B ...
-H
Enable ! style history substitution. This option is on by default when the shell is interactive.
bash -H ...
-T
If limit is given, and the -a option is not used, limit is the new value of the specified resource. 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-byteblocks; -P, -T, -b, -k, -n, and -u, which are unscaled values; and, when in Posix mode, -c and -f, which are in 512-byteincrements. The return status is 0 unless an invalid option or argument is supplied, or an error occurs while setting a newlimit.umask [-p] [-S] [mode]The user file-creation mask is set to mode. If mode begins with a digit, it is interpreted as an octal number; otherwise itis interpreted as a symbolic mode mask similar to that accepted by chmod(1). If mode is omitted, the current value of themask is printed. The -S option causes the mask to be printed in symbolic form; the default output is an octal number. If the
bash -T ...