bash shell参考文档
bash shell参考文档
- bash
- BASH(1) General Commands Manual BASH(1)
- NAME
- SYNOPSIS
- COPYRIGHT
- DESCRIPTION
- OPTIONS
- ARGUMENTS
- INVOCATION
- DEFINITIONS
- RESERVED WORDS
- SHELL GRAMMAR
- Simple Commands
- Pipelines
- Lists
- Compound Commands
- Coprocesses
- Shell Function Definitions
- COMMENTS
- QUOTING
- PARAMETERS
- Positional Parameters
- Special Parameters
- Shell Variables
- Arrays
- EXPANSION
- Brace Expansion
- Tilde Expansion
- Parameter Expansion
- Command Substitution
- Arithmetic Expansion
- Process Substitution
- Word Splitting
- Pathname Expansion
- Quote Removal
- REDIRECTION
- Redirecting Input
- Redirecting Output
- Appending Redirected Output
- Redirecting Standard Output and Standard Error
- Appending Standard Output and Standard Error
- Here Documents
- Here Strings
- READLINE
- Readline Notation
- Readline Initialization
- Readline Key Bindings
- Readline Variables
- Readline Conditional Constructs
- Searching
- Readline Command Names
- Commands for Moving
- Commands for Manipulating the History
- Commands for Changing Text
- Killing and Yanking
- Numeric Arguments
- Completing
- Keyboard Macros
- Miscellaneous
- Programmable Completion
- HISTORY
- HISTORY EXPANSION
- Event Designators
- Word Designators
- Modifiers
- SHELL BUILTIN COMMANDS
bash
BASH(1) General Commands Manual BASH(1)
NAME
bash - GNU Bourne-Again SHell
SYNOPSIS
bash [options] [command_string | file]
COPYRIGHT
Bash is Copyright (C) 1989-2016 by the Free Software Foundation, Inc.
DESCRIPTION
Bash is an sh-compatible command language interpreter that executescommands read from the standard input or from a file. Bash also incor-porates useful features from the Korn and C shells (ksh and csh).Bash is intended to be a conformant implementation of the Shell andUtilities portion of the IEEE POSIX specification (IEEE Standard1003.1). Bash can be configured to be POSIX-conformant by default.
OPTIONS
All of the single-character shell options documented in the descriptionof the set builtin command can be used as options when the shell isinvoked. In addition, bash interprets the following options when it isinvoked:-c If the -c option is present, then commands are read from thefirst non-option argument command_string. If there are argu-ments after the command_string, the first argument isassigned to $0 and any remaining arguments are assigned tothe positional parameters. The assignment to $0 sets thename of the shell, which is used in warning and error mes-sages.-i If the -i option is present, the shell is interactive.-l Make bash act as if it had been invoked as a login shell (seeINVOCATION below).-r If the -r option is present, the shell becomes restricted(see RESTRICTED SHELL below).-s If the -s option is present, or if no arguments remain afteroption processing, then commands are read from the standardinput. This option allows the positional parameters to beset when invoking an interactive shell.-v Print shell input lines as they are read.-x Print commands and their arguments as they are executed.-D A list of all double-quoted strings preceded by $ is printedon the standard output. These are the strings that are sub-ject to language translation when the current locale is not Cor POSIX. This implies the -n option; no commands will beexecuted.[-+]O [shopt_option]shopt_option is one of the shell options accepted by theshopt builtin (see SHELL BUILTIN COMMANDS below). Ifshopt_option is present, -O sets the value of that option; +Ounsets it. If shopt_option is not supplied, the names andvalues of the shell options accepted by shopt are printed onthe standard output. If the invocation option is +O, theoutput is displayed in a format that may be reused as input.-- A -- signals the end of options and disables further optionprocessing. Any arguments after the -- are treated as file-names and arguments. An argument of - is equivalent to --.Bash also interprets a number of multi-character options. Theseoptions must appear on the command line before the single-characteroptions to be recognized.--debuggerArrange for the debugger profile to be executed before the shellstarts. Turns on extended debugging mode (see the descriptionof the extdebug option to the shopt builtin below).--dump-po-stringsEquivalent to -D, but the output is in the GNU gettext po (por-table object) file format.--dump-stringsEquivalent to -D.--help Display a usage message on standard output and exit success-fully.--init-file file--rcfile fileExecute commands from file instead of the system wide initial-ization file /etc/bash.bashrc and the standard personal initial-ization file ~/.bashrc if the shell is interactive (see INVOCA-TION below).--loginEquivalent to -l.--noeditingDo not use the GNU readline library to read command lines whenthe shell is interactive.--noprofileDo not read either the system-wide startup file /etc/profile orany of the personal initialization files ~/.bash_profile,~/.bash_login, or ~/.profile. By default, bash reads thesefiles when it is invoked as a login shell (see INVOCATIONbelow).--norc Do not read and execute the system wide initialization file/etc/bash.bashrc and the personal initialization file ~/.bashrcif the shell is interactive. This option is on by default ifthe shell is invoked as sh.--posixChange the behavior of bash where the default operation differsfrom the POSIX standard to match the standard (posix mode). SeeSEE ALSO below for a reference to a document that details howposix mode affects bash's behavior.--restrictedThe shell becomes restricted (see RESTRICTED SHELL below).--verboseEquivalent to -v.--versionShow version information for this instance of bash on the stan-dard output and exit successfully.
ARGUMENTS
If arguments remain after option processing, and neither the -c nor the-s option has been supplied, the first argument is assumed to be thename of a file containing shell commands. If bash is invoked in thisfashion, $0 is set to the name of the file, and the positional parame-ters are set to the remaining arguments. Bash reads and executes com-mands from this file, then exits. Bash's exit status is the exit sta-tus of the last command executed in the script. If no commands areexecuted, the exit status is 0. An attempt is first made to open thefile in the current directory, and, if no file is found, then the shellsearches the directories in PATH for the script.
INVOCATION
A login shell is one whose first character of argument zero is a -, orone 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 standard inputand error are both connected to terminals (as determined by isatty(3)),or one started with the -i option. PS1 is set and $- includes i ifbash is interactive, allowing a shell script or a startup file to testthis state.The following paragraphs describe how bash executes its startup files.If any of the files exist but cannot be read, bash reports an error.Tildes are expanded in filenames as described below under Tilde Expan-sion in the EXPANSION section.When bash is invoked as an interactive login shell, or as a non-inter-active shell with the --login option, it first reads and executes com-mands from the file /etc/profile, if that file exists. After readingthat file, it looks for ~/.bash_profile, ~/.bash_login, and ~/.profile,in that order, and reads and executes commands from the first one thatexists and is readable. The --noprofile option may be used when theshell is started to inhibit this behavior.When an interactive login shell exits, or a non-interactive login shellexecutes the exit builtin command, bash reads and executes commandsfrom the file ~/.bash_logout, if it exists.When an interactive shell that is not a login shell is started, bashreads and executes commands from /etc/bash.bashrc and ~/.bashrc, ifthese files exist. This may be inhibited by using the --norc option.The --rcfile file option will force bash to read and execute commandsfrom file instead of /etc/bash.bashrc and ~/.bashrc.When bash is started non-interactively, to run a shell script, forexample, it looks for the variable BASH_ENV in the environment, expandsits value if it appears there, and uses the expanded value as the nameof a file to read and execute. Bash behaves as if the following com-mand were executed:if [ -n "$BASH_ENV" ]; then . "$BASH_ENV"; fibut the value of the PATH variable is not used to search for the file-name.If bash is invoked with the name sh, it tries to mimic the startupbehavior of historical versions of sh as closely as possible, whileconforming to the POSIX standard as well. When invoked as an interac-tive login shell, or a non-interactive shell with the --login option,it first attempts to read and execute commands from /etc/profile and~/.profile, in that order. The --noprofile option may be used toinhibit this behavior. When invoked as an interactive shell with thename sh, bash looks for the variable ENV, expands its value if it isdefined, and uses the expanded value as the name of a file to read andexecute. Since a shell invoked as sh does not attempt to read and exe-cute commands from any other startup files, the --rcfile option has noeffect. A non-interactive shell invoked with the name sh does notattempt to read any other startup files. When invoked as sh, bashenters posix mode after the startup files are read.When bash is started in posix mode, as with the --posix command lineoption, it follows the POSIX standard for startup files. In this mode,interactive shells expand the ENV variable and commands are read andexecuted from the file whose name is the expanded value. No otherstartup files are read.Bash attempts to determine when it is being run with its standard inputconnected to a network connection, as when executed by the remote shelldaemon, usually rshd, or the secure shell daemon sshd. If bash deter-mines it is being run in this fashion, it reads and executes commandsfrom ~/.bashrc and ~/.bashrc, if these files exist and are readable.It will not do this if invoked as sh. The --norc option may be used toinhibit this behavior, and the --rcfile option may be used to forceanother file to be read, but neither rshd nor sshd generally invoke theshell with those options or allow them to be specified.If the shell is started with the effective user (group) id not equal tothe real user (group) id, and the -p option is not supplied, no startupfiles are read, shell functions are not inherited from the environment,the SHELLOPTS, BASHOPTS, CDPATH, and GLOBIGNORE variables, if theyappear in the environment, are ignored, and the effective user id isset to the real user id. If the -p option is supplied at invocation,the startup behavior is the same, but the effective user id is notreset.
DEFINITIONS
The following definitions are used throughout the rest of this docu-ment.blank A space or tab.word A sequence of characters considered as a single unit by theshell. Also known as a token.name A word consisting only of alphanumeric characters and under-scores, and beginning with an alphabetic character or an under-score. Also referred to as an identifier.metacharacterA character that, when unquoted, separates words. One of thefollowing:| & ; ( ) < > space tab newlinecontrol operatorA token that performs a control function. It is one of the fol-lowing symbols:|| & && ; ;; ;& ;;& ( ) | |& <newline>
RESERVED WORDS
Reserved words are words that have a special meaning to the shell. Thefollowing words are recognized as reserved when unquoted and either thefirst word of a simple command (see SHELL GRAMMAR below) or the thirdword of a case or for command:! case coproc do done elif else esac fi for function if in selectthen until while { } time [[ ]]
SHELL GRAMMAR
Simple Commands
A simple command is a sequence of optional variable assignments fol-lowed by blank-separated words and redirections, and terminated by acontrol operator. The first word specifies the command to be executed,and is passed as argument zero. The remaining words are passed asarguments to the invoked command.The return value of a simple command is its exit status, or 128+n ifthe command is terminated by signal n.
Pipelines
A pipeline is a sequence of one or more commands separated by one ofthe control operators | or |&. The format for a pipeline is:[time [-p]] [ ! ] command [ [|||&] command2 ... ]The standard output of command is connected via a pipe to the standardinput of command2. This connection is performed before any redirec-tions specified by the command (see REDIRECTION below). If |& is used,command's standard error, in addition to its standard output, is con-nected to command2's standard input through the pipe; it is shorthandfor 2>&1 |. This implicit redirection of the standard error to thestandard output is performed after any redirections specified by thecommand.The return status of a pipeline is the exit status of the last command,unless the pipefail option is enabled. If pipefail is enabled, thepipeline's return status is the value of the last (rightmost) commandto exit with a non-zero status, or zero if all commands exit success-fully. If the reserved word ! precedes a pipeline, the exit status ofthat pipeline is the logical negation of the exit status as describedabove. The shell waits for all commands in the pipeline to terminatebefore returning a value.If the time reserved word precedes a pipeline, the elapsed as well asuser and system time consumed by its execution are reported when thepipeline terminates. The -p option changes the output format to thatspecified by POSIX. When the shell is in posix mode, it does not rec-ognize time as a reserved word if the next token begins with a `-'.The TIMEFORMAT variable may be set to a format string that specifieshow the timing information should be displayed; see the description ofTIMEFORMAT under Shell Variables below.When the shell is in posix mode, time may be followed by a newline. Inthis case, the shell displays the total user and system time consumedby the shell and its children. The TIMEFORMAT variable may be used tospecify the format of the time information.Each command in a pipeline is executed as a separate process (i.e., ina subshell).
Lists
A list is a sequence of one or more pipelines separated by one of theoperators ;, &, &&, or ||, and optionally terminated by one of ;, &, or<newline>.Of these list operators, && and || have equal precedence, followed by ;and &, which have equal precedence.A sequence of one or more newlines may appear in a list instead of asemicolon to delimit commands.If a command is terminated by the control operator &, the shell exe-cutes the command in the background in a subshell. The shell does notwait for the command to finish, and the return status is 0. Commandsseparated by a ; are executed sequentially; the shell waits for eachcommand to terminate in turn. The return status is the exit status ofthe last command executed.AND and OR lists are sequences of one or more pipelines separated bythe && and || control operators, respectively. AND and OR lists areexecuted with left associativity. An AND list has the formcommand1 && command2command2 is executed if, and only if, command1 returns an exit statusof zero.An OR list has the formcommand1 || command2command2 is executed if and only if command1 returns a non-zero exitstatus. The return status of AND and OR lists is the exit status ofthe last command executed in the list.
Compound Commands
A compound command is one of the following. In most cases a list in acommand's description may be separated from the rest of the command byone or more newlines, and may be followed by a newline in place of asemicolon.(list) list is executed in a subshell environment (see COMMAND EXECU-TION ENVIRONMENT below). Variable assignments and builtin com-mands that affect the shell's environment do not remain ineffect after the command completes. The return status is theexit status of list.{ list; }list is simply executed in the current shell environment. listmust be terminated with a newline or semicolon. This is knownas a group command. The return status is the exit status oflist. Note that unlike the metacharacters ( and ), { and } arereserved words and must occur where a reserved word is permittedto be recognized. Since they do not cause a word break, theymust be separated from list by whitespace or another shellmetacharacter.((expression))The expression is evaluated according to the rules describedbelow under ARITHMETIC EVALUATION. If the value of the expres-sion is non-zero, the return status is 0; otherwise the returnstatus is 1. This is exactly equivalent to let "expression".[[ expression ]]Return a status of 0 or 1 depending on the evaluation of theconditional expression expression. Expressions are composed ofthe primaries described below under CONDITIONAL EXPRESSIONS.Word splitting and pathname expansion are not performed on thewords between the [[ and ]]; tilde expansion, parameter andvariable expansion, arithmetic expansion, command substitution,process substitution, and quote removal are performed. Condi-tional operators such as -f must be unquoted to be recognized asprimaries.When used with [[, the < and > operators sort lexicographicallyusing the current locale.See the description of the test builtin command (section SHELL BUILTINCOMMANDS below) for the handling of parameters (i.e. missing parame-ters).When the == and != operators are used, the string to the right of theoperator is considered a pattern and matched according to the rulesdescribed below under Pattern Matching, as if the extglob shell optionwere enabled. The = operator is equivalent to ==. If the nocasematchshell option is enabled, the match is performed without regard to thecase of alphabetic characters. The return value is 0 if the stringmatches (==) or does not match (!=) the pattern, and 1 otherwise. Anypart of the pattern may be quoted to force the quoted portion to bematched as a string.An additional binary operator, =~, is available, with the same prece-dence as == and !=. When it is used, the string to the right of theoperator is considered an extended regular expression and matchedaccordingly (as in regex(3)). The return value is 0 if the stringmatches the pattern, and 1 otherwise. If the regular expression issyntactically incorrect, the conditional expression's return value is2. If the nocasematch shell option is enabled, the match is performedwithout regard to the case of alphabetic characters. Any part of thepattern may be quoted to force the quoted portion to be matched as astring. Bracket expressions in regular expressions must be treatedcarefully, since normal quoting characters lose their meanings betweenbrackets. If the pattern is stored in a shell variable, quoting thevariable expansion forces the entire pattern to be matched as a string.Substrings matched by parenthesized subexpressions within the regularexpression are saved in the array variable BASH_REMATCH. The elementof BASH_REMATCH with index 0 is the portion of the string matching theentire regular expression. The element of BASH_REMATCH with index n isthe portion of the string matching the nth parenthesized subexpression.Expressions may be combined using the following operators, listed indecreasing order of precedence:( expression )Returns the value of expression. This may be used tooverride the normal precedence of operators.! expressionTrue if expression is false.expression1 && expression2True if both expression1 and expression2 are true.expression1 || expression2True if either expression1 or expression2 is true.The && and || operators do not evaluate expression2 if the valueof expression1 is sufficient to determine the return value ofthe entire conditional expression.for name [ [ in [ word ... ] ] ; ] do list ; doneThe list of words following in is expanded, generating a list ofitems. The variable name is set to each element of this list inturn, and list is executed each time. If the in word is omit-ted, the for command executes list once for each positionalparameter that is set (see PARAMETERS below). The return statusis the exit status of the last command that executes. If theexpansion of the items following in results in an empty list, nocommands are executed, and the return status is 0.for (( expr1 ; expr2 ; expr3 )) ; do list ; doneFirst, the arithmetic expression expr1 is evaluated according tothe rules described below under ARITHMETIC EVALUATION. Thearithmetic expression expr2 is then evaluated repeatedly untilit evaluates to zero. Each time expr2 evaluates to a non-zerovalue, list is executed and the arithmetic expression expr3 isevaluated. If any expression is omitted, it behaves as if itevaluates to 1. The return value is the exit status of the lastcommand in list that is executed, or false if any of the expres-sions is invalid.select name [ in word ] ; do list ; doneThe list of words following in is expanded, generating a list ofitems. The set of expanded words is printed on the standarderror, each preceded by a number. If the in word is omitted,the positional parameters are printed (see PARAMETERS below).The PS3 prompt is then displayed and a line read from the stan-dard input. If the line consists of a number corresponding toone of the displayed words, then the value of name is set tothat word. If the line is empty, the words and prompt are dis-played again. If EOF is read, the command completes. Any othervalue read causes name to be set to null. The line read issaved in the variable REPLY. The list is executed after eachselection until a break command is executed. The exit status ofselect is the exit status of the last command executed in list,or zero if no commands were executed.case word in [ [(] pattern [ | pattern ] ... ) list ;; ] ... esacA case command first expands word, and tries to match it againsteach pattern in turn, using the same matching rules as for path-name expansion (see Pathname Expansion below). The word isexpanded using tilde expansion, parameter and variable expan-sion, arithmetic expansion, command substitution, process sub-stitution and quote removal. Each pattern examined is expandedusing tilde expansion, parameter and variable expansion, arith-metic expansion, command substitution, and process substitution.If the nocasematch shell option is enabled, the match is per-formed without regard to the case of alphabetic characters.When a match is found, the corresponding list is executed. Ifthe ;; operator is used, no subsequent matches are attemptedafter the first pattern match. Using ;& in place of ;; causesexecution to continue with the list associated with the next setof patterns. Using ;;& in place of ;; causes the shell to testthe next pattern list in the statement, if any, and execute anyassociated list on a successful match. The exit status is zeroif no pattern matches. Otherwise, it is the exit status of thelast command executed in list.if list; then list; [ elif list; then list; ] ... [ else list; ] fiThe if list is executed. If its exit status is zero, the thenlist is executed. Otherwise, each elif list is executed inturn, and if its exit status is zero, the corresponding thenlist is executed and the command completes. Otherwise, the elselist is executed, if present. The exit status is the exit sta-tus of the last command executed, or zero if no condition testedtrue.while list-1; do list-2; doneuntil list-1; do list-2; doneThe while command continuously executes the list list-2 as longas the last command in the list list-1 returns an exit status ofzero. The until command is identical to the while command,except that the test is negated: list-2 is executed as long asthe last command in list-1 returns a non-zero exit status. Theexit status of the while and until commands is the exit statusof the last command executed in list-2, or zero if none was exe-cuted.
Coprocesses
A coprocess is a shell command preceded by the coproc reserved word. Acoprocess is executed asynchronously in a subshell, as if the commandhad been terminated with the & control operator, with a two-way pipeestablished between the executing shell and the coprocess.The format for a coprocess is:coproc [NAME] command [redirections]This creates a coprocess named NAME. If NAME is not supplied, thedefault name is COPROC. NAME must not be supplied if command is a sim-ple command (see above); otherwise, it is interpreted as the first wordof the simple command. When the coprocess is executed, the shell cre-ates an array variable (see Arrays below) named NAME in the context ofthe executing shell. The standard output of command is connected via apipe to a file descriptor in the executing shell, and that filedescriptor is assigned to NAME[0]. The standard input of command isconnected via a pipe to a file descriptor in the executing shell, andthat file descriptor is assigned to NAME[1]. This pipe is establishedbefore any redirections specified by the command (see REDIRECTIONbelow). The file descriptors can be utilized as arguments to shellcommands and redirections using standard word expansions. The filedescriptors are not available in subshells. The process ID of theshell spawned to execute the coprocess is available as the value of thevariable NAME_PID. The wait builtin command may be used to wait forthe coprocess to terminate.Since the coprocess is created as an asynchronous command, the coproccommand always returns success. The return status of a coprocess isthe exit status of command.
Shell Function Definitions
A shell function is an object that is called like a simple command andexecutes a compound command with a new set of positional parameters.Shell functions are declared as follows:name () compound-command [redirection]function name [()] compound-command [redirection]This defines a function named name. The reserved word functionis optional. If the function reserved word is supplied, theparentheses are optional. The body of the function is the com-pound command compound-command (see Compound Commands above).That command is usually a list of commands between { and }, butmay be any command listed under Compound Commands above, withone exception: If the function reserved word is used, but theparentheses are not supplied, the braces are required. com-pound-command is executed whenever name is specified as the nameof a simple command. When in posix mode, name may not be thename of one of the POSIX special builtins. Any redirections(see REDIRECTION below) specified when a function is defined areperformed when the function is executed. The exit status of afunction definition is zero unless a syntax error occurs or areadonly function with the same name already exists. When exe-cuted, the exit status of a function is the exit status of thelast command executed in the body. (See FUNCTIONS below.)
COMMENTS
In a non-interactive shell, or an interactive shell in which the inter-active_comments option to the shopt builtin is enabled (see SHELLBUILTIN COMMANDS below), a word beginning with # causes that word andall remaining characters on that line to be ignored. An interactiveshell without the interactive_comments option enabled does not allowcomments. The interactive_comments option is on by default in interac-tive shells.
QUOTING
Quoting is used to remove the special meaning of certain characters orwords to the shell. Quoting can be used to disable special treatmentfor special characters, to prevent reserved words from being recognizedas such, and to prevent parameter expansion.Each of the metacharacters listed above under DEFINITIONS has specialmeaning to the shell and must be quoted if it is to represent itself.When the command history expansion facilities are being used (see HIS-TORY EXPANSION below), the history expansion character, usually !, mustbe quoted to prevent history expansion.There are three quoting mechanisms: the escape character, singlequotes, and double quotes.A non-quoted backslash (\) is the escape character. It preserves theliteral value of the next character that follows, with the exception of<newline>. If a \<newline> pair appears, and the backslash is notitself quoted, the \<newline> is treated as a line continuation (thatis, it is removed from the input stream and effectively ignored).Enclosing characters in single quotes preserves the literal value ofeach character within the quotes. A single quote may not occur betweensingle quotes, even when preceded by a backslash.Enclosing characters in double quotes preserves the literal value ofall characters within the quotes, with the exception of $, `, \, and,when history expansion is enabled, !. When the shell is in posix mode,the ! has no special meaning within double quotes, even when historyexpansion is enabled. The characters $ and ` retain their specialmeaning within double quotes. The backslash retains its special mean-ing only when followed by one of the following characters: $, `, ", \,or <newline>. A double quote may be quoted within double quotes bypreceding it with a backslash. If enabled, history expansion will beperformed unless an ! appearing in double quotes is escaped using abackslash. The backslash preceding the ! is not removed.The special parameters * and @ have special meaning when in doublequotes (see PARAMETERS below).Words of the form $'string' are treated specially. The word expands tostring, with backslash-escaped characters replaced as specified by theANSI C standard. Backslash escape sequences, if present, are decodedas follows:\a alert (bell)\b backspace\e\E an escape character\f form feed\n new line\r carriage return\t horizontal tab\v vertical tab\\ backslash\' single quote\" double quote\? question mark\nnn the eight-bit character whose value is the octal valuennn (one to three digits)\xHH the eight-bit character whose value is the hexadecimalvalue HH (one or two hex digits)\uHHHH the Unicode (ISO/IEC 10646) character whose value is thehexadecimal value HHHH (one to four hex digits)\UHHHHHHHHthe Unicode (ISO/IEC 10646) character whose value is thehexadecimal value HHHHHHHH (one to eight hex digits)\cx a control-x characterThe expanded result is single-quoted, as if the dollar sign had notbeen present.A double-quoted string preceded by a dollar sign ($"string") will causethe string to be translated according to the current locale. If thecurrent locale is C or POSIX, the dollar sign is ignored. If thestring is translated and replaced, the replacement is double-quoted.
PARAMETERS
A parameter is an entity that stores values. It can be a name, a num-ber, or one of the special characters listed below under Special Param-eters. A variable is a parameter denoted by a name. A variable has avalue and zero or more attributes. Attributes are assigned using thedeclare builtin command (see declare below in SHELL BUILTIN COMMANDS).A parameter is set if it has been assigned a value. The null string isa valid value. Once a variable is set, it may be unset only by usingthe unset builtin command (see SHELL BUILTIN COMMANDS below).A variable may be assigned to by a statement of the formname=[value]If value is not given, the variable is assigned the null string. Allvalues undergo tilde expansion, parameter and variable expansion, com-mand substitution, arithmetic expansion, and quote removal (see EXPAN-SION below). If the variable has its integer attribute set, then valueis evaluated as an arithmetic expression even if the $((...)) expansionis not used (see Arithmetic Expansion below). Word splitting is notperformed, with the exception of "$@" as explained below under SpecialParameters. Pathname expansion is not performed. Assignment state-ments may also appear as arguments to the alias, declare, typeset,export, readonly, and local builtin commands (declaration commands).When in posix mode, these builtins may appear in a command after one ormore instances of the command builtin and retain these assignmentstatement properties.In the context where an assignment statement is assigning a value to ashell variable or array index, the += operator can be used to append toor add to the variable's previous value. This includes arguments tobuiltin commands such as declare that accept assignment statements(declaration commands). When += is applied to a variable for which theinteger attribute has been set, value is evaluated as an arithmeticexpression and added to the variable's current value, which is alsoevaluated. When += is applied to an array variable using compoundassignment (see Arrays below), the variable's value is not unset (as itis when using =), and new values are appended to the array beginning atone greater than the array's maximum index (for indexed arrays) oradded as additional key-value pairs in an associative array. Whenapplied to a string-valued variable, value is expanded and appended tothe variable's value.A variable can be assigned the nameref attribute using the -n option tothe declare or local builtin commands (see the descriptions of declareand local below) to create a nameref, or a reference to another vari-able. This allows variables to be manipulated indirectly. Wheneverthe nameref variable is referenced, assigned to, unset, or has itsattributes modified (other than using or changing the nameref attributeitself), the operation is actually performed on the variable specifiedby the nameref variable's value. A nameref is commonly used withinshell functions to refer to a variable whose name is passed as an argu-ment to the function. For instance, if a variable name is passed to ashell function as its first argument, runningdeclare -n ref=$1inside the function creates a nameref variable ref whose value is thevariable name passed as the first argument. References and assignmentsto ref, and changes to its attributes, are treated as references,assignments, and attribute modifications to the variable whose name waspassed as $1. If the control variable in a for loop has the namerefattribute, the list of words can be a list of shell variables, and aname reference will be established for each word in the list, in turn,when the loop is executed. Array variables cannot be given the namerefattribute. However, nameref variables can reference array variablesand subscripted array variables. Namerefs can be unset using the -noption to the unset builtin. Otherwise, if unset is executed with thename of a nameref variable as an argument, the variable referenced bythe nameref variable will be unset.
Positional Parameters
A positional parameter is a parameter denoted by one or more digits,other than the single digit 0. Positional parameters are assigned fromthe shell's arguments when it is invoked, and may be reassigned usingthe set builtin command. Positional parameters may not be assigned towith assignment statements. The positional parameters are temporarilyreplaced when a shell function is executed (see FUNCTIONS below).When a positional parameter consisting of more than a single digit isexpanded, it must be enclosed in braces (see EXPANSION below).
Special Parameters
The shell treats several parameters specially. These parameters mayonly be referenced; assignment to them is not allowed.* Expands to the positional parameters, starting from one. Whenthe expansion is not within double quotes, each positionalparameter expands to a separate word. In contexts where it isperformed, those words are subject to further word splitting andpathname expansion. When the expansion occurs within doublequotes, it expands to a single word with the value of eachparameter separated by the first character of the IFS specialvariable. That is, "$*" is equivalent to "$1c$2c...", where cis the first character of the value of the IFS variable. If IFSis unset, the parameters are separated by spaces. If IFS isnull, the parameters are joined without intervening separators.@ Expands to the positional parameters, starting from one. Whenthe expansion occurs within double quotes, each parameterexpands to a separate word. That is, "$@" is equivalent to "$1""$2" ... If the double-quoted expansion occurs within a word,the expansion of the first parameter is joined with the begin-ning part of the original word, and the expansion of the lastparameter is joined with the last part of the original word.When there are no positional parameters, "$@" and $@ expand tonothing (i.e., they are removed).# Expands to the number of positional parameters in decimal.? Expands to the exit status of the most recently executed fore-ground pipeline.- Expands to the current option flags as specified upon invoca-tion, by the set builtin command, or those set by the shellitself (such as the -i option).$ Expands to the process ID of the shell. In a () subshell, itexpands to the process ID of the current shell, not the sub-shell.! Expands to the process ID of the job most recently placed intothe background, whether executed as an asynchronous command orusing the bg builtin (see JOB CONTROL below).0 Expands to the name of the shell or shell script. This is setat shell initialization. If bash is invoked with a file of com-mands, $0 is set to the name of that file. If bash is startedwith the -c option, then $0 is set to the first argument afterthe string to be executed, if one is present. Otherwise, it isset to the filename used to invoke bash, as given by argumentzero._ At shell startup, set to the absolute pathname used to invokethe shell or shell script being executed as passed in the envi-ronment or argument list. Subsequently, expands to the lastargument to the previous command, after expansion. Also set tothe full pathname used to invoke each command executed andplaced in the environment exported to that command. When check-ing mail, this parameter holds the name of the mail file cur-rently being checked.
Shell Variables
The following variables are set by the shell:BASH Expands to the full filename used to invoke this instance ofbash.BASHOPTSA colon-separated list of enabled shell options. Each word inthe list is a valid argument for the -s option to the shoptbuiltin command (see SHELL BUILTIN COMMANDS below). The optionsappearing in BASHOPTS are those reported as on by shopt. Ifthis variable is in the environment when bash starts up, eachshell option in the list will be enabled before reading anystartup files. This variable is read-only.BASHPIDExpands to the process ID of the current bash process. Thisdiffers from $$ under certain circumstances, such as subshellsthat do not require bash to be re-initialized.BASH_ALIASESAn associative array variable whose members correspond to theinternal list of aliases as maintained by the alias builtin.Elements added to this array appear in the alias list; however,unsetting array elements currently does not cause aliases to beremoved from the alias list. If BASH_ALIASES is unset, it losesits special properties, even if it is subsequently reset.BASH_ARGCAn array variable whose values are the number of parameters ineach frame of the current bash execution call stack. The numberof parameters to the current subroutine (shell function orscript executed with . or source) is at the top of the stack.When a subroutine is executed, the number of parameters passedis pushed onto BASH_ARGC. The shell sets BASH_ARGC only when inextended debugging mode (see the description of the extdebugoption to the shopt builtin below)BASH_ARGVAn array variable containing all of the parameters in the cur-rent bash execution call stack. The final parameter of the lastsubroutine call is at the top of the stack; the first parameterof the initial call is at the bottom. When a subroutine is exe-cuted, the parameters supplied are pushed onto BASH_ARGV. Theshell sets BASH_ARGV only when in extended debugging mode (seethe description of the extdebug option to the shopt builtinbelow)BASH_CMDSAn associative array variable whose members correspond to theinternal hash table of commands as maintained by the hashbuiltin. Elements added to this array appear in the hash table;however, unsetting array elements currently does not cause com-mand names to be removed from the hash table. If BASH_CMDS isunset, it loses its special properties, even if it is subse-quently reset.BASH_COMMANDThe command currently being executed or about to be executed,unless the shell is executing a command as the result of a trap,in which case it is the command executing at the time of thetrap.BASH_EXECUTION_STRINGThe command argument to the -c invocation option.BASH_LINENOAn array variable whose members are the line numbers in sourcefiles where each corresponding member of FUNCNAME was invoked.${BASH_LINENO[$i]} is the line number in the source file(${BASH_SOURCE[$i+1]}) where ${FUNCNAME[$i]} was called (or${BASH_LINENO[$i-1]} if referenced within another shell func-tion). Use LINENO to obtain the current line number.BASH_LOADABLES_PATHA colon-separated list of directories in which the shell looksfor dynamically loadable builtins specified by the enable com-mand.BASH_REMATCHAn array variable whose members are assigned by the =~ binaryoperator to the [[ conditional command. The element with index0 is the portion of the string matching the entire regularexpression. The element with index n is the portion of thestring matching the nth parenthesized subexpression. This vari-able is read-only.BASH_SOURCEAn array variable whose members are the source filenames wherethe corresponding shell function names in the FUNCNAME arrayvariable are defined. The shell function ${FUNCNAME[$i]} isdefined in the file ${BASH_SOURCE[$i]} and called from${BASH_SOURCE[$i+1]}.BASH_SUBSHELLIncremented by one within each subshell or subshell environmentwhen the shell begins executing in that environment. The ini-tial value is 0.BASH_VERSINFOA readonly array variable whose members hold version informationfor this instance of bash. The values assigned to the arraymembers are as follows:BASH_VERSINFO[0] The major version number (the release).BASH_VERSINFO[1] The minor version number (the version).BASH_VERSINFO[2] The patch level.BASH_VERSINFO[3] The build version.BASH_VERSINFO[4] The release status (e.g., beta1).BASH_VERSINFO[5] The value of MACHTYPE.BASH_VERSIONExpands to a string describing the version of this instance ofbash.COMP_CWORDAn index into ${COMP_WORDS} of the word containing the currentcursor position. This variable is available only in shell func-tions invoked by the programmable completion facilities (seeProgrammable Completion below).COMP_KEYThe key (or final key of a key sequence) used to invoke the cur-rent completion function.COMP_LINEThe current command line. This variable is available only inshell functions and external commands invoked by the program-mable completion facilities (see Programmable Completion below).COMP_POINTThe index of the current cursor position relative to the begin-ning of the current command. If the current cursor position isat the end of the current command, the value of this variable isequal to ${#COMP_LINE}. This variable is available only inshell functions and external commands invoked by the program-mable completion facilities (see Programmable Completion below).COMP_TYPESet to an integer value corresponding to the type of completionattempted that caused a completion function to be called: TAB,for normal completion, ?, for listing completions after succes-sive tabs, !, for listing alternatives on partial word comple-tion, @, to list completions if the word is not unmodified, or%, for menu completion. This variable is available only inshell functions and external commands invoked by the program-mable completion facilities (see Programmable Completion below).COMP_WORDBREAKSThe set of characters that the readline library treats as wordseparators when performing word completion. If COMP_WORDBREAKSis unset, it loses its special properties, even if it is subse-quently reset.COMP_WORDSAn array variable (see Arrays below) consisting of the individ-ual words in the current command line. The line is split intowords as readline would split it, using COMP_WORDBREAKS asdescribed above. This variable is available only in shell func-tions invoked by the programmable completion facilities (seeProgrammable Completion below).COPROC An array variable (see Arrays below) created to hold the filedescriptors for output from and input to an unnamed coprocess(see Coprocesses above).DIRSTACKAn array variable (see Arrays below) containing the current con-tents of the directory stack. Directories appear in the stackin the order they are displayed by the dirs builtin. Assigningto members of this array variable may be used to modify directo-ries already in the stack, but the pushd and popd builtins mustbe used to add and remove directories. Assignment to this vari-able will not change the current directory. If DIRSTACK isunset, it loses its special properties, even if it is subse-quently reset.EUID Expands to the effective user ID of the current user, initial-ized at shell startup. This variable is readonly.FUNCNAMEAn array variable containing the names of all shell functionscurrently in the execution call stack. The element with index 0is the name of any currently-executing shell function. The bot-tom-most element (the one with the highest index) is "main".This variable exists only when a shell function is executing.Assignments to FUNCNAME have no effect. If FUNCNAME is unset,it loses its special properties, even if it is subsequentlyreset.This variable can be used with BASH_LINENO and BASH_SOURCE.Each element of FUNCNAME has corresponding elements inBASH_LINENO and BASH_SOURCE to describe the call stack. Forinstance, ${FUNCNAME[$i]} was called from the file${BASH_SOURCE[$i+1]} at line number ${BASH_LINENO[$i]}. Thecaller builtin displays the current call stack using this infor-mation.GROUPS An array variable containing the list of groups of which thecurrent user is a member. Assignments to GROUPS have no effect.If GROUPS is unset, it loses its special properties, even if itis subsequently reset.HISTCMDThe history number, or index in the history list, of the currentcommand. If HISTCMD is unset, it loses its special properties,even if it is subsequently reset.HOSTNAMEAutomatically set to the name of the current host.HOSTTYPEAutomatically set to a string that uniquely describes the typeof machine on which bash is executing. The default is system-dependent.LINENO Each time this parameter is referenced, the shell substitutes adecimal number representing the current sequential line number(starting with 1) within a script or function. When not in ascript or function, the value substituted is not guaranteed tobe meaningful. If LINENO is unset, it loses its special proper-ties, even if it is subsequently reset.MACHTYPEAutomatically set to a string that fully describes the systemtype on which bash is executing, in the standard GNU cpu-com-pany-system format. The default is system-dependent.MAPFILEAn array variable (see Arrays below) created to hold the textread by the mapfile builtin when no variable name is supplied.OLDPWD The previous working directory as set by the cd command.OPTARG The value of the last option argument processed by the getoptsbuiltin command (see SHELL BUILTIN COMMANDS below).OPTIND The index of the next argument to be processed by the getoptsbuiltin command (see SHELL BUILTIN COMMANDS below).OSTYPE Automatically set to a string that describes the operating sys-tem on which bash is executing. The default is system-depen-dent.PIPESTATUSAn array variable (see Arrays below) containing a list of exitstatus values from the processes in the most-recently-executedforeground pipeline (which may contain only a single command).PPID The process ID of the shell's parent. This variable is read-only.PWD The current working directory as set by the cd command.RANDOM Each time this parameter is referenced, a random integer between0 and 32767 is generated. The sequence of random numbers may beinitialized by assigning a value to RANDOM. If RANDOM is unset,it loses its special properties, even if it is subsequentlyreset.READLINE_LINEThe contents of the readline line buffer, for use with "bind -x"(see SHELL BUILTIN COMMANDS below).READLINE_POINTThe position of the insertion point in the readline line buffer,for use with "bind -x" (see SHELL BUILTIN COMMANDS below).REPLY Set to the line of input read by the read builtin command whenno arguments are supplied.SECONDSEach time this parameter is referenced, the number of secondssince shell invocation is returned. If a value is assigned toSECONDS, the value returned upon subsequent references is thenumber of seconds since the assignment plus the value assigned.If SECONDS is unset, it loses its special properties, even if itis subsequently reset.SHELLOPTSA colon-separated list of enabled shell options. Each word inthe list is a valid argument for the -o option to the setbuiltin command (see SHELL BUILTIN COMMANDS below). The optionsappearing in SHELLOPTS are those reported as on by set -o. Ifthis variable is in the environment when bash starts up, eachshell option in the list will be enabled before reading anystartup files. This variable is read-only.SHLVL Incremented by one each time an instance of bash is started.UID Expands to the user ID of the current user, initialized at shellstartup. This variable is readonly.The following variables are used by the shell. In some cases, bashassigns a default value to a variable; these cases are noted below.BASH_COMPATThe value is used to set the shell's compatibility level. Seethe description of the shopt builtin below under SHELL BUILTINCOMMANDS for a description of the various compatibility levelsand their effects. The value may be a decimal number (e.g.,4.2) or an integer (e.g., 42) corresponding to the desired com-patibility level. If BASH_COMPAT is unset or set to the emptystring, the compatibility level is set to the default for thecurrent version. If BASH_COMPAT is set to a value that is notone of the valid compatibility levels, the shell prints an errormessage and sets the compatibility level to the default for thecurrent version. The valid compatibility levels correspond tothe compatibility options accepted by the shopt builtindescribed below (for example, compat42 means that 4.2 and 42 arevalid values). The current version is also a valid value.BASH_ENVIf this parameter is set when bash is executing a shell script,its value is interpreted as a filename containing commands toinitialize the shell, as in ~/.bashrc. The value of BASH_ENV issubjected to parameter expansion, command substitution, andarithmetic expansion before being interpreted as a filename.PATH is not used to search for the resultant filename.BASH_XTRACEFDIf set to an integer corresponding to a valid file descriptor,bash will write the trace output generated when set -x isenabled to that file descriptor. The file descriptor is closedwhen BASH_XTRACEFD is unset or assigned a new value. UnsettingBASH_XTRACEFD or assigning it the empty string causes the traceoutput to be sent to the standard error. Note that settingBASH_XTRACEFD to 2 (the standard error file descriptor) and thenunsetting it will result in the standard error being closed.CDPATH The search path for the cd command. This is a colon-separatedlist of directories in which the shell looks for destinationdirectories specified by the cd command. A sample value is".:~:/usr".CHILD_MAXSet the number of exited child status values for the shell toremember. Bash will not allow this value to be decreased belowa POSIX-mandated minimum, and there is a maximum value (cur-rently 8192) that this may not exceed. The minimum value issystem-dependent.COLUMNSUsed by the select compound command to determine the terminalwidth when printing selection lists. Automatically set if thecheckwinsize option is enabled or in an interactive shell uponreceipt of a SIGWINCH.COMPREPLYAn array variable from which bash reads the possible completionsgenerated by a shell function invoked by the programmable com-pletion facility (see Programmable Completion below). Eacharray element contains one possible completion.EMACS If bash finds this variable in the environment when the shellstarts with value "t", it assumes that the shell is running inan Emacs shell buffer and disables line editing.ENV Similar to BASH_ENV; used when the shell is invoked in POSIXmode.EXECIGNOREA colon-separated list of shell patterns (see Pattern Matching)defining the list of filenames to be ignored by command searchusing PATH. Files whose full pathnames match one of these pat-terns are not considered executable files for the purposes ofcompletion and command execution via PATH lookup. This does notaffect the behavior of the [, test, and [[ commands. Full path-names in the command hash table are not subject to EXECIGNORE.Use this variable to ignore shared library files that have theexecutable bit set, but are not executable files. The patternmatching honors the setting of the extglob shell option.FCEDIT The default editor for the fc builtin command.FIGNOREA colon-separated list of suffixes to ignore when performingfilename completion (see READLINE below). A filename whose suf-fix matches one of the entries in FIGNORE is excluded from thelist of matched filenames. A sample value is ".o:~" (Quoting isneeded when assigning a value to this variable, which containstildes).FUNCNESTIf set to a numeric value greater than 0, defines a maximumfunction nesting level. Function invocations that exceed thisnesting level will cause the current command to abort.GLOBIGNOREA colon-separated list of patterns defining the set of filenamesto be ignored by pathname expansion. If a filename matched by apathname expansion pattern also matches one of the patterns inGLOBIGNORE, it is removed from the list of matches.HISTCONTROLA colon-separated list of values controlling how commands aresaved on the history list. If the list of values includesignorespace, lines which begin with a space character are notsaved in the history list. A value of ignoredups causes linesmatching the previous history entry to not be saved. A value ofignoreboth is shorthand for ignorespace and ignoredups. A valueof erasedups causes all previous lines matching the current lineto be removed from the history list before that line is saved.Any value not in the above list is ignored. If HISTCONTROL isunset, or does not include a valid value, all lines read by theshell parser are saved on the history list, subject to the valueof HISTIGNORE. The second and subsequent lines of a multi-linecompound command are not tested, and are added to the historyregardless of the value of HISTCONTROL.HISTFILEThe name of the file in which command history is saved (see HIS-TORY below). The default value is ~/.bash_history. If unset,the command history is not saved when a shell exits.HISTFILESIZEThe maximum number of lines contained in the history file. Whenthis variable is assigned a value, the history file is trun-cated, if necessary, to contain no more than that number oflines by removing the oldest entries. The history file is alsotruncated to this size after writing it when a shell exits. Ifthe value is 0, the history file is truncated to zero size.Non-numeric values and numeric values less than zero inhibittruncation. The shell sets the default value to the value ofHISTSIZE after reading any startup files.HISTIGNOREA colon-separated list of patterns used to decide which commandlines should be saved on the history list. Each pattern isanchored at the beginning of the line and must match the com-plete line (no implicit `*' is appended). Each pattern istested against the line after the checks specified by HISTCON-TROL are applied. In addition to the normal shell patternmatching characters, `&' matches the previous history line. `&'may be escaped using a backslash; the backslash is removedbefore attempting a match. The second and subsequent lines of amulti-line compound command are not tested, and are added to thehistory regardless of the value of HISTIGNORE. The patternmatching honors the setting of the extglob shell option.HISTSIZEThe number of commands to remember in the command history (seeHISTORY below). If the value is 0, commands are not saved inthe history list. Numeric values less than zero result in everycommand being saved on the history list (there is no limit).The shell sets the default value to 500 after reading anystartup files.HISTTIMEFORMATIf this variable is set and not null, its value is used as aformat string for strftime(3) to print the time stamp associatedwith each history entry displayed by the history builtin. Ifthis variable is set, time stamps are written to the historyfile so they may be preserved across shell sessions. This usesthe history comment character to distinguish timestamps fromother history lines.HOME The home directory of the current user; the default argument forthe cd builtin command. The value of this variable is also usedwhen performing tilde expansion.HOSTFILEContains the name of a file in the same format as /etc/hoststhat should be read when the shell needs to complete a hostname.The list of possible hostname completions may be changed whilethe shell is running; the next time hostname completion isattempted after the value is changed, bash adds the contents ofthe new file to the existing list. If HOSTFILE is set, but hasno value, or does not name a readable file, bash attempts toread /etc/hosts to obtain the list of possible hostname comple-tions. When HOSTFILE is unset, the hostname list is cleared.IFS The Internal Field Separator that is used for word splittingafter expansion and to split lines into words with the readbuiltin command. The default value is ``<space><tab><new-line>''.IGNOREEOFControls the action of an interactive shell on receipt of an EOFcharacter as the sole input. If set, the value is the number ofconsecutive EOF characters which must be typed as the firstcharacters on an input line before bash exits. If the variableexists but does not have a numeric value, or has no value, thedefault value is 10. If it does not exist, EOF signifies theend of input to the shell.INPUTRCThe filename for the readline startup file, overriding thedefault of ~/.inputrc (see READLINE below).LANG Used to determine the locale category for any category notspecifically selected with a variable starting with LC_.LC_ALL This variable overrides the value of LANG and any other LC_variable specifying a locale category.LC_COLLATEThis variable determines the collation order used when sortingthe results of pathname expansion, and determines the behaviorof range expressions, equivalence classes, and collatingsequences within pathname expansion and pattern matching.LC_CTYPEThis variable determines the interpretation of characters andthe behavior of character classes within pathname expansion andpattern matching.LC_MESSAGESThis variable determines the locale used to translate double-quoted strings preceded by a $.LC_NUMERICThis variable determines the locale category used for numberformatting.LC_TIMEThis variable determines the locale category used for data andtime formatting.LINES Used by the select compound command to determine the columnlength for printing selection lists. Automatically set if thecheckwinsize option is enabled or in an interactive shell uponreceipt of a SIGWINCH.MAIL If this parameter is set to a file or directory name and theMAILPATH variable is not set, bash informs the user of thearrival of mail in the specified file or Maildir-format direc-tory.MAILCHECKSpecifies how often (in seconds) bash checks for mail. Thedefault is 60 seconds. When it is time to check for mail, theshell does so before displaying the primary prompt. If thisvariable is unset, or set to a value that is not a numbergreater than or equal to zero, the shell disables mail checking.MAILPATHA colon-separated list of filenames to be checked for mail. Themessage to be printed when mail arrives in a particular file maybe specified by separating the filename from the message with a`?'. When used in the text of the message, $_ expands to thename of the current mailfile. Example:MAILPATH='/var/mail/bfox?"You have mail":~/shell-mail?"$_ hasmail!"'Bash can be configured to supply a default value for this vari-able (there is no value by default), but the location of theuser mail files that it uses is system dependent (e.g.,/var/mail/$USER).OPTERR If set to the value 1, bash displays error messages generated bythe getopts builtin command (see SHELL BUILTIN COMMANDS below).OPTERR is initialized to 1 each time the shell is invoked or ashell script is executed.PATH The search path for commands. It is a colon-separated list ofdirectories in which the shell looks for commands (see COMMANDEXECUTION below). A zero-length (null) directory name in thevalue of PATH indicates the current directory. A null directoryname may appear as two adjacent colons, or as an initial ortrailing colon. The default path is system-dependent, and isset by the administrator who installs bash. A common value is``/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin''.POSIXLY_CORRECTIf this variable is in the environment when bash starts, theshell enters posix mode before reading the startup files, as ifthe --posix invocation option had been supplied. If it is setwhile the shell is running, bash enables posix mode, as if thecommand set -o posix had been executed.PROMPT_COMMANDIf set, the value is executed as a command prior to issuing eachprimary prompt.PROMPT_DIRTRIMIf set to a number greater than zero, the value is used as thenumber of trailing directory components to retain when expandingthe \w and \W prompt string escapes (see PROMPTING below).Characters removed are replaced with an ellipsis.PS0 The value of this parameter is expanded (see PROMPTING below)and displayed by interactive shells after reading a command andbefore the command is executed.PS1 The value of this parameter is expanded (see PROMPTING below)and used as the primary prompt string. The default value is``\s-\v\$ ''.PS2 The value of this parameter is expanded as with PS1 and used asthe secondary prompt string. The default is ``> ''.PS3 The value of this parameter is used as the prompt for the selectcommand (see SHELL GRAMMAR above).PS4 The value of this parameter is expanded as with PS1 and thevalue is printed before each command bash displays during anexecution trace. The first character of PS4 is replicated mul-tiple times, as necessary, to indicate multiple levels of indi-rection. The default is ``+ ''.SHELL The full pathname to the shell is kept in this environment vari-able. If it is not set when the shell starts, bash assigns toit the full pathname of the current user's login shell.TIMEFORMATThe value of this parameter is used as a format string specify-ing how the timing information for pipelines prefixed with thetime reserved word should be displayed. The % character intro-duces an escape sequence that is expanded to a time value orother information. The escape sequences and their meanings areas follows; the braces denote optional portions.%% A literal %.%[p][l]R The elapsed time in seconds.%[p][l]U The number of CPU seconds spent in user mode.%[p][l]S The number of CPU seconds spent in system mode.%P The CPU percentage, computed as (%U + %S) / %R.The optional p is a digit specifying the precision, the numberof fractional digits after a decimal point. A value of 0 causesno decimal point or fraction to be output. At most three placesafter the decimal point may be specified; values of p greaterthan 3 are changed to 3. If p is not specified, the value 3 isused.The optional l specifies a longer format, including minutes, ofthe form MMmSS.FFs. The value of p determines whether or notthe fraction is included.If this variable is not set, bash acts as if it had the value$'\nreal\t%3lR\nuser\t%3lU\nsys\t%3lS'. If the value is null,no timing information is displayed. A trailing newline is addedwhen the format string is displayed.TMOUT If set to a value greater than zero, TMOUT is treated as thedefault timeout for the read builtin. The select command termi-nates if input does not arrive after TMOUT seconds when input iscoming from a terminal. In an interactive shell, the value isinterpreted as the number of seconds to wait for a line of inputafter issuing the primary prompt. Bash terminates after waitingfor that number of seconds if a complete line of input does notarrive.TMPDIR If set, bash uses its value as the name of a directory in whichbash creates temporary files for the shell's use.auto_resumeThis variable controls how the shell interacts with the user andjob control. If this variable is set, single word simple com-mands without redirections are treated as candidates for resump-tion of an existing stopped job. There is no ambiguity allowed;if there is more than one job beginning with the string typed,the job most recently accessed is selected. The name of astopped job, in this context, is the command line used to startit. If set to the value exact, the string supplied must matchthe name of a stopped job exactly; if set to substring, thestring supplied needs to match a substring of the name of astopped job. The substring value provides functionality analo-gous to the %? job identifier (see JOB CONTROL below). If setto any other value, the supplied string must be a prefix of astopped job's name; this provides functionality analogous to the%string job identifier.histcharsThe two or three characters which control history expansion andtokenization (see HISTORY EXPANSION below). The first characteris the history expansion character, the character which signalsthe start of a history expansion, normally `!'. The secondcharacter is the quick substitution character, which is used asshorthand for re-running the previous command entered, substi-tuting one string for another in the command. The default is`^'. The optional third character is the character which indi-cates that the remainder of the line is a comment when found asthe first character of a word, normally `#'. The history com-ment character causes history substitution to be skipped for theremaining words on the line. It does not necessarily cause theshell parser to treat the rest of the line as a comment.
Arrays
Bash provides one-dimensional indexed and associative array variables.Any variable may be used as an indexed array; the declare builtin willexplicitly declare an array. There is no maximum limit on the size ofan array, nor any requirement that members be indexed or assigned con-tiguously. Indexed arrays are referenced using integers (includingarithmetic expressions) and are zero-based; associative arrays are ref-erenced using arbitrary strings. Unless otherwise noted, indexed arrayindices must be non-negative integers.An indexed array is created automatically if any variable is assignedto using the syntax name[subscript]=value. The subscript is treated asan arithmetic expression that must evaluate to a number. To explicitlydeclare an indexed array, use declare -a name (see SHELL BUILTIN COM-MANDS below). declare -a name[subscript] is also accepted; the sub-script is ignored.Associative arrays are created using declare -A name.Attributes may be specified for an array variable using the declare andreadonly builtins. Each attribute applies to all members of an array.Arrays are assigned to using compound assignments of the formname=(value1 ... valuen), where each value is of the form [sub-script]=string. Indexed array assignments do not require anything butstring. When assigning to indexed arrays, if the optional brackets andsubscript are supplied, that index is assigned to; otherwise the indexof the element assigned is the last index assigned to by the statementplus one. Indexing starts at zero.When assigning to an associative array, the subscript is required.This syntax is also accepted by the declare builtin. Individual arrayelements may be assigned to using the name[subscript]=value syntaxintroduced above. When assigning to an indexed array, if name is sub-scripted by a negative number, that number is interpreted as relativeto one greater than the maximum index of name, so negative indicescount back from the end of the array, and an index of -1 references thelast element.Any element of an array may be referenced using ${name[subscript]}.The braces are required to avoid conflicts with pathname expansion. Ifsubscript is @ or *, the word expands to all members of name. Thesesubscripts differ only when the word appears within double quotes. Ifthe word is double-quoted, ${name[*]} expands to a single word with thevalue of each array member separated by the first character of the IFSspecial variable, and ${name[@]} expands each element of name to a sep-arate word. When there are no array members, ${name[@]} expands tonothing. If the double-quoted expansion occurs within a word, theexpansion of the first parameter is joined with the beginning part ofthe original word, and the expansion of the last parameter is joinedwith the last part of the original word. This is analogous to theexpansion of the special parameters * and @ (see Special Parametersabove). ${#name[subscript]} expands to the length of ${name[sub-script]}. If subscript is * or @, the expansion is the number of ele-ments in the array. If the subscript used to reference an element ofan indexed array evaluates to a number less than zero, it is inter-preted as relative to one greater than the maximum index of the array,so negative indices count back from the end of the array, and an indexof -1 references the last element.Referencing an array variable without a subscript is equivalent to ref-erencing the array with a subscript of 0. Any reference to a variableusing a valid subscript is legal, and bash will create an array if nec-essary.An array variable is considered set if a subscript has been assigned avalue. The null string is a valid value.It is possible to obtain the keys (indices) of an array as well as thevalues. ${!name[@]} and ${!name[*]} expand to the indices assigned inarray variable name. The treatment when in double quotes is similar tothe 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 subscripts toindexed arrays are interpreted as described above. Care must be takento avoid unwanted side effects caused by pathname expansion. unsetname, where name is an array, or unset name[subscript], where subscriptis * or @, removes the entire array.The declare, local, and readonly builtins each accept a -a option tospecify an indexed array and a -A option to specify an associativearray. If both options are supplied, -A takes precedence. The readbuiltin accepts a -a option to assign a list of words read from thestandard input to an array. The set and declare builtins display arrayvalues in a way that allows them to be reused as assignments.
EXPANSION
Expansion is performed on the command line after it has been split intowords. There are seven kinds of expansion performed: brace expansion,tilde expansion, parameter and variable expansion, command substitu-tion, arithmetic expansion, word splitting, and pathname expansion.The order of expansions is: brace expansion; tilde expansion, parameterand variable expansion, arithmetic expansion, and command substitution(done in a left-to-right fashion); word splitting; and pathname expan-sion.On systems that can support it, there is an additional expansion avail-able: process substitution. This is performed at the same time astilde, parameter, variable, and arithmetic expansion and command sub-stitution.After these expansions are performed, quote characters present in theoriginal word are removed unless they have been quoted themselves(quote removal).Only brace expansion, word splitting, and pathname expansion can changethe number of words of the expansion; other expansions expand a singleword to a single word. The only exceptions to this are the expansionsof "$@" and "${name[@]}" as explained above (see PARAMETERS).
Brace Expansion
Brace expansion is a mechanism by which arbitrary strings may be gener-ated. This mechanism is similar to pathname expansion, but the file-names generated need not exist. Patterns to be brace expanded take theform of an optional preamble, followed by either a series of comma-sep-arated strings or a sequence expression between a pair of braces, fol-lowed by an optional postscript. The preamble is prefixed to eachstring contained within the braces, and the postscript is then appendedto each resulting string, expanding left to right.Brace expansions may be nested. The results of each expanded stringare 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 areeither integers or single characters, and incr, an optional increment,is an integer. When integers are supplied, the expression expands toeach number between x and y, inclusive. Supplied integers may be pre-fixed with 0 to force each term to have the same width. When either xor y begins with a zero, the shell attempts to force all generatedterms to contain the same number of digits, zero-padding where neces-sary. When characters are supplied, the expression expands to eachcharacter lexicographically between x and y, inclusive, using thedefault C locale. Note that both x and y must be of the same type.When the increment is supplied, it is used as the difference betweeneach term. The default increment is 1 or -1 as appropriate.Brace expansion is performed before any other expansions, and any char-acters special to other expansions are preserved in the result. It isstrictly textual. Bash does not apply any syntactic interpretation tothe context of the expansion or the text between the braces.A correctly-formed brace expansion must contain unquoted opening andclosing braces, and at least one unquoted comma or a valid sequenceexpression. Any incorrectly formed brace expansion is left unchanged.A { or , may be quoted with a backslash to prevent its being consideredpart of a brace expression. To avoid conflicts with parameter expan-sion, the string ${ is not considered eligible for brace expansion.This construct is typically used as shorthand when the common prefix ofthe strings to be generated is longer than in the above example: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 historicalversions of sh. sh does not treat opening or closing braces speciallywhen they appear as part of a word, and preserves them in the output.Bash removes braces from words as a consequence of brace expansion.For example, a word entered to sh as file{1,2} appears identically inthe output. The same word is output as file1 file2 after expansion bybash. If strict compatibility with sh is desired, start bash with the+B option or disable brace expansion with the +B option to the set com-mand (see SHELL BUILTIN COMMANDS below).
Tilde Expansion
If a word begins with an unquoted tilde character (`~'), all of thecharacters preceding the first unquoted slash (or all characters, ifthere is no unquoted slash) are considered a tilde-prefix. If none ofthe characters in the tilde-prefix are quoted, the characters in thetilde-prefix following the tilde are treated as a possible login name.If this login name is the null string, the tilde is replaced with thevalue of the shell parameter HOME. If HOME is unset, the home direc-tory of the user executing the shell is substituted instead. Other-wise, the tilde-prefix is replaced with the home directory associatedwith the specified login name.If the tilde-prefix is a `~+', the value of the shell variable PWDreplaces the tilde-prefix. If the tilde-prefix is a `~-', the value ofthe shell variable OLDPWD, if it is set, is substituted. If the char-acters following the tilde in the tilde-prefix consist of a number N,optionally prefixed by a `+' or a `-', the tilde-prefix is replacedwith the corresponding element from the directory stack, as it would bedisplayed by the dirs builtin invoked with the tilde-prefix as an argu-ment. If the characters following the tilde in the tilde-prefix con-sist of a number without a leading `+' or `-', `+' is assumed.If the login name is invalid, or the tilde expansion fails, the word isunchanged.Each variable assignment is checked for unquoted tilde-prefixes immedi-ately following a : or the first =. In these cases, tilde expansion isalso performed. Consequently, one may use filenames with tildes inassignments to PATH, MAILPATH, and CDPATH, and the shell assigns theexpanded value.
Parameter Expansion
The `$' character introduces parameter expansion, command substitution,or arithmetic expansion. The parameter name or symbol to be expandedmay be enclosed in braces, which are optional but serve to protect thevariable to be expanded from characters immediately following it whichcould be interpreted as part of the name.When braces are used, the matching ending brace is the first `}' notescaped by a backslash or within a quoted string, and not within anembedded arithmetic expansion, command substitution, or parameterexpansion.${parameter}The value of parameter is substituted. The braces are requiredwhen parameter is a positional parameter with more than onedigit, or when parameter is followed by a character which is notto be interpreted as part of its name. The parameter is a shellparameter as described above PARAMETERS) or an array reference(Arrays).If the first character of parameter is an exclamation point (!), andparameter is not a nameref, it introduces a level of variable indirec-tion. Bash uses the value of the variable formed from the rest ofparameter as the name of the variable; this variable is then expandedand that value is used in the rest of the substitution, rather than thevalue of parameter itself. This is known as indirect expansion. Ifparameter is a nameref, this expands to the name of the variable refer-enced by parameter instead of performing the complete indirect expan-sion. The exceptions to this are the expansions of ${!prefix*} and${!name[@]} described below. The exclamation point must immediatelyfollow the left brace in order to introduce indirection.In each of the cases below, word is subject to tilde expansion, parame-ter expansion, command substitution, and arithmetic expansion.When not performing substring expansion, using the forms documentedbelow (e.g., :-), bash tests for a parameter that is unset or null.Omitting the colon results in a test only for a parameter that isunset.${parameter:-word}Use Default Values. If parameter is unset or null, the expan-sion of word is substituted. Otherwise, the value of parameteris substituted.${parameter:=word}Assign Default Values. If parameter is unset or null, theexpansion of word is assigned to parameter. The value of param-eter is then substituted. Positional parameters and specialparameters 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, ifit is not interactive, exits. Otherwise, the value of parameteris substituted.${parameter:+word}Use Alternate Value. If parameter is null or unset, nothing issubstituted, otherwise the expansion of word is substituted.${parameter:offset}${parameter:offset:length}Substring Expansion. Expands to up to length characters of thevalue 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 thevalue of parameter starting at the character specified by offsetand extending to the end of the value. length and offset arearithmetic expressions (see ARITHMETIC EVALUATION below).If offset evaluates to a number less than zero, the value isused as an offset in characters from the end of the value ofparameter. If length evaluates to a number less than zero, itis interpreted as an offset in characters from the end of thevalue of parameter rather than a number of characters, and theexpansion is the characters between offset and that result.Note that a negative offset must be separated from the colon byat least one space to avoid being confused with the :- expan-sion.If parameter is @, the result is length positional parametersbeginning 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 an expan-sion error if length evaluates to a number less than zero.If parameter is an indexed array name subscripted by @ or *, theresult is the length members of the array beginning with${parameter[offset]}. A negative offset is taken relative toone greater than the maximum index of the specified array. Itis an expansion error if length evaluates to a number less thanzero.Substring expansion applied to an associative array producesundefined results.Substring indexing is zero-based unless the positional parame-ters are used, in which case the indexing starts at 1 bydefault. If offset is 0, and the positional parameters areused, $0 is prefixed to the list.${!prefix*}${!prefix@}Names matching prefix. Expands to the names of variables whosenames begin with prefix, separated by the first character of theIFS special variable. When @ is used and the expansion appearswithin double quotes, each variable name expands to a separateword.${!name[@]}${!name[*]}List of array keys. If name is an array variable, expands tothe 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 ofparameter is substituted. If parameter is * or @, the valuesubstituted is the number of positional parameters. If parame-ter is an array name subscripted by * or @, the value substi-tuted is the number of elements in the array. If parameter isan indexed array name subscripted by a negative number, thatnumber is interpreted as relative to one greater than the maxi-mum index of parameter, so negative indices count back from theend of the array, and an index of -1 references the last ele-ment.${parameter#word}${parameter##word}Remove matching prefix pattern. The word is expanded to producea pattern just as in pathname expansion. If the pattern matchesthe beginning of the value of parameter, then the result of theexpansion is the expanded value of parameter with the shortestmatching pattern (the ``#'' case) or the longest matching pat-tern (the ``##'' case) deleted. If parameter is @ or *, thepattern removal operation is applied to each positional parame-ter in turn, and the expansion is the resultant list. If param-eter is an array variable subscripted with @ or *, the patternremoval operation is applied to each member of the array inturn, and the expansion is the resultant list.${parameter%word}${parameter%%word}Remove matching suffix pattern. The word is expanded to producea pattern just as in pathname expansion. If the pattern matchesa trailing portion of the expanded value of parameter, then theresult of the expansion is the expanded value of parameter withthe shortest matching pattern (the ``%'' case) or the longestmatching pattern (the ``%%'' case) deleted. If parameter is @or *, the pattern removal operation is applied to each posi-tional parameter in turn, and the expansion is the resultantlist. If parameter is an array variable subscripted with @ or*, the pattern removal operation is applied to each member ofthe array in turn, and the expansion is the resultant list.${parameter/pattern/string}Pattern substitution. The pattern is expanded to produce a pat-tern just as in pathname expansion. Parameter is expanded andthe longest match of pattern against its value is replaced withstring. If pattern begins with /, all matches of pattern arereplaced with string. Normally only the first match isreplaced. If pattern begins with #, it must match at the begin-ning of the expanded value of parameter. If pattern begins with%, it must match at the end of the expanded value of parameter.If string is null, matches of pattern are deleted and the / fol-lowing pattern may be omitted. If the nocasematch shell optionis enabled, the match is performed without regard to the case ofalphabetic characters. If parameter is @ or *, the substitutionoperation is applied to each positional parameter in turn, andthe expansion is the resultant list. If parameter is an arrayvariable subscripted with @ or *, the substitution operation isapplied 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 alpha-betic characters in parameter. The pattern is expanded to pro-duce a pattern just as in pathname expansion. Each character inthe expanded value of parameter is tested against pattern, and,if it matches the pattern, its case is converted. The patternshould not attempt to match more than one character. The ^operator converts lowercase letters matching pattern to upper-case; the , operator converts matching uppercase letters to low-ercase. The ^^ and ,, expansions convert each matched characterin the expanded value; the ^ and , expansions match and convertonly the first character in the expanded value. If pattern isomitted, it is treated like a ?, which matches every character.If parameter is @ or *, the case modification operation isapplied to each positional parameter in turn, and the expansionis the resultant list. If parameter is an array variable sub-scripted with @ or *, the case modification operation is appliedto each member of the array in turn, and the expansion is theresultant list.${parameter@operator}Parameter transformation. The expansion is either a transforma-tion of the value of parameter or information about parameteritself, depending on the value of operator. Each operator is asingle letter:Q The expansion is a string that is the value of parameterquoted in a format that can be reused as input.E The expansion is a string that is the value of parameterwith backslash escape sequences expanded as with the$'...' quoting mechansim.P The expansion is a string that is the result of expandingthe value of parameter as if it were a prompt string (seePROMPTING below).A The expansion is a string in the form of an assignmentstatement or declare command that, if evaluated, willrecreate parameter with its attributes and value.a The expansion is a string consisting of flag values rep-resenting parameter's attributes.If parameter is @ or *, the operation is applied to each posi-tional 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 andpathname expansion as described below.
Command Substitution
Command substitution allows the output of a command to replace the com-mand name. There are two forms:$(command)or`command`Bash performs the expansion by executing command in a subshell environ-ment and replacing the command substitution with the standard output ofthe command, with any trailing newlines deleted. Embedded newlines arenot deleted, but they may be removed during word splitting. The com-mand substitution $(cat file) can be replaced by the equivalent butfaster $(< file).When the old-style backquote form of substitution is used, backslashretains its literal meaning except when followed by $, `, or \. Thefirst backquote not preceded by a backslash terminates the command sub-stitution. When using the $(command) form, all characters between theparentheses make up the command; none are treated specially.Command substitutions may be nested. To nest when using the backquotedform, escape the inner backquotes with backslashes.If the substitution appears within double quotes, word splitting andpathname expansion are not performed on the results.
Arithmetic Expansion
Arithmetic expansion allows the evaluation of an arithmetic expressionand the substitution of the result. The format for arithmetic expan-sion is:$((expression))The old format $[expression] is deprecated and will be removed inupcoming versions of bash.The expression is treated as if it were within double quotes, but adouble quote inside the parentheses is not treated specially. Alltokens in the expression undergo parameter and variable expansion, com-mand substitution, and quote removal. The result is treated as thearithmetic expression to be evaluated. Arithmetic expansions may benested.The evaluation is performed according to the rules listed below underARITHMETIC EVALUATION. If expression is invalid, bash prints a messageindicating failure and no substitution occurs.
Process Substitution
Process substitution allows a process's input or output to be referredto using a filename. It takes the form of <(list) or >(list). Theprocess list is run asynchronously, and its input or output appears asa filename. This filename is passed as an argument to the current com-mand as the result of the expansion. If the >(list) form is used,writing to the file will provide input for list. If the <(list) formis used, the file passed as an argument should be read to obtain theoutput of list. Process substitution is supported on systems that sup-port named pipes (FIFOs) or the /dev/fd method of naming open files.When available, process substitution is performed simultaneously withparameter and variable expansion, command substitution, and arithmeticexpansion.
Word Splitting
The shell scans the results of parameter expansion, command substitu-tion, and arithmetic expansion that did not occur within double quotesfor word splitting.The shell treats each character of IFS as a delimiter, and splits theresults of the other expansions into words using these characters asfield 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 previousexpansions are ignored, and any sequence of IFS characters not at thebeginning or end serves to delimit words. If IFS has a value otherthan the default, then sequences of the whitespace characters space,tab, and newline are ignored at the beginning and end of the word, aslong as the whitespace character is in the value of IFS (an IFS white-space character). Any character in IFS that is not IFS whitespace,along with any adjacent IFS whitespace characters, delimits a field. Asequence of IFS whitespace characters is also treated as a delimiter.If the value of IFS is null, no word splitting occurs.Explicit null arguments ("" or '') are retained and passed to commandsas empty strings. Unquoted implicit null arguments, resulting from theexpansion of parameters that have no values, are removed. If a parame-ter with no value is expanded within double quotes, a null argumentresults and is retained and passed to a command as an empty string.When a quoted null argument appears as part of a word whose expansionis non-null, the null argument is removed. That is, the word -d''becomes -d after word splitting and null argument removal.Note that if no expansion occurs, no splitting is performed.
Pathname Expansion
After word splitting, unless the -f option has been set, bash scanseach word for the characters *, ?, and [. If one of these charactersappears, then the word is regarded as a pattern, and replaced with analphabetically sorted list of filenames matching the pattern (see Pat-tern Matching below). If no matching filenames are found, and theshell option nullglob is not enabled, the word is left unchanged. Ifthe nullglob option is set, and no matches are found, the word isremoved. If the failglob shell option is set, and no matches arefound, an error message is printed and the command is not executed. Ifthe shell option nocaseglob is enabled, the match is performed withoutregard to the case of alphabetic characters. Note that when usingrange expressions like [a-z] (see below), letters of the other case maybe included, depending on the setting of LC_COLLATE. When a pattern isused for pathname expansion, the character ``.'' at the start of aname or immediately following a slash must be matched explicitly,unless the shell option dotglob is set. When matching a pathname, theslash character must always be matched explicitly. In other cases, the``.'' character is not treated specially. See the description ofshopt below under SHELL BUILTIN COMMANDS for a description of thenocaseglob, nullglob, failglob, and dotglob shell options.The GLOBIGNORE shell variable may be used to restrict the set of file-names matching a pattern. If GLOBIGNORE is set, each matching filenamethat also matches one of the patterns in GLOBIGNORE is removed from thelist of matches. If the nocaseglob option is set, the matching againstthe patterns in GLOBIGNORE is performed without regard to case. Thefilenames ``.'' and ``..'' are always ignored when GLOBIGNORE is setand not null. However, setting GLOBIGNORE to a non-null value has theeffect of enabling the dotglob shell option, so all other filenamesbeginning with a ``.'' will match. To get the old behavior of ignor-ing filenames beginning with a ``.'', make ``.*'' one of the patternsin GLOBIGNORE. The dotglob option is disabled when GLOBIGNORE isunset. The pattern matching honors the setting of the extglob shelloption.Pattern MatchingAny character that appears in a pattern, other than the special patterncharacters described below, matches itself. The NUL character may notoccur in a pattern. A backslash escapes the following character; theescaping backslash is discarded when matching. The special patterncharacters 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 theglobstar shell option is enabled, and * is used in apathname expansion context, two adjacent *s used as asingle pattern will match all files and zero or moredirectories and subdirectories. If followed by a /, twoadjacent *s will match only directories and subdirecto-ries.? Matches any single character.[...] Matches any one of the enclosed characters. A pair ofcharacters separated by a hyphen denotes a range expres-sion; any character that falls between those two charac-ters, inclusive, using the current locale's collatingsequence and character set, is matched. If the firstcharacter following the [ is a ! or a ^ then any charac-ter not enclosed is matched. The sorting order of char-acters in range expressions is determined by the currentlocale and the values of the LC_COLLATE or LC_ALL shellvariables, if set. To obtain the traditional interpreta-tion of range expressions, where [a-d] is equivalent to[abcd], set value of the LC_ALL shell variable to C, orenable the globasciiranges shell option. A - may bematched by including it as the first or last character inthe set. A ] may be matched by including it as the firstcharacter in the set.Within [ and ], character classes can be specified usingthe syntax [:class:], where class is one of the followingclasses defined in the POSIX standard:alnum alpha ascii blank cntrl digit graph lower printpunct space upper word xdigitA character class matches any character belonging to thatclass. The word character class matches letters, digits,and the character _.Within [ and ], an equivalence class can be specifiedusing the syntax [=c=], which matches all characters withthe same collation weight (as defined by the currentlocale) as the character c.Within [ and ], the syntax [.symbol.] matches the collat-ing symbol symbol.If the extglob shell option is enabled using the shopt builtin, severalextended pattern matching operators are recognized. In the followingdescription, a pattern-list is a list of one or more patterns separatedby a |. Composite patterns may be formed using one or more of the fol-lowing 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 patterns
Quote Removal
After the preceding expansions, all unquoted occurrences of the charac-ters \, ', and " that did not result from one of the above expansionsare removed.
REDIRECTION
Before a command is executed, its input and output may be redirectedusing a special notation interpreted by the shell. Redirection allowscommands' file handles to be duplicated, opened, closed, made to referto different files, and can change the files the command reads from andwrites to. Redirection may also be used to modify file handles in thecurrent shell execution environment. The following redirection opera-tors may precede or appear anywhere within a simple command or may fol-low a command. Redirections are processed in the order they appear,from left to right.Each redirection that may be preceded by a file descriptor number mayinstead be preceded by a word of the form {varname}. In this case, foreach redirection operator except >&- and <&-, the shell will allocate afile descriptor greater than or equal to 10 and assign it to varname.If >&- or <&- is preceded by {varname}, the value of varname definesthe file descriptor to close.In the following descriptions, if the file descriptor number is omit-ted, and the first character of the redirection operator is <, the re-direction refers to the standard input (file descriptor 0). If thefirst character of the redirection operator is >, the redirectionrefers to the standard output (file descriptor 1).The word following the redirection operator in the following descrip-tions, unless otherwise noted, is subjected to brace expansion, tildeexpansion, parameter and variable expansion, command substitution,arithmetic expansion, quote removal, pathname expansion, and wordsplitting. If it expands to more than one word, bash reports an error.Note that the order of redirections is significant. For example, thecommandls > 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 standarderror was duplicated from the standard output before the standard out-put was redirected to dirlist.Bash handles several filenames specially when they are used in redirec-tions, as described in the following table. If the operating system onwhich bash is running provides these special files, bash will use them;otherwise it will emulate them internally with the behavior describedbelow./dev/fd/fdIf fd is a valid integer, file descriptor fd is dupli-cated./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 portis an integer port number or service name, bash attemptsto open the corresponding TCP socket./dev/udp/host/portIf host is a valid hostname or Internet address, and portis an integer port number or service name, bash attemptsto open 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 withcare, as they may conflict with file descriptors the shell uses inter-nally.Note that the exec builtin command can make redirections take effect inthe current shell.
Redirecting Input
Redirection of input causes the file whose name results from the expan-sion of word to be opened for reading on file descriptor n, or thestandard input (file descriptor 0) if n is not specified.The general format for redirecting input is:[n]<word
Redirecting Output
Redirection of output causes the file whose name results from theexpansion of word to be opened for writing on file descriptor n, or thestandard output (file descriptor 1) if n is not specified. If the filedoes not exist it is created; if it does exist it is truncated to zerosize.The general format for redirecting output is:[n]>wordIf the redirection operator is >, and the noclobber option to the setbuiltin has been enabled, the redirection will fail if the file whosename results from the expansion of word exists and is a regular file.If the redirection operator is >|, or the redirection operator is > andthe noclobber option to the set builtin command is not enabled, the re-direction is attempted even if the file named by word exists.
Appending Redirected Output
Redirection of output in this fashion causes the file whose nameresults from the expansion of word to be opened for appending on filedescriptor n, or the standard output (file descriptor 1) if n is notspecified. If the file does not exist it is created.The general format for appending output is:[n]>>word
Redirecting Standard Output and Standard Error
This construct allows both the standard output (file descriptor 1) andthe standard error output (file descriptor 2) to be redirected to thefile whose name is the expansion of word.There are two formats for redirecting standard output and standarderror:&>wordand>&wordOf the two forms, the first is preferred. This is semantically equiva-lent to>word 2>&1When using the second form, word may not expand to a number or -. Ifit does, other redirection operators apply (see Duplicating FileDescriptors below) for compatibility reasons.
Appending Standard Output and Standard Error
This construct allows both the standard output (file descriptor 1) andthe standard error output (file descriptor 2) to be appended to thefile 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 Documents
This type of redirection instructs the shell to read input from thecurrent source until a line containing only delimiter (with no trailingblanks) is seen. All of the lines read up to that point are then usedas the standard input (or file descriptor n if n is specified) for acommand.The format of here-documents is:[n]<<[-]wordhere-documentdelimiterNo parameter and variable expansion, command substitution, arithmeticexpansion, or pathname expansion is performed on word. If any part ofword is quoted, the delimiter is the result of quote removal on word,and the lines in the here-document are not expanded. If word isunquoted, all lines of the here-document are subjected to parameterexpansion, command substitution, and arithmetic expansion, the charac-ter sequence \<newline> is ignored, and \ must be used to quote thecharacters \, $, and `.If the redirection operator is <<-, then all leading tab characters arestripped from input lines and the line containing delimiter. Thisallows here-documents within shell scripts to be indented in a naturalfashion.
Here Strings
A variant of here documents, the format is:[n]<<strftime(3) and the result isinserted into the prompt string; an empty format resultsin a locale-specific time representation. The braces arerequired\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 portionfollowing 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 abbreviatedwith a tilde (uses the value of the PROMPT_DIRTRIM vari-able)\W the basename of the current working directory, with $HOMEabbreviated 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 couldbe used to embed a terminal control sequence into theprompt\] end a sequence of non-printing charactersThe command number and the history number are usually different: thehistory number of a command is its position in the history list, whichmay include commands restored from the history file (see HISTORYbelow), while the command number is the position in the sequence ofcommands executed during the current shell session. After the stringis decoded, it is expanded via parameter expansion, command substitu-tion, arithmetic expansion, and quote removal, subject to the value ofthe promptvars shell option (see the description of the shopt commandunder SHELL BUILTIN COMMANDS below).
READLINE
This is the library that handles reading input when using an interac-tive shell, unless the --noediting option is given at shell invocation.Line editing is also used when using the -e option to the read builtin.By default, the line editing commands are similar to those of Emacs. Avi-style line editing interface is also available. Line editing can beenabled at any time using the -o emacs or -o vi options to the setbuiltin (see SHELL BUILTIN COMMANDS below). To turn off line editingafter the shell is running, use the +o emacs or +o vi options to theset builtin.
Readline Notation
In this section, the Emacs-style notation is used to denote keystrokes.Control keys are denoted by C-key, e.g., C-n means Control-N. Simi-larly, meta keys are denoted by M-key, so M-x means Meta-X. (On key-boards without a meta key, M-x means ESC x, i.e., press the Escape keythen the x key. This makes ESC the meta prefix. The combination M-C-xmeans ESC-Control-x, or press the Escape key then hold the Control keywhile pressing the x key.)Readline commands may be given numeric arguments, which normally act asa repeat count. Sometimes, however, it is the sign of the argumentthat is significant. Passing a negative argument to a command thatacts in the forward direction (e.g., kill-line) causes that command toact in a backward direction. Commands whose behavior with argumentsdeviates from this are noted below.When a command is described as killing text, the text deleted is savedfor possible future retrieval (yanking). The killed text is saved in akill ring. Consecutive kills cause the text to be accumulated into oneunit, which can be yanked all at once. Commands which do not kill textseparate the chunks of text on the kill ring.
Readline Initialization
Readline is customized by putting commands in an initialization file(the inputrc file). The name of this file is taken from the value ofthe INPUTRC variable. If that variable is unset, the default is~/.inputrc. When a program which uses the readline library starts up,the initialization file is read, and the key bindings and variables areset. There are only a few basic constructs allowed in the readlineinitialization file. Blank lines are ignored. Lines beginning with a# are comments. Lines beginning with a $ indicate conditional con-structs. Other lines denote key bindings and variable settings.The default key-bindings may be changed with an inputrc file. Otherprograms that use this library may add their own commands and bindings.For example, placingM-Control-u: universal-argumentorC-Meta-u: universal-argumentinto the inputrc would make M-C-u execute the readline command univer-sal-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 astring that is inserted when the key is pressed (a macro).
Readline Key Bindings
The syntax for controlling key bindings in the inputrc file is simple.All that is required is the name of the command or the text of a macroand a key sequence to which it should be bound. The name may be speci-fied in one of two ways: as a symbolic key name, possibly with Meta- orControl- prefixes, or as a key sequence.When using the form keyname:function-name or macro, keyname is the nameof 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 is bound torun the macro expressed on the right hand side (that is, to insert thetext ``> output'' into the line).In the second form, "keyseq":function-name or macro, keyseq differsfrom keyname above in that strings denoting an entire key sequence maybe specified by placing the sequence within double quotes. Some GNUEmacs style key escapes can be used, as in the following example, butthe 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 ~ isbound 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 ofbackslash 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 valuennn (one to three digits)\xHH the eight-bit character whose value is the hexadecimalvalue HH (one or two hex digits)When entering the text of a macro, single or double quotes must be usedto indicate a macro definition. Unquoted text is assumed to be a func-tion name. In the macro body, the backslash escapes described aboveare expanded. Backslash will quote any other character in the macrotext, including " and '.Bash allows the current readline key bindings to be displayed or modi-fied with the bind builtin command. The editing mode may be switchedduring interactive use by using the -o option to the set builtin com-mand (see SHELL BUILTIN COMMANDS below).
Readline Variables
Readline has variables that can be used to further customize its behav-ior. A variable may be set in the inputrc file with a statement of theformset variable-name valueExcept where noted, readline variables can take the values On or Off(without regard to case). Unrecognized variable names are ignored.When a variable value is read, empty or null values, "on" (case-insen-sitive), and "1" are equivalent to On. All other values are equivalentto Off. The variables and their default values are:bell-style (audible)Controls what happens when readline wants to ring the terminalbell. If set to none, readline never rings the bell. If set tovisible, readline uses a visible bell if one is available. Ifset to audible, readline attempts to ring the terminal's bell.bind-tty-special-chars (On)If set to On, readline attempts to bind the control characterstreated specially by the kernel's terminal driver to their read-line equivalents.blink-matching-paren (Off)If set to On, readline attempts to briefly move the cursor to anopening parenthesis when a closing parenthesis is inserted.colored-completion-prefix (Off)If set to On, when listing completions, readline displays thecommon prefix of the set of possible completions using a differ-ent color. The color definitions are taken from the value ofthe LS_COLORS environment variable.colored-stats (Off)If set to On, readline displays possible completions using dif-ferent colors to indicate their file type. The color defini-tions are taken from the value of the LS_COLORS environmentvariable.comment-begin (``#'')The string that is inserted when the readline insert-commentcommand 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 matcheswhen performing completion. The value is ignored if it is lessthan 0 or greater than the terminal screen width. A value of 0will 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 completionin a case-insensitive fashion.completion-map-case (Off)If set to On, and completion-ignore-case is enabled, readlinetreats 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 pos-sible completions that is displayed without modification. Whenset to a value greater than zero, common prefixes longer thanthis 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 num-ber of possible completions generated by the possible-comple-tions command. It may be set to any integer value greater thanor equal to zero. If the number of possible completions isgreater than or equal to the value of this variable, the user isasked whether or not he wishes to view them; otherwise they aresimply listed on the terminal.convert-meta (On)If set to On, readline will convert characters with the eighthbit set to an ASCII key sequence by stripping the eighth bit andprefixing an escape character (in effect, using escape as themeta prefix). The default is On, but readline will set it toOff if the locale contains eight-bit characters.disable-completion (Off)If set to On, readline will inhibit word completion. Completioncharacters 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 supportit, readline echoes a character corresponding to a signal gener-ated from the keyboard.editing-mode (emacs)Controls whether readline begins with a set of key bindings sim-ilar to Emacs or vi. editing-mode can be set to either emacs orvi.enable-bracketed-paste (Off)When set to On, readline will configure the terminal in a waythat will enable it to insert each paste into the editing bufferas a single string of characters, instead of treating each char-acter as if it had been read from the keyboard. This can pre-vent pasted characters from being interpreted as editing com-mands.enable-keypad (Off)When set to On, readline will try to enable the application key-pad 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 modifierkey 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 readlineattempts word completion.history-preserve-point (Off)If set to On, the history code attempts to place point at thesame 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 historylist. 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, thenumber of history entries is set to the value of the HISTSIZEshell variable. If an attempt is made to set history-size to anon-numeric value, the maximum number of history entries will beset 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 anew line.input-meta (Off)If set to On, readline will enable eight-bit input (that is, itwill not strip the eighth bit from the characters it reads),regardless of what the terminal claims it can support. The namemeta-flag is a synonym for this variable. The default is Off,but readline will set it to On if the locale contains eight-bitcharacters.isearch-terminators (``C-[C-J'')The string of characters that should terminate an incrementalsearch without subsequently executing the character as a com-mand. If this variable has not been given a value, the charac-ters ESC and C-J will terminate an incremental search.keymap (emacs)Set the current readline keymap. The set of valid keymap namesis emacs, emacs-standard, emacs-meta, emacs-ctlx, vi, vi-com-mand, and vi-insert. vi is equivalent to vi-command; emacs isequivalent 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 theprimary prompt when emacs editing mode is active. The value isexpanded like a key binding, so the standard set of meta- andcontrol 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 con-trol sequence into the mode string.keyseq-timeout (500)Specifies the duration readline will wait for a character whenreading an ambiguous key sequence (one that can form a completekey sequence using the input read so far, or can take additionalinput to complete a longer key sequence). If no input isreceived within the timeout, readline will use the shorter butcomplete key sequence. The value is specified in milliseconds,so a value of 1000 means that readline will wait one second foradditional input. If this variable is set to a value less thanor equal to zero, or to a non-numeric value, readline will waituntil another key is pressed to decide which key sequence tocomplete.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 dis-played with a preceding asterisk (*).mark-symlinked-directories (Off)If set to On, completed names which are symbolic links to direc-tories have a slash appended (subject to the value ofmark-directories).match-hidden-files (On)This variable, when set to On, causes readline to match fileswhose names begin with a `.' (hidden files) when performingfilename completion. If set to Off, the leading `.' must besupplied 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 thelist of possible completions (which may be empty) before cyclingthrough the list.output-meta (Off)If set to On, readline will display characters with the eighthbit set directly rather than as a meta-prefixed escape sequence.The default is Off, but readline will set it to On if the localecontains eight-bit characters.page-completions (On)If set to On, readline uses an internal more-like pager to dis-play a screenful of possible completions at a time.print-completions-horizontally (Off)If set to On, readline will display completions with matchessorted horizontally in alphabetical order, rather than down thescreen.revert-all-at-newline (Off)If set to On, readline will undo all changes to history linesbefore returning when accept-line is executed. By default, his-tory lines may be modified and retain individual undo listsacross 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 completioncause the matches to be listed immediately instead of ringingthe bell.show-all-if-unmodified (Off)This alters the default behavior of the completion functions ina fashion similar to show-all-if-ambiguous. If set to On, wordswhich have more than one possible completion without any possi-ble partial completion (the possible completions don't share acommon prefix) cause the matches to be listed immediatelyinstead of ringing the bell.show-mode-in-prompt (Off)If set to On, add a character to the beginning of the promptindicating the editing mode: emacs (@), vi command (:) or viinsertion (+).skip-completed-text (Off)If set to On, this alters the default completion behavior wheninserting 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 thatmatch characters after point in the word being completed, soportions of the word following the cursor are not duplicated.vi-cmd-mode-string ((cmd))This string is displayed immediately before the last line of theprimary prompt when vi editing mode is active and in commandmode. The value is expanded like a key binding, so the standardset of meta- and control prefixes and backslash escape sequencesis available. Use the \1 and \2 escapes to begin and endsequences of non-printing characters, which can be used to embeda terminal control sequence into the mode string.vi-ins-mode-string ((ins))This string is displayed immediately before the last line of theprimary prompt when vi editing mode is active and in insertionmode. The value is expanded like a key binding, so the standardset of meta- and control prefixes and backslash escape sequencesis available. Use the \1 and \2 escapes to begin and endsequences of non-printing characters, which can be used to embeda terminal control sequence into the mode string.visible-stats (Off)If set to On, a character denoting a file's type as reported bystat(2) is appended to the filename when listing possible com-pletions.
Readline Conditional Constructs
Readline implements a facility similar in spirit to the conditionalcompilation features of the C preprocessor which allows key bindingsand variable settings to be performed as the result of tests. Thereare four parser directives used.$if The $if construct allows bindings to be made based on the edit-ing 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 testwhether readline is in emacs or vi mode. This may beused in conjunction with the set keymap command, forinstance, to set bindings in the emacs-standard andemacs-ctlx keymaps only if readline is starting out inemacs mode.term The term= form may be used to include terminal-specifickey bindings, perhaps to bind the key sequences output bythe terminal's function keys. The word on the right sideof the = is tested against both the full name of the ter-minal and the portion of the terminal name before thefirst -. 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 readlinelibrary sets the application name, and an initializationfile can test for a particular value. This could be usedto bind key sequences to functions useful for a specificprogram. For instance, the following command adds a keysequence that quotes the current or previous word inbash:$if Bash# Quote the current or previous word"\C-xq": "\eb\"\ef\""$endif$endif This command, as seen in the previous example, terminates an $ifcommand.$else Commands in this branch of the $if directive are executed if thetest fails.$includeThis directive takes a single filename as an argument and readscommands and bindings from that file. For example, the follow-ing directive would read /etc/inputrc:$include /etc/inputrc
Searching
Readline provides commands for searching through the command history(see HISTORY below) for lines containing a specified string. There aretwo search modes: incremental and non-incremental.Incremental searches begin before the user has finished typing thesearch string. As each character of the search string is typed, read-line displays the next entry from the history matching the string typedso far. An incremental search requires only as many characters asneeded to find the desired history entry. The characters present inthe value of the isearch-terminators variable are used to terminate anincremental search. If that variable has not been assigned a value theEscape and Control-J characters will terminate an incremental search.Control-G will abort an incremental search and restore the originalline. When the search is terminated, the history entry containing thesearch string becomes the current line.To find other matching entries in the history list, type Control-S orControl-R as appropriate. This will search backward or forward in thehistory for the next entry matching the search string typed so far.Any other key sequence bound to a readline command will terminate thesearch and execute that command. For instance, a newline will termi-nate the search and accept the line, thereby executing the command fromthe history list.Readline remembers the last incremental search string. If two Control-Rs are typed without any intervening characters defining a new searchstring, any remembered search string is used.Non-incremental searches read the entire search string before startingto search for matching history lines. The search string may be typedby the user or be part of the contents of the current line.
Readline Command Names
The following is a list of the names of the commands and the defaultkey sequences to which they are bound. Command names without an accom-panying key sequence are unbound by default. In the following descrip-tions, point refers to the current cursor position, and mark refers toa cursor position saved by the set-mark command. The text between thepoint and mark is referred to as the region.
Commands for Moving
beginning-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 ofalphanumeric characters (letters and digits).backward-word (M-b)Move back to the start of the current or previous word. Wordsare composed of alphanumeric characters (letters and digits).shell-forward-wordMove forward to the end of the next word. Words are delimitedby non-quoted shell metacharacters.shell-backward-wordMove back to the start of the current or previous word. Wordsare delimited by non-quoted shell metacharacters.clear-screen (C-l)Clear the screen leaving the current line at the top of thescreen. With an argument, refresh the current line withoutclearing the screen.redraw-current-lineRefresh the current line.
Commands for Manipulating the History
accept-line (Newline, Return)Accept the line regardless of where the cursor is. If this lineis non-empty, add it to the history list according to the stateof the HISTCONTROL variable. If the line is a modified historyline, then restore the history line to its original state.previous-history (C-p)Fetch the previous command from the history list, moving back inthe list.next-history (C-n)Fetch the next command from the history list, moving forward inthe 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 currentlybeing entered.reverse-search-history (C-r)Search backward starting at the current line and moving `up'through the history as necessary. This is an incrementalsearch.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 lineusing 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-incrementalsearch for a string supplied by the user.history-search-forwardSearch forward through the history for the string of charactersbetween the start of the current line and the point. This is anon-incremental search.history-search-backwardSearch backward through the history for the string of charactersbetween the start of the current line and the point. This is anon-incremental search.yank-nth-arg (M-C-y)Insert the first argument to the previous command (usually thesecond word on the previous line) at point. With an argument n,insert the nth word from the previous command (the words in theprevious command begin with word 0). A negative argumentinserts the nth word from the end of the previous command. Oncethe argument n is computed, the argument is extracted as if the"!n" history expansion had been specified.yank-last-arg (M-., M-_)Insert the last argument to the previous command (the last wordof the previous history entry). With a numeric argument, behaveexactly like yank-nth-arg. Successive calls to yank-last-argmove back through the history list, inserting the last word (orthe word specified by the argument to the first call) of eachline in turn. Any numeric argument supplied to these successivecalls determines the direction to move through the history. Anegative argument switches the direction through the history(back or forward). The history expansion facilities are used toextract the last word, as if the "!$" history expansion had beenspecified.shell-expand-line (M-C-e)Expand the line as the shell does. This performs alias and his-tory expansion as well as all of the shell word expansions. SeeHISTORY EXPANSION below for a description of history expansion.history-expand-line (M-^)Perform history expansion on the current line. See HISTORYEXPANSION below for a description of history expansion.magic-spacePerform history expansion on the current line and insert aspace. See HISTORY EXPANSION below for a description of historyexpansion.alias-expand-linePerform alias expansion on the current line. See ALIASES abovefor 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 linerelative 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 theresult as shell commands. Bash attempts to invoke $VISUAL,$EDITOR, and emacs as the editor, in that order.
Commands for Changing Text
end-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 charac-ters on 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 thesame character as the tty EOF character, as C-d commonly is, seeabove for the effects.backward-delete-char (Rubout)Delete the character behind the cursor. When given a numericargument, save the deleted text on the kill ring.forward-backward-delete-charDelete the character under the cursor, unless the cursor is atthe end of the line, in which case the character behind the cur-sor is deleted.quoted-insert (C-q, C-v)Add the next character typed to the line verbatim. This is howto 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 atpoint, 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, movingpoint 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 negativeargument, uppercase the previous word, but do not move point.downcase-word (M-l)Lowercase the current (or following) word. With a negativeargument, lowercase the previous word, but do not move point.capitalize-word (M-c)Capitalize the current (or following) word. With a negativeargument, capitalize the previous word, but do not move point.overwrite-modeToggle overwrite mode. With an explicit positive numeric argu-ment, switches to overwrite mode. With an explicit non-positivenumeric argument, switches to insert mode. This command affectsonly emacs mode; vi mode does overwrite differently. Each callto readline() starts in insert mode. In overwrite mode, charac-ters bound to self-insert replace the text at point rather thanpushing the text to the right. Characters bound to back-ward-delete-char replace the character before point with aspace. By default, this command is unbound.
Killing and Yanking
kill-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. Thekilled text is saved on the kill-ring.kill-whole-lineKill all characters on the current line, no matter where pointis.kill-word (M-d)Kill from point to the end of the current word, or if betweenwords, 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 asthose used by backward-word.shell-kill-wordKill from point to the end of the current word, or if betweenwords, 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 asthose used by shell-backward-word.unix-word-rubout (C-w)Kill the word behind point, using white space as a word bound-ary. The killed text is saved on the kill-ring.unix-filename-ruboutKill the word behind point, using white space and the slashcharacter as the word boundaries. The killed text is saved onthe kill-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 bound-aries are the same as backward-word.copy-forward-wordCopy the word following point to the kill buffer. The wordboundaries 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 follow-ing yank or yank-pop.
Numeric Arguments
digit-argument (M-0, M-1, ..., M--)Add this digit to the argument already accumulating, or start anew argument. M-- starts a negative argument.universal-argumentThis is another way to specify an argument. If this command isfollowed by one or more digits, optionally with a leading minussign, those digits define the argument. If the command is fol-lowed by digits, executing universal-argument again ends thenumeric argument, but is otherwise ignored. As a special case,if this command is immediately followed by a character that isneither a digit nor minus sign, the argument count for the nextcommand is multiplied by four. The argument count is initiallyone, so executing this function the first time makes the argu-ment count four, a second time makes the argument count sixteen,and so on.
Completing
complete (TAB)Attempt to perform completion on the text before point. Bashattempts 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, filenamecompletion 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 havebeen generated by possible-completions.menu-completeSimilar to complete, but replaces the word to be completed witha single match from the list of possible completions. Repeatedexecution of menu-complete steps through the list of possiblecompletions, inserting each match in turn. At the end of thelist of completions, the bell is rung (subject to the setting ofbell-style) and the original text is restored. An argument of nmoves n positions forward in the list of matches; a negativeargument may be used to move backward through the list. Thiscommand is intended to be bound to TAB, but is unbound bydefault.menu-complete-backwardIdentical to menu-complete, but moves backward through the listof 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 beginningor end of the line (like delete-char). If at the end of theline, behaves identically to possible-completions. This commandis 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, treatingit as a filename.complete-username (M-~)Attempt completion on the text before point, treating it as ausername.possible-username-completions (C-x ~)List the possible completions of the text before point, treatingit as a username.complete-variable (M-$)Attempt completion on the text before point, treating it as ashell variable.possible-variable-completions (C-x $)List the possible completions of the text before point, treatingit as a shell variable.complete-hostname (M-@)Attempt completion on the text before point, treating it as ahostname.possible-hostname-completions (C-x @)List the possible completions of the text before point, treatingit as a hostname.complete-command (M-!)Attempt completion on the text before point, treating it as acommand name. Command completion attempts to match the textagainst aliases, reserved words, shell functions, shellbuiltins, and finally executable filenames, in that order.possible-command-completions (C-x !)List the possible completions of the text before point, treatingit as a command name.dynamic-complete-history (M-TAB)Attempt completion on the text before point, comparing the textagainst lines from the history list for possible completionmatches.dabbrev-expandAttempt menu completion on the text before point, comparing thetext against lines from the history list for possible completionmatches.complete-into-braces (M-{)Perform filename completion and insert the list of possible com-pletions enclosed within braces so the list is available to theshell (see Brace Expansion above).
Keyboard Macros
start-kbd-macro (C-x ()Begin saving the characters typed into the current keyboardmacro.end-kbd-macro (C-x ))Stop saving the characters typed into the current keyboard macroand store the definition.call-last-kbd-macro (C-x e)Re-execute the last keyboard macro defined, by making the char-acters in the macro appear as if typed at the keyboard.print-last-kbd-macro ()Print the last keyboard macro defined in a format suitable forthe inputrc file.
Miscellaneous
re-read-init-file (C-x C-r)Read in the contents of the inputrc file, and incorporate anybindings 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 thatis 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 theundo 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 isset 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 ofthat character. A negative count searches for previous occur-rences.character-search-backward (M-C-])A character is read and point is moved to the previous occur-rence of that character. A negative count searches for subse-quent occurrences.skip-csi-sequenceRead enough characters to consume a multi-key sequence such asthose defined for keys like Home and End. Such sequences beginwith a Control Sequence Indicator (CSI), usually ESC-[. If thissequence 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 com-ment-begin variable is inserted at the beginning of the currentline. If a numeric argument is supplied, this command acts as atoggle: if the characters at the beginning of the line do notmatch the value of comment-begin, the value is inserted, other-wise the characters in comment-begin are deleted from the begin-ning of the line. In either case, the line is accepted as if anewline had been typed. The default value of comment-begincauses this command to make the current line a shell comment.If a numeric argument causes the comment character to beremoved, the line will be executed by the shell.glob-complete-word (M-g)The word before point is treated as a pattern for pathnameexpansion, with an asterisk implicitly appended. This patternis used to generate a list of matching filenames for possiblecompletions.glob-expand-word (C-x *)The word before point is treated as a pattern for pathnameexpansion, and the list of matching filenames is inserted,replacing the word. If a numeric argument is supplied, anasterisk is appended before pathname expansion.glob-list-expansions (C-x g)The list of expansions that would have been generated byglob-expand-word is displayed, and the line is redrawn. If anumeric argument is supplied, an asterisk is appended beforepathname expansion.dump-functionsPrint all of the functions and their key bindings to the read-line output stream. If a numeric argument is supplied, the out-put is formatted in such a way that it can be made part of aninputrc file.dump-variablesPrint all of the settable readline variables and their values tothe readline output stream. If a numeric argument is supplied,the output is formatted in such a way that it can be made partof an inputrc file.dump-macrosPrint all of the readline key sequences bound to macros and thestrings they output. If a numeric argument is supplied, theoutput is formatted in such a way that it can be made part of aninputrc file.display-shell-version (C-x C-v)Display version information about the current instance of bash.
Programmable Completion
When word completion is attempted for an argument to a command forwhich a completion specification (a compspec) has been defined usingthe complete builtin (see SHELL BUILTIN COMMANDS below), the program-mable completion facilities are invoked.First, the command name is identified. If the command word is theempty string (completion attempted at the beginning of an empty line),any compspec defined with the -E option to complete is used. If acompspec has been defined for that command, the compspec is used togenerate the list of possible completions for the word. If the commandword is a full pathname, a compspec for the full pathname is searchedfor first. If no compspec is found for the full pathname, an attemptis made to find a compspec for the portion following the final slash.If those searches do not result in a compspec, any compspec definedwith the -D option to complete is used as the default.Once a compspec has been found, it is used to generate the list ofmatching words. If a compspec is not found, the default bash comple-tion as described above under Completing is performed.First, the actions specified by the compspec are used. Only matcheswhich are prefixed by the word being completed are returned. When the-f or -d option is used for filename or directory name completion, theshell variable FIGNORE is used to filter the matches.Any completions specified by a pathname expansion pattern to the -Goption are generated next. The words generated by the pattern need notmatch the word being completed. The GLOBIGNORE shell variable is notused to filter the matches, but the FIGNORE variable is used.Next, the string specified as the argument to the -W option is consid-ered. The string is first split using the characters in the IFS spe-cial variable as delimiters. Shell quoting is honored. Each word isthen expanded using brace expansion, tilde expansion, parameter andvariable expansion, command substitution, and arithmetic expansion, asdescribed above under EXPANSION. The results are split using the rulesdescribed above under Word Splitting. The results of the expansion areprefix-matched against the word being completed, and the matching wordsbecome the possible completions.After these matches have been generated, any shell function or commandspecified with the -F and -C options is invoked. When the command orfunction is invoked, the COMP_LINE, COMP_POINT, COMP_KEY, and COMP_TYPEvariables are assigned values as described above under Shell Variables.If a shell function is being invoked, the COMP_WORDS and COMP_CWORDvariables are also set. When the function or command is invoked, thefirst argument ($1) is the name of the command whose arguments arebeing completed, the second argument ($2) is the word being completed,and the third argument ($3) is the word preceding the word being com-pleted on the current command line. No filtering of the generated com-pletions against the word being completed is performed; the function orcommand has complete freedom in generating the matches.Any function specified with -F is invoked first. The function may useany of the shell facilities, including the compgen builtin describedbelow, to generate the matches. It must put the possible completionsin the COMPREPLY array variable, one per array element.Next, any command specified with the -C option is invoked in an envi-ronment equivalent to command substitution. It should print a list ofcompletions, one per line, to the standard output. Backslash may beused to escape a newline, if necessary.After all of the possible completions are generated, any filter speci-fied with the -X option is applied to the list. The filter is a pat-tern as used for pathname expansion; a & in the pattern is replacedwith the text of the word being completed. A literal & may be escapedwith a backslash; the backslash is removed before attempting a match.Any completion that matches the pattern will be removed from the list.A leading ! negates the pattern; in this case any completion not match-ing the pattern will be removed. If the nocasematch shell option isenabled, the match is performed without regard to the case of alpha-betic characters.Finally, any prefix and suffix specified with the -P and -S options areadded to each member of the completion list, and the result is returnedto 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 compspec wasdefined, directory name completion is attempted.If the -o plusdirs option was supplied to complete when the compspecwas defined, directory name completion is attempted and any matches areadded to the results of the other actions.By default, if a compspec is found, whatever it generates is returnedto the completion code as the full set of possible completions. Thedefault bash completions are not attempted, and the readline default offilename completion is disabled. If the -o bashdefault option was sup-plied to complete when the compspec was defined, the bash default com-pletions are attempted if the compspec generates no matches. If the -odefault option was supplied to complete when the compspec was defined,readline's default completion will be performed 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 a slashto completed names which are symbolic links to directories, subject tothe value of the mark-directories readline variable, regardless of thesetting of the mark-symlinked-directories readline variable.There is some support for dynamically modifying completions. This ismost useful when used in combination with a default completion speci-fied with complete -D. It's possible for shell functions executed ascompletion handlers to indicate that completion should be retried byreturning an exit status of 124. If a shell function returns 124, andchanges the compspec associated with the command on which completion isbeing attempted (supplied as the first argument when the function isexecuted), programmable completion restarts from the beginning, with anattempt to find a new compspec for that command. This allows a set ofcompletions to be built dynamically as completion is attempted, ratherthan being loaded all at once.For instance, assuming that there is a library of compspecs, each keptin a file corresponding to the name of the command, the followingdefault 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 default
HISTORY
When the -o history option to the set builtin is enabled, the shellprovides access to the command history, the list of commands previouslytyped. The value of the HISTSIZE variable is used as the number ofcommands to save in a history list. The text of the last HISTSIZE com-mands (default 500) is saved. The shell stores each command in thehistory list prior to parameter and variable expansion (see EXPANSIONabove) but after history expansion is performed, subject to the valuesof the shell variables HISTIGNORE and HISTCONTROL.On startup, the history is initialized from the file named by the vari-able HISTFILE (default ~/.bash_history). The file named by the valueof HISTFILE is truncated, if necessary, to contain no more than thenumber of lines specified by the value of HISTFILESIZE. If HISTFILE-SIZE is unset, or set to null, a non-numeric value, or a numeric valueless than zero, the history file is not truncated. When the historyfile is read, lines beginning with the history comment character fol-lowed immediately by a digit are interpreted as timestamps for the pre-ceding history line. These timestamps are optionally displayed depend-ing on the value of the HISTTIMEFORMAT variable. When a shell withhistory enabled exits, the last $HISTSIZE lines are copied from thehistory list to $HISTFILE. If the histappend shell option is enabled(see the description of shopt under SHELL BUILTIN COMMANDS below), thelines are appended to the history file, otherwise the history file isoverwritten. If HISTFILE is unset, or if the history file isunwritable, the history is not saved. If the HISTTIMEFORMAT variableis set, time stamps are written to the history file, marked with thehistory comment character, so they may be preserved across shell ses-sions. This uses the history comment character to distinguish time-stamps from other history lines. After saving the history, the historyfile is truncated to contain no more than HISTFILESIZE lines. If HIST-FILESIZE is unset, or set to null, a non-numeric value, or a numericvalue less than zero, the history file is not truncated.The builtin command fc (see SHELL BUILTIN COMMANDS below) may be usedto list or edit and re-execute a portion of the history list. The his-tory builtin may be used to display or modify the history list andmanipulate the history file. When using command-line editing, searchcommands are available in each editing mode that provide access to thehistory list.The shell allows control over which commands are saved on the historylist. The HISTCONTROL and HISTIGNORE variables may be set to cause theshell to save only a subset of the commands entered. The cmdhist shelloption, if enabled, causes the shell to attempt to save each line of amulti-line command in the same history entry, adding semicolons wherenecessary to preserve syntactic correctness. The lithist shell optioncauses the shell to save the command with embedded newlines instead ofsemicolons. See the description of the shopt builtin below under SHELLBUILTIN COMMANDS for information on setting and unsetting shelloptions.
HISTORY EXPANSION
The shell supports a history expansion feature that is similar to thehistory expansion in csh. This section describes what syntax featuresare available. This feature is enabled by default for interactiveshells, and can be disabled using the +H option to the set builtin com-mand (see SHELL BUILTIN COMMANDS below). Non-interactive shells do notperform history expansion by default.History expansions introduce words from the history list into the inputstream, making it easy to repeat commands, insert the arguments to aprevious command into the current input line, or fix errors in previouscommands quickly.History expansion is performed immediately after a complete line isread, before the shell breaks it into words. It takes place in twoparts. The first is to determine which line from the history list touse during substitution. The second is to select portions of that linefor inclusion into the current one. The line selected from the historyis the event, and the portions of that line that are acted upon arewords. Various modifiers are available to manipulate the selectedwords. The line is broken into words in the same fashion as when read-ing input, so that several metacharacter-separated words surrounded byquotes are considered one word. History expansions are introduced bythe appearance of the history expansion character, which is ! bydefault. Only backslash (\) and single quotes can quote the historyexpansion character, but the history expansion character is alsotreated as quoted if it immediately precedes the closing double quotein a double-quoted string.Several characters inhibit history expansion if found immediately fol-lowing the history expansion character, even if it is unquoted: space,tab, newline, carriage return, and =. If the extglob shell option isenabled, ( will also inhibit expansion.Several shell options settable with the shopt builtin may be used totailor the behavior of history expansion. If the histverify shelloption is enabled (see the description of the shopt builtin below), andreadline is being used, history substitutions are not immediatelypassed to the shell parser. Instead, the expanded line is reloadedinto the readline editing buffer for further modification. If readlineis being used, and the histreedit shell option is enabled, a failedhistory substitution will be reloaded into the readline editing bufferfor correction. The -p option to the history builtin command may beused to see what a history expansion will do before using it. The -soption to the history builtin may be used to add commands to the end ofthe history list without actually executing them, so that they areavailable for subsequent recall.The shell allows control of the various characters used by the historyexpansion mechanism (see the description of histchars above under ShellVariables). The shell uses the history comment character to mark his-tory timestamps when writing the history file.
Event Designators
An event designator is a reference to a command line entry in the his-tory list. Unless the reference is absolute, events are relative tothe 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.!-n Refer to the current command minus n.!! Refer to the previous command. This is a synonym for `!-1'.!stringRefer to the most recent command preceding the current positionin the history list starting with string.!?string[?]Refer to the most recent command preceding the current positionin the history list containing string. The trailing ? may beomitted if string is followed immediately by a newline.^string1^string2^Quick substitution. Repeat the previous command, replacingstring1 with string2. Equivalent to ``!!:s/string1/string2/''(see Modifiers below).!# The entire command line typed so far.
Word Designators
Word designators are used to select desired words from the event. A :separates the event specification from the word designator. It may beomitted if the word designator begins with a ^, $, *, -, or %. Wordsare numbered from the beginning of the line, with the first word beingdenoted by 0 (zero). Words are inserted into the current line sepa-rated by single spaces.0 (zero)The zeroth word. For the shell, this is the command word.n The nth word.^ The first argument. That is, word 1.$ The last word. This is usually the last argument, but willexpand to the zeroth word if there is only one word in the line.% The word matched by the most recent `?string?' search.x-y A range of words; `-y' abbreviates `0-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-$.x- Abbreviates x-$ like x*, but omits the last word.If a word designator is supplied without an event specification, theprevious command is used as the event.
Modifiers
After the optional word designator, there may appear a sequence of oneor more of the following modifiers, each preceded by a `:'.h Remove a trailing filename component, leaving only the head.t Remove all leading filename components, leaving the tail.r Remove a trailing suffix of the form .xxx, leaving the basename.e Remove all but the trailing suffix.p Print the new command but do not execute it.q Quote the substituted words, escaping further substitutions.x Quote the substituted words as with q, but break into words atblanks and newlines.s/old/new/Substitute new for the first occurrence of old in the eventline. Any delimiter can be used in place of /. The finaldelimiter is optional if it is the last character of the eventline. The delimiter may be quoted in old and new with a singlebackslash. If & appears in new, it is replaced by old. A sin-gle backslash will quote the &. If old is null, it is set tothe last old substituted, or, if no previous history substitu-tions took place, the last string in a !?string[?] search.& Repeat the previous substitution.g Cause changes to be applied over the entire event line. This isused in conjunction with `:s' (e.g., `:gs/old/new/') or `:&'.If used with `:s', any delimiter can be used in place of /, andthe final delimiter is optional if it is the last character ofthe event line. An a may be used as a synonym for g.G Apply the following `s' modifier once to each word in the eventline.
SHELL BUILTIN COMMANDS
Unless otherwise noted, each builtin command documented in this sectionas accepting options preceded by - accepts -- to signify the end of theoptions. The :, true, false, and test builtins do not accept optionsand do not treat -- specially. The exit, logout, return, break, con-tinue, let, and shift builtins accept and process arguments beginningwith - without requiring --. Other builtins that accept arguments butare not specified as accepting options interpret arguments beginningwith - as invalid options and require -- to prevent this interpreta-tion.: [arguments]No effect; the command does nothing beyond expanding argumentsand performing any specified redirections. The return status iszero.. filename [arguments]source filename [arguments]Read and execute commands from filename in the current shellenvironment 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 containingfilename. 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 optionto the shopt builtin command is turned off, the PATH is notsearched. If any arguments are supplied, they become the posi-tional parameters when filename is executed. Otherwise thepositional parameters are unchanged. If the -T option isenabled, source inherits any trap on DEBUG; if it is not, anyDEBUG trap string is saved and restored around the call tosource, and source unsets the DEBUG trap while it executes. If-T is not set, and the sourced file changes the DEBUG trap, thenew value is retained when source completes. The return statusis the status of the last command exited within the script (0 ifno 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 ofaliases in the form alias name=value on standard output. Whenarguments are supplied, an alias is defined for each name whosevalue is given. A trailing space in value causes the next wordto be checked for alias substitution when the alias is expanded.For each name in the argument list for which no value is sup-plied, the name and value of the alias is printed. Aliasreturns true unless a name is given for which no alias has beendefined.bg [jobspec ...]Resume each suspended job jobspec in the background, as if ithad been started with &. If jobspec is not present, the shell'snotion of the current job is used. bg jobspec returns 0 unlessrun when job control is disabled or, when run with job controlenabled, any specified jobspec was not found or was startedwithout 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 keysequence to a readline function or macro, or set a readlinevariable. Each non-option argument is a command as it wouldappear in .inputrc, but each binding or command must be passedas a separate argument; e.g., '"\C-x\C-r": re-read-init-file'.Options, if supplied, have the following meanings:-m keymapUse keymap as the keymap to be affected by the subsequentbindings. Acceptable keymap names are emacs, emacs-stan-dard, emacs-meta, emacs-ctlx, vi, vi-move, vi-command,and vi-insert. vi is equivalent to vi-command (vi-moveis also a synonym); emacs is equivalent to emacs-stan-dard.-l List the names of all readline functions.-p Display readline function names and bindings in such away that they can be re-read.-P List current readline function names and bindings.-s Display readline key sequences bound to macros and thestrings they output in such a way that they can be re-read.-S Display readline key sequences bound to macros and thestrings they output.-v Display readline variable names and values in such a waythat they can be re-read.-V List current readline variable names and values.-f filenameRead key bindings from filename.-q functionQuery about which keys invoke the named function.-u functionUnbind all keys bound to the named function.-r keyseqRemove any current binding for keyseq.-x keyseq:shell-commandCause shell-command to be executed whenever keyseq isentered. When shell-command is executed, the shell setsthe READLINE_LINE variable to the contents of the read-line line buffer and the READLINE_POINT variable to thecurrent location of the insertion point. If the executedcommand changes the value of READLINE_LINE or READ-LINE_POINT, those new values will be reflected in theediting state.-X List all key sequences bound to shell commands and theassociated commands in a format that can be reused asinput.The return value is 0 unless an unrecognized option is given oran error occurred.break [n]Exit from within a for, while, until, or select loop. If n isspecified, break n levels. n must be >= 1. If n is greaterthan the number of enclosing loops, all enclosing loops areexited. The return value is 0 unless n is not greater than orequal to 1.builtin shell-builtin [arguments]Execute the specified shell builtin, passing it arguments, andreturn its exit status. This is useful when defining a functionwhose name is the same as a shell builtin, retaining the func-tionality of the builtin within the function. The cd builtin iscommonly redefined this way. The return status is false ifshell-builtin is not a shell builtin command.caller [expr]Returns the context of any active subroutine call (a shell func-tion or a script executed with the . or source builtins). With-out expr, caller displays the line number and source filename ofthe current subroutine call. If a non-negative integer is sup-plied as expr, caller displays the line number, subroutine name,and source file corresponding to that position in the currentexecution call stack. This extra information may be used, forexample, to print a stack trace. The current frame is frame 0.The return value is 0 unless the shell is not executing a sub-routine call or expr does not correspond to a valid position inthe call stack.cd [-L|[-P [-e]] [-@]] [dir]Change the current directory to dir. if dir is not supplied,the value of the HOME shell variable is the default. Any addi-tional arguments following dir are ignored. The variable CDPATHdefines the search path for the directory containing dir: eachdirectory name in CDPATH is searched for dir. Alternativedirectory names in CDPATH are separated by a colon (:). A nulldirectory name in CDPATH is the same as the current directory,i.e., ``.''. If dir begins with a slash (/), then CDPATH is notused. The -P option causes cd to use the physical directorystructure by resolving symbolic links while traversing dir andbefore processing instances of .. in dir (see also the -P optionto the set builtin command); the -L option forces symbolic linksto be followed by resolving the link after processing instancesof .. in dir. If .. appears in dir, it is processed by removingthe immediately previous pathname component from dir, back to aslash or the beginning of dir. If the -e option is suppliedwith -P, and the current working directory cannot be success-fully determined after a successful directory change, cd willreturn an unsuccessful status. On systems that support it, the-@ option presents the extended attributes associated with afile as a directory. An argument of - is converted to $OLDPWDbefore the directory change is attempted. If a non-empty direc-tory name from CDPATH is used, or if - is the first argument,and the directory change is successful, the absolute pathname ofthe new working directory is written to the standard output.The return value is true if the directory was successfullychanged; false otherwise.command [-pVv] command [arg ...]Run command with args suppressing the normal shell functionlookup. Only builtin commands or commands found in the PATH areexecuted. If the -p option is given, the search for command isperformed using a default value for PATH that is guaranteed tofind all of the standard utilities. If either the -V or -voption is supplied, a description of command is printed. The -voption causes a single word indicating the command or filenameused to invoke command to be displayed; the -V option produces amore verbose description. If the -V or -v option is supplied,the exit status is 0 if command was found, and 1 if not. Ifneither option is supplied and an error occurred or command can-not be found, the exit status is 127. Otherwise, the exit sta-tus of the command builtin is the exit status of command.compgen [option] [word]Generate possible completion matches for word according to theoptions, which may be any option accepted by the completebuiltin with the exception of -p and -r, and write the matchesto the standard output. When using the -F or -C options, thevarious shell variables set by the programmable completionfacilities, while available, will not have useful values.The matches will be generated in the same way as if the program-mable completion code had generated them directly from a comple-tion specification with the same flags. If word is specified,only those completions matching word will be displayed.The return value is true unless an invalid option is supplied,or no matches were generated.complete [-abcdefgjksuv] [-o comp-option] [-DE] [-A action] [-G glob-pat] [-W wordlist] [-F function] [-C command][-X filterpat] [-P prefix] [-S suffix] name [name ...]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 themto be reused as input. The -r option removes a completion spec-ification for each name, or, if no names are supplied, all com-pletion 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 -Eoption indicates that the remaining options and actions shouldapply to ``empty'' command completion; that is, completionattempted on a blank line.The process of applying these completion specifications whenword completion is attempted is described above under Program-mable Completion.Other options, if specified, have the following meanings. Thearguments to the -G, -W, and -X options (and, if necessary, the-P and -S options) should be quoted to protect them from expan-sion before the complete builtin is invoked.-o comp-optionThe comp-option controls several aspects of the comp-spec's behavior beyond the simple generation of comple-tions. comp-option may be one of:bashdefaultPerform the rest of the default bash completionsif the compspec generates no matches.default Use readline's default filename completion ifthe compspec generates no matches.dirnamesPerform directory name completion if the comp-spec generates no matches.filenamesTell readline that the compspec generates file-names, so it can perform any filename-specificprocessing (like adding a slash to directorynames, quoting special characters, or suppress-ing trailing spaces). Intended to be used withshell functions.noquote Tell readline not to quote the completed wordsif they are filenames (quoting filenames is thedefault).nosort Tell readline not to sort the list of possiblecompletions alphabetically.nospace Tell readline not to append a space (thedefault) to words completed at the end of theline.plusdirsAfter any matches defined by the compspec aregenerated, directory name completion isattempted and any matches are added to theresults of the other actions.-A actionThe action may be one of the following to generate alist 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 bespecified 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 bespecified 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 bythe HOSTFILE shell variable.job Job names, if job control is active. May alsobe 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 setbuiltin.shopt Shell option names as accepted by the shoptbuiltin.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 spec-ified as -v.-C commandcommand is executed in a subshell environment, and itsoutput is used as the possible completions.-F functionThe shell function function is executed in the currentshell environment. When the function is executed, thefirst argument ($1) is the name of the command whosearguments are being completed, the second argument ($2)is the word being completed, and the third argument ($3)is the word preceding the word being completed on thecurrent command line. When it finishes, the possiblecompletions are retrieved from the value of the COMPRE-PLY array variable.-G globpatThe pathname expansion pattern globpat is expanded togenerate the possible completions.-P prefixprefix is added at the beginning of each possible com-pletion after all other options have been applied.-S suffixsuffix is appended to each possible completion after allother options have been applied.-W wordlistThe wordlist is split using the characters in the IFSspecial variable as delimiters, and each resultant wordis expanded. The possible completions are the membersof the resultant list which match the word being com-pleted.-X filterpatfilterpat is a pattern as used for pathname expansion.It is applied to the list of possible completions gener-ated by the preceding options and arguments, and eachcompletion matching filterpat is removed from the list.A leading ! in filterpat negates the pattern; in thiscase, any completion not matching filterpat is removed.The return value is true unless an invalid option is supplied,an option other than -p or -r is supplied without a name argu-ment, an attempt is made to remove a completion specificationfor a name for which no specification exists, or an error occursadding a completion specification.compopt [-o option] [-DE] [+o option] [name]Modify completion options for each name according to theoptions, or for the currently-executing completion if no namesare supplied. If no options are given, display the completionoptions for each name or the current completion. The possiblevalues of option are those valid for the complete builtindescribed above. The -D option indicates that the remainingoptions should apply to the ``default'' command completion; thatis, completion attempted on a command for which no completionhas previously been defined. The -E option indicates that theremaining options should apply to ``empty'' command completion;that is, completion attempted on a blank line.The return value is true unless an invalid option is supplied,an attempt is made to modify the options for a name for which nocompletion specification exists, or an output error occurs.continue [n]Resume the next iteration of the enclosing for, while, until, orselect loop. If n is specified, resume at the nth enclosingloop. n must be >= 1. If n is greater than the number ofenclosing loops, the last enclosing loop (the ``top-level''loop) is resumed. The return value is 0 unless n is not greaterthan or equal to 1.declare [-aAfFgilnrtux] [-p] [name[=value] ...]typeset [-aAfFgilnrtux] [-p] [name[=value] ...]Declare variables and/or give them attributes. If no names aregiven then display the values of variables. The -p option willdisplay the attributes and values of each name. When -p is usedwith name arguments, additional options, other than -f and -F,are ignored. When -p is supplied without name arguments, itwill display the attributes and values of all variables havingthe attributes specified by the additional options. If no otheroptions are supplied with -p, declare will display theattributes and values of all shell variables. The -f optionwill restrict the display to shell functions. The -F optioninhibits the display of function definitions; only the functionname and attributes are printed. If the extdebug shell optionis enabled using shopt, the source file name and line numberwhere each name is defined are displayed as well. The -F optionimplies -f. The -g option forces variables to be created ormodified at the global scope, even when declare is executed in ashell function. It is ignored in all other cases. The follow-ing options can be used to restrict output to variables with thespecified attribute or to give variables attributes:-a Each name is an indexed array variable (see Arraysabove).-A Each name is an associative array variable (see Arraysabove).-f Use function names only.-i The variable is treated as an integer; arithmetic evalua-tion (see ARITHMETIC EVALUATION above) is performed whenthe variable is assigned a value.-l When the variable is assigned a value, all upper-casecharacters are converted to lower-case. The upper-caseattribute is disabled.-n Give each name the nameref attribute, making it a namereference to another variable. That other variable isdefined by the value of name. All references, assign-ments, and attribute modifications to name, except thoseusing or changing the -n attribute itself, are performedon the variable referenced by name's value. The namerefattribute cannot be applied to array variables.-r Make names readonly. These names cannot then be assignedvalues by subsequent assignment statements or unset.-t Give each name the trace attribute. Traced functionsinherit the DEBUG and RETURN traps from the callingshell. The trace attribute has no special meaning forvariables.-u When the variable is assigned a value, all lower-casecharacters are converted to upper-case. The lower-caseattribute is disabled.-x Mark names for export to subsequent commands via theenvironment.Using `+' instead of `-' turns off the attribute instead, withthe exceptions that +a may not be used to destroy an array vari-able and +r will not remove the readonly attribute. When usedin a function, declare and typeset make each name local, as withthe local command, unless the -g option is supplied. If a vari-able name is followed by =value, the value of the variable isset to value. When using -a or -A and the compound assignmentsyntax to create array variables, additional attributes do nottake effect until subsequent assignments. The return value is 0unless an invalid option is encountered, an attempt is made todefine a function using ``-f foo=bar'', an attempt is made toassign a value to a readonly variable, an attempt is made toassign a value to an array variable without using the compoundassignment syntax (see Arrays above), one of the names is not avalid shell variable name, an attempt is made to turn off read-only status for a readonly variable, an attempt is made to turnoff array status for an array variable, or an attempt is made todisplay a non-existent function with -f.dirs [-clpv] [+n] [-n]Without options, displays the list of currently remembereddirectories. The default display is on a single line withdirectory names separated by spaces. Directories are added tothe list with the pushd command; the popd command removesentries from the list. The current directory is always thefirst directory in the stack.-c Clears the directory stack by deleting all of theentries.-l Produces a listing using full pathnames; the defaultlisting format uses a tilde to denote the home directory.-p Print the directory stack with one entry per line.-v Print the directory stack with one entry per line, pre-fixing each entry with its index in the stack.+n Displays the nth entry counting from the left of the listshown by dirs when invoked without options, starting withzero.-n Displays the nth entry counting from the right of thelist shown by dirs when invoked without options, startingwith zero.The return value is 0 unless an invalid option is supplied or nindexes beyond the end of the directory stack.disown [-ar] [-h] [jobspec ... | pid ... ]Without options, remove each jobspec from the table of activejobs. If jobspec is not present, and neither the -a nor the -roption is supplied, the current job is used. If the -h optionis given, each jobspec is not removed from the table, but ismarked so that SIGHUP is not sent to the job if the shellreceives a SIGHUP. If no jobspec is supplied, the -a optionmeans to remove or mark all jobs; the -r option without a job-spec argument restricts operation to running jobs. The returnvalue is 0 unless a jobspec does not specify a valid job.echo [-neE] [arg ...]Output the args, separated by spaces, followed by a newline.The return status is 0 unless a write error occurs. If -n isspecified, the trailing newline is suppressed. If the -e optionis given, interpretation of the following backslash-escapedcharacters is enabled. The -E option disables the interpreta-tion of these escape characters, even on systems where they areinterpreted by default. The xpg_echo shell option may be usedto dynamically determine whether or not echo expands theseescape characters by default. echo does not interpret -- tomean the end of options. echo interprets the following escapesequences:\a alert (bell)\b backspace\c suppress further output\e\E an escape character\f form feed\n new line\r carriage return\t horizontal tab\v vertical tab\\ backslash\0nnn the eight-bit character whose value is the octal valuennn (zero to three octal digits)\xHH the eight-bit character whose value is the hexadecimalvalue HH (one or two hex digits)\uHHHH the Unicode (ISO/IEC 10646) character whose value is thehexadecimal value HHHH (one to four hex digits)\UHHHHHHHHthe Unicode (ISO/IEC 10646) character whose value is thehexadecimal value HHHHHHHH (one to eight hex digits)enable [-a] [-dnps] [-f filename] [name ...]Enable and disable builtin shell commands. Disabling a builtinallows a disk command which has the same name as a shell builtinto be executed without specifying a full pathname, even thoughthe shell normally searches for builtins before disk commands.If -n is used, each name is disabled; otherwise, names areenabled. For example, to use the test binary found via the PATHinstead of the shell builtin version, run ``enable -n test''.The -f option means to load the new builtin command name fromshared object filename, on systems that support dynamic loading.The -d option will delete a builtin previously loaded with -f.If no name arguments are given, or if the -p option is supplied,a list of shell builtins is printed. With no other option argu-ments, the list consists of all enabled shell builtins. If -nis supplied, only disabled builtins are printed. If -a is sup-plied, the list printed includes all builtins, with an indica-tion of whether or not each is enabled. If -s is supplied, theoutput is restricted to the POSIX special builtins. The returnvalue is 0 unless a name is not a shell builtin or there is anerror loading a new builtin from a shared object.eval [arg ...]The args are read and concatenated together into a single com-mand. This command is then read and executed by the shell, andits exit status is returned as the value of eval. If there areno args, or only null arguments, eval returns 0.exec [-cl] [-a name] [command [arguments]]If command is specified, it replaces the shell. No new processis created. The arguments become the arguments to command. Ifthe -l option is supplied, the shell places a dash at the begin-ning of the zeroth argument passed to command. This is whatlogin(1) does. The -c option causes command to be executed withan empty environment. If -a is supplied, the shell passes nameas the zeroth argument to the executed command. If command can-not be executed for some reason, a non-interactive shell exits,unless the execfail shell option is enabled. In that case, itreturns failure. An interactive shell returns failure if thefile cannot be executed. If command is not specified, any redi-rections take effect in the current shell, and the return statusis 0. If there is a redirection error, the return status is 1.exit [n]Cause the shell to exit with a status of n. If n is omitted,the exit status is that of the last command executed. A trap onEXIT is executed before the shell terminates.export [-fn] [name[=word]] ...export -pThe supplied names are marked for automatic export to the envi-ronment of subsequently executed commands. If the -f option isgiven, the names refer to functions. If no names are given, orif the -p option is supplied, a list of names of all exportedvariables is printed. The -n option causes the export propertyto be removed from each name. If a variable name is followed by=word, the value of the variable is set to word. export returnsan exit status of 0 unless an invalid option is encountered, oneof the names is not a valid shell variable name, or -f is sup-plied with a name that is not a function.fc [-e ename] [-lnr] [first] [last]fc -s [pat=rep] [cmd]The first form selects a range of commands from first to lastfrom the history list and displays or edits and re-executesthem. First and last may be specified as a string (to locatethe last command beginning with that string) or as a number (anindex into the history list, where a negative number is used asan offset from the current command number). If last is notspecified it is set to the current command for listing (so that``fc -l -10'' prints the last 10 commands) and to first other-wise. If first is not specified it is set to the previous com-mand for editing and -16 for listing.The -n option suppresses the command numbers when listing. The-r option reverses the order of the commands. If the -l optionis given, the commands are listed on standard output. Other-wise, the editor given by ename is invoked on a file containingthose commands. If ename is not given, the value of the FCEDITvariable is used, and the value of EDITOR if FCEDIT is not set.If neither variable is set, vi is used. When editing is com-plete, the edited commands are echoed and executed.In the second form, command is re-executed after each instanceof pat is replaced by rep. Command is intepreted the same asfirst above. A useful alias to use with this is ``r="fc -s"'',so that typing ``r cc'' runs the last command beginning with``cc'' and typing ``r'' re-executes the last command.If the first form is used, the return value is 0 unless aninvalid option is encountered or first or last specify historylines out of range. If the -e option is supplied, the returnvalue is the value of the last command executed or failure if anerror occurs with the temporary file of commands. If the secondform is used, the return status is that of the command re-exe-cuted, unless cmd does not specify a valid history line, inwhich case fc returns failure.fg [jobspec]Resume jobspec in the foreground, and make it the current job.If jobspec is not present, the shell's notion of the current jobis used. The return value is that of the command placed intothe foreground, or failure if run when job control is disabledor, when run with job control enabled, if jobspec does not spec-ify a valid job or jobspec specifies a job that was startedwithout job control.getopts optstring name [args]getopts is used by shell procedures to parse positional parame-ters. optstring contains the option characters to be recog-nized; if a character is followed by a colon, the option isexpected to have an argument, which should be separated from itby white space. The colon and question mark characters may notbe used as option characters. Each time it is invoked, getoptsplaces the next option in the shell variable name, initializingname if it does not exist, and the index of the next argument tobe processed into the variable OPTIND. OPTIND is initialized to1 each time the shell or a shell script is invoked. When anoption requires an argument, getopts places that argument intothe variable OPTARG. The shell does not reset OPTIND automati-cally; it must be manually reset between multiple calls togetopts within the same shell invocation if a new set of parame-ters is to be used.When the end of options is encountered, getopts exits with areturn value greater than zero. OPTIND is set to the index ofthe first non-option argument, and name is set to ?.getopts normally parses the positional parameters, but if morearguments are given in args, getopts parses those instead.getopts can report errors in two ways. If the first characterof optstring is a colon, silent error reporting is used. Innormal operation, diagnostic messages are printed when invalidoptions or missing option arguments are encountered. If thevariable OPTERR is set to 0, no error messages will be dis-played, even if the first character of optstring is not a colon.If an invalid option is seen, getopts places ? into name and, ifnot silent, prints an error message and unsets OPTARG. Ifgetopts is silent, the option character found is placed inOPTARG and no diagnostic message is printed.If a required argument is not found, and getopts is not silent,a question mark (?) is placed in name, OPTARG is unset, and adiagnostic message is printed. If getopts is silent, then acolon (:) is placed in name and OPTARG is set to the optioncharacter found.getopts returns true if an option, specified or unspecified, isfound. It returns false if the end of options is encountered oran error occurs.hash [-lr] [-p filename] [-dt] [name]Each time hash is invoked, the full pathname of the command nameis determined by searching the directories in $PATH and remem-bered. Any previously-remembered pathname is discarded. If the-p option is supplied, no path search is performed, and filenameis used as the full filename of the command. The -r optioncauses the shell to forget all remembered locations. The -doption causes the shell to forget the remembered location ofeach name. If the -t option is supplied, the full pathname towhich each name corresponds is printed. If multiple name argu-ments are supplied with -t, the name is printed before thehashed full pathname. The -l option causes output to be dis-played in a format that may be reused as input. If no argumentsare given, or if only -l is supplied, information about remem-bered commands is printed. The return status is true unless aname is not found or an invalid option is supplied.help [-dms] [pattern]Display helpful information about builtin commands. If patternis specified, help gives detailed help on all commands matchingpattern; otherwise help for all the builtins and shell controlstructures is printed.-d Display a short description of each pattern-m Display the description of each pattern in a manpage-likeformat-s Display only a short usage synopsis for each patternThe return status is 0 unless no command matches pattern.history [n]history -chistory -d offsethistory -anrw [filename]history -p arg [arg ...]history -s arg [arg ...]With no options, display the command history list with line num-bers. Lines listed with a * have been modified. An argument ofn lists only the last n lines. If the shell variable HISTTIME-FORMAT is set and not null, it is used as a format string forstrftime(3) to display the time stamp associated with each dis-played history entry. No intervening blank is printed betweenthe formatted time stamp and the history line. If filename issupplied, it is used as the name of the history file; if not,the value of HISTFILE is used. Options, if supplied, have thefollowing meanings:-c Clear the history list by deleting all the entries.-d offsetDelete the history entry at position offset.-a Append the ``new'' history lines to the history file.These are history lines entered since the beginning ofthe current bash session, but not already appended to thehistory file.-n Read the history lines not already read from the historyfile into the current history list. These are linesappended to the history file since the beginning of thecurrent bash session.-r Read the contents of the history file and append them tothe current history list.-w Write the current history list to the history file, over-writing the history file's contents.-p Perform history substitution on the following args anddisplay the result on the standard output. Does notstore the results in the history list. Each arg must bequoted to disable normal history expansion.-s Store the args in the history list as a single entry.The last command in the history list is removed beforethe args are added.If the HISTTIMEFORMAT variable is set, the time stamp informa-tion associated with each history entry is written to the his-tory file, marked with the history comment character. When thehistory file is read, lines beginning with the history commentcharacter followed immediately by a digit are interpreted astimestamps for the following history entry. The return value is0 unless an invalid option is encountered, an error occurs whilereading or writing the history file, an invalid offset is sup-plied as an argument to -d, or the history expansion supplied asan argument to -p fails.jobs [-lnprs] [ jobspec ... ]jobs -x command [ args ... ]The first form lists the active jobs. The options have the fol-lowing meanings:-l List process IDs in addition to the normal information.-n Display information only about jobs that have changedstatus since the user was last notified of their status.-p List only the process ID of the job's process groupleader.-r Display only running jobs.-s Display only stopped jobs.If jobspec is given, output is restricted to information aboutthat job. The return status is 0 unless an invalid option isencountered or an invalid jobspec is supplied.If the -x option is supplied, jobs replaces any jobspec found incommand or args with the corresponding process group ID, andexecutes command passing it args, returning its exit status.kill [-s sigspec | -n signum | -sigspec] [pid | jobspec] ...kill -l|-L [sigspec | exit_status]Send the signal named by sigspec or signum to the processesnamed by pid or jobspec. sigspec is either a case-insensitivesignal name such as SIGKILL (with or without the SIG prefix) ora signal number; signum is a signal number. If sigspec is notpresent, then SIGTERM is assumed. An argument of -l lists thesignal names. If any arguments are supplied when -l is given,the names of the signals corresponding to the arguments arelisted, and the return status is 0. The exit_status argument to-l is a number specifying either a signal number or the exitstatus of a process terminated by a signal. The -L option isequivalent to -l. kill returns true if at least one signal wassuccessfully sent, or false if an error occurs or an invalidoption is encountered.let arg [arg ...]Each arg is an arithmetic expression to be evaluated (see ARITH-METIC EVALUATION above). If the last arg evaluates to 0, letreturns 1; 0 is returned otherwise.local [option] [name[=value] ... | - ]For each argument, a l
bash shell参考文档相关推荐
- linux自动化脚本制作参考文档
linux自动化脚本制作参考文档 一.环境部分 1.0.启动盘制作 前提:1个8G以上的U盘,想要安装的系统ISO镜像 参考连接: 1.windows系统 #打开'运行' => win + r ...
- View4.5测试参考文档7--View Administrator安装、配置、创建桌面池
View4.5测试参考文档7--View Administrator安装.配置.创建桌面池 见附件! 转载于:https://blog.51cto.com/ieihihc/471642
- CHM格式的可以全文搜索的Spring3.2官方参考文档
Spring的官方参考文档是html格式的,并且没有目录树,用它本身的跳转功能,跳来跳去经常把头给跳晕了! 最重要的一个缺点是没有全文搜索,于是一生气就做了一个CHM格式的有目录,带全文搜索的 ...
- 教您怎么从spring 官网下载参考文档
假如您使用spring,那么本经验可能帮助到您. 假如您使用spring的过程中,需要查询一些文档,那么本经验可能帮助到您. 假如您对下载spring的文档有疑惑,那么本经验可能帮助到您. 教您怎么从 ...
- RxJava 参考文档
/**************************************************************** RxJava 参考文档* 说明:* 最近无意中发现RxJava这个好 ...
- Python 参考文档
Python 参考文档 笔者在学习 Python ,查找相关资料时觉得比较有用的参考文档,将持续更新- python 官方文档 简明 Python 教程 PyCharm(2018.2)专业版破解PyC ...
- PyQt5 参考文档
PyQt5 参考文档 笔者在 PyQt5 实践中遇到问题,查找相关资料时觉得比较有用的参考文档,将持续更新- PyQt5 官方文档(英文) PyQt5 官方文档(中文) PyQt5 实现控制台显示功能 ...
- Python-OpenCV 参考文档
Python-OpenCV 参考文档 笔者在 Python-OpenCV 实践中遇到问题,查找相关资料时觉得比较有用的参考文档.将持续更新- 官方文档 1.在图片/视频中添加中文
- mpvue 从零开始 女友拉黑了我 5 不在以下request 合法域名列表中,请参考文档
上一篇,才调通了接口,试了几次,都成功,突然,微信报错了. VM6239:1 https://www.easy-mock.com 不在以下 request 合法域名列表中,请参考文档:https:// ...
- mysql 5.5免安装配置_mysql的参考文档mysql5.5.21免安装版的配置方法
mysql的5.5版本(与5.1版本有所区别)中my.ini文件的内容. 在mysql根目录里新建my.ini文件,用阅读器打开(加入如下内容) [client] #password = your_p ...
最新文章
- WinCE5.0中应用程序如何直接写屏
- 遇到 HTTP 错误 403.14 - Forbidden?
- 新手做自媒体运营了解这几个步骤,运营效率提高5倍!(附教程)
- Android中程序向桌面和Launcher添加快捷方式
- 【运营】盘点2014,有哪些O2O名牌被撕。
- QT udp自动获取对方ip和端口号
- @param注解_启用 parameters 编译选项简化 mybatis @Param 注解重复问题
- 【Python基础】一文搞定pandas的数据合并
- BlueStore——先进的用户态文件系统《一》
- iview table 方法若干
- linux 系统yum下安装vnc
- gridsearchcv参数_Python机器学习库Sklearn系列教程(21)-参数优化
- JDBC的数据库的基础事务管理
- 自动化中间人攻击工具subterfuge小实验
- HDU 5050 Divided Land(进制转换)
- 使用Docker部署ShareLaTex并简单配置中文环境
- PPT科研绘图:用PPT绘图,保存为eps并导入Latex
- php除数不能为零,0为什么不能做除数(为什么0不能作为除数)
- golang实现最简单的麻将胡牌算法(不包括牌型,有需求后续可以更新牌型计算)
- Centos8安装GitLab14.2开源代码托管工具
热门文章
- 什么是国外广告联盟?国外广告联盟怎么赚钱?为什么你做不赚钱?
- War3地图编辑器基础:物体编辑器F6(自定义单位+单位属性设置)
- 用户如何制作360度全景图?360度全景图有什么用?
- coco2d-x 或者 creator 实现物体点击后的果冻效果
- win11最新bug修复合集(来源于微软官方)
- 箱形图的优缺点,python绘制箱形图
- 高精度定位赋能行业创新,Petal Maps Platform 创新地图平台能力
- 计算机云平台热门吗,哪个云电脑好用又便宜?国内的云游戏平台到底哪个好?
- 架构设计:网络附属存储NAS,块存储EBS与对象存储OSS的比较以及选用
- 【零样本知识蒸馏】(六)NeutIPS 2019:Zero-shot knowledge transfer via adversarial belief matching