| {: , : , : 157, : 954, : } |
| {: , : , : 350, : 2378, : } |
| {: , : , : 427, : 2569, : } |
| {: , : , : 87, : 569, : } |
| {: , : , : 113, : 720, : } |
| {: , : , : 138, : 870, : } |
| {: , : , : 103, : 675, : } |
| {: , : , : 63, : 378, : } |
| {: , : , : 31, : 195, : } |
| {: , : , : 164, : 1025, : ’) preserves the literal value of all 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 history expansion is enabled. The characters ‘$’ and ‘‘’ retain their special meaning within double quotes. The backslash retains its special meaning only when followed by one of the following characters: ‘$’, ‘‘’, ‘\} |
| {: , : , : 167, : 1050, : \n\ndouble quote\n\n\\?\n\nquestion mark\n\n\\nnn\n\nThe eight-bit character whose value is the octal value nnn (one to three octal digits).\n\n\\xHH\n\nThe eight-bit character whose value is the hexadecimal value HH (one or two hex digits).\n\n\\uHHHH\n\nThe Unicode (ISO/IEC 10646) character whose value is the hexadecimal value HHHH (one to four hex digits).\n\n\\UHHHHHHHH\nThe Unicode (ISO/IEC 10646) character whose value is the hexadecimal value HHHHHHHH (one to eight hex digits).\n\\cx\n\nA control-x character.\n\nThe expanded result is single-quoted, as if the dollar sign had not been present. |
| chapter_titleBasic Shell Featuressection_titleLocale-Specific Translationnum_wordsnum_charstextPrefixing a double-quoted string with a dollar sign (‘$’), such as $\, causes the string to be translated according to the current locale. The gettext infrastructure performs the lookup and translation, using the LC_MESSAGES, TEXTDOMAINDIR, and TEXTDOMAIN shell variables, as explained below. See the gettext documentation for additional details not covered here. If the current locale is C or POSIX, if there are no translations available, or if the string is not translated, the dollar sign is ignored, and the string is treated as double-quoted. Since this is a form of double quoting, the string remains double-quoted by default, whether or not it is translated and replaced. If the noexpand_translation option is enabled using the shopt builtin, translated strings are single-quoted instead of double-quoted.\n\nThe rest of this section is a brief overview of how you use gettext to create translations for strings in a shell script named scriptname. There are more details in the gettext documentation. Once you’ve marked the strings in your script that you want to translate using $\, you create a gettext \ file using the command bash --dump-po-strings scriptname > domain.pot The domain is your message domain. It’s just an arbitrary string that’s used to identify the files gettext needs, like a package or script name. It needs to be unique among all the message domains on systems where you install the translations, so gettext knows which translations correspond to your script. You’ll use the template file to create translations for each target language. The template file conventionally has the suffix ‘.pot’. You copy this template file to a separate file for each target language you want to support (called \ files, which use the suffix ‘.po’). PO files use various naming conventions, but when you are working to translate a template file into a particular language, you first copy the template file to a file whose name is the language you want to target, with the ‘.po’ suffix. For instance, the Spanish translations of your strings would be in a file named ‘es.po’, and to get started using a message domain named \ you would run cp example.pot es.po Ultimately, PO files are often named domain.po and installed in directories that contain multiple translation files for a particular language. Whichever naming convention you choose, you will need to translate the strings in the PO files into the appropriate languages. This has to be done manually. When you have the translations and PO files complete, you’ll use the gettext tools to produce what are called \ files, which are compiled versions of the PO files the gettext tools use to look up translations efficiently. MO files are also called \ files. You use the msgfmt program to do this. For instance, if you had a file with Spanish translations, you could run msgfmt -o es.mo es.po to produce the corresponding MO file. Once you have the MO files, you decide where to install them and use the TEXTDOMAINDIR shell variable to tell the gettext tools where they are. Make sure to use the same message domain to name the MO files as you did for the PO files when you install them. Your users will use the LANG or LC_MESSAGES shell variables to select the desired language. You set the TEXTDOMAIN variable to the script’s message domain. As above, you use the message domain to name your translation files. You, or possibly your users, set the TEXTDOMAINDIR variable to the name of a directory where the message catalog files are stored. If you install the message files into the system’s standard message catalog directory, you don’t need to worry about this variable. The directory where the message catalog files are stored varies between systems. Some use the message catalog selected by the LC_MESSAGES shell variable. Others create the name of the message catalog from the value of the TEXTDOMAIN shell variable, possibly adding the ‘.mo’ suffix. If you use the TEXTDOMAIN variable, you may need to set the TEXTDOMAINDIR variable to the location of the message catalog files, as above. It’s common to use both variables in this fashion: $TEXTDOMAINDIR/$LC_MESSAGES/LC MESSAGES/$TEXTDOMAIN.mo.\n\nIf you used that last convention, and you wanted to store the message catalog files with Spanish (es) and Esperanto (eo) translations into a local directory you use for custom translation files, you could run\nTEXTDOMAIN=example\nTEXTDOMAINDIR=/usr/local/share/locale\ncp es.mo ${TEXTDOMAINDIR}/es/LC_MESSAGES/${TEXTDOMAIN}.mo cp eo.mo ${TEXTDOMAINDIR}/eo/LC_MESSAGES/${TEXTDOMAIN}.mo When all of this is done, and the message catalog files containing the compiled translations are installed in the correct location, your users will be able to see translated strings in any of the supported languages by setting the LANG or LC_MESSAGES environment variables before running your script. |
| chapter_titleBasic Shell Featuressection_titleCommentsnum_wordsnum_charstextIn a non-interactive shell, or an interactive shell in which the interactive_comments option to the shopt builtin is enabled, a word beginning with ‘#’ introduces a comment. A word begins at the beginning of a line, after unquoted whitespace, or after an operator. The comment causes that word and all remaining characters on that line to be ignored. An interactive shell without the interactive_ comments option enabled does not allow comments. The interactive_comments option is enabled by default in interactive shells. description of what makes a shell interactive. |
| chapter_titleBasic Shell Featuressection_titleShell Commandsnum_wordsnum_charstextA simple shell command such as echo a b c consists of the command itself followed by arguments, separated by spaces. More complex shell commands are composed of simple commands arranged together in a variety of ways: in a pipeline in which the output of one command becomes the input of a second, in a loop or conditional construct, or in some other grouping. |
| chapter_titleBasic Shell Featuressection_titleReserved Wordsnum_wordsnum_charstextReserved words are words that have special meaning to the shell. They are used to begin and end the shell’s compound commands. The following words are recognized as reserved when unquoted and the first word of a command (see below for exceptions):\nif\nthen\nelif\nelse\nfi\ntime\nfor\nin\nuntil while do\ndone\ncase\nesac\ncoproc select function { } [[ ]] ! in is recognized as a reserved word if it is the third word of a case or select command. in and do are recognized as reserved words if they are the third word in a for command. |
| chapter_titleBasic Shell Featuressection_titleSimple Commandsnum_wordsnum_charstextA simple command is the kind of command that’s executed most often. It’s just a sequence of words separated by blanks, terminated by one of the shell’s control operators. The first word generally specifies a command to be executed, with the rest of the words being that command’s arguments. The return status of a simple command is its exit status as provided by the posix 1003.1 waitpid function, or 128+n if the command was terminated by signal n. |
| chapter_titleBasic Shell Featuressection_titlePipelinesnum_wordsnum_charstextA pipeline is a sequence of one or more commands separated by one of the control operators ‘|’ or ‘|&’. The format for a pipeline is [time [-p]] [!] command1 [ | or |& command2 ]... The output of each command in the pipeline is connected via a pipe to the input of the next command. That is, each command reads the previous command’s output. This connection is performed before any redirections specified by command1. If ‘|&’ is the pipeline operator, command1’s standard error, in addition to its standard output, is connected to command2’s standard input through the pipe; it is shorthand for 2>&1 |. This implicit redirection of the standard error to the standard output is performed after any redirections specified by command1, consistent with that shorthand. If the reserved word time precedes the pipeline, Bash prints timing statistics for the pipeline once it finishes. The statistics currently consist of elapsed (wall-clock) time and user and system time consumed by the command’s execution. The -p option changes the output format to that specified by posix. When the shell is in posix mode, it does not recognize time as a reserved word if the next token begins with a ‘-’. The value of the TIMEFORMAT variable is a format string that specifies how the timing information should be displayed.\nfor a description of the available formats. Providing time as a reserved word permits the\ntiming of shell builtins, shell functions, and pipelines. An external time command cannot time these easily. When the shell is in posix mode, you can use time by itself as a simple command. In this case, the shell displays the total user and system time consumed by the shell and its children. The TIMEFORMAT variable specifies the format of the time information. If a pipeline is not executed asynchronously, the shell waits for all commands in the pipeline to complete. Each command in a multi-command pipeline, where pipes are created, is executed in its own subshell, which is a separate process. If the lastpipe option is enabled using the shopt builtin, and job control is not active, the last element of a pipeline may be run by the shell process. The exit status of a pipeline is the exit status of the last command in the pipeline, unless the pipefail option is enabled. If pipefail is enabled, the pipeline’s return status is the value of the last (rightmost) command to exit with a non-zero status, or zero if all commands exit successfully. If the reserved word ‘!’ precedes the pipeline, the exit status is the logical negation of the exit status. If a pipeline is not executed asynchronously, the shell waits for all commands in the pipeline to terminate before returning a value. The return status of an asynchronous pipeline is 0. |
| chapter_titleBasic Shell Featuressection_titleLists of Commandsnum_wordsnum_charstextA list is a sequence of one or more pipelines separated by one of the operators ‘;’, ‘&’, ‘&&’, or ‘||’, and optionally terminated by one of ‘;’, ‘&’, or a 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 to delimit commands, equivalent to a semicolon. If a command is terminated by the control operator ‘&’, the shell executes the command asynchronously in a subshell. This is known as executing the command in the background, and these are referred to as asynchronous commands. The shell does not wait for the command to finish, and the return status is 0 (true). When job control is not active, the standard input for asynchronous commands, in the absence of any explicit redirections, is redirected from /dev/null. Commands separated by a ‘;’ are executed sequentially; the shell waits for each command to terminate in turn. The return status is the exit status of the last command executed. and and or lists are sequences of one or more pipelines separated by the control operators ‘&&’ and ‘||’, respectively. and and or lists are executed with left associativity. An and list has the form command1 && command2 command2 is executed if, and only if, command1 returns an exit status of zero (success). An or list has the form command1 || command2 command2 is executed if, and only if, command1 returns a non-zero exit status. The return status of and and or lists is the exit status of the last command executed in the list. |
| chapter_titleBasic Shell Featuressection_titleCompound Commandsnum_wordsnum_charstextCompound commands are the shell programming language constructs. Each construct begins with a reserved word or control operator and is terminated by a corresponding reserved word or operator. Any redirections associated with a compound command apply to all commands within that compound command unless explicitly overridden. In most cases a list of commands in a compound command’s description may be separated from the rest of the command by one or more newlines, and may be followed by a newline in place of a semicolon. Bash provides looping constructs, conditional commands, and mechanisms to group commands and execute them as a unit. |
| chapter_titleBasic Shell Featuressection_titleLooping Constructsnum_wordsnum_charstextBash supports the following looping constructs. Note that wherever a ‘;’ appears in the description of a command’s syntax, it may be replaced with one or more newlines.\nuntil\n\nThe syntax of the until command is:\nuntil test-commands; do consequent-commands; done\nExecute consequent-commands as long as test-commands has an exit status which is not zero. The return status is the exit status of the last command executed in consequent-commands, or zero if none was executed.\n\nwhile\n\nThe syntax of the while command is:\nwhile test-commands; do consequent-commands; done\nExecute consequent-commands as long as test-commands has an exit status of zero. The return status is the exit status of the last command executed in consequent-commands, or zero if none was executed.\n\nfor\n\nThe syntax of the for command is:\nfor name [ [in words...]; ] do commands; done\nExpand words, and then execute commands once for each word in the resultant list, with name bound to the current word. If ‘in words’ is not present, the for command executes the commands once for each positional parameter that is set, as if ‘in \’ had been specified. The return status is the exit status of the last command that executes. If there are no items in the expansion of words, no commands are executed, and the return status is zero. There is an alternate form of the for command which is similar to the C language:\nfor (( expr1; expr2; expr3 )) [;] do commands; done\nFirst, evaluate the arithmetic expression expr1 according to the rules described below. Then, repeatedly evaluate the arithmetic expression expr2 until it evaluates to zero. Each time expr2 evaluates to a non-zero value, execute commands and evaluate the arithmetic expression expr3. If any expression is omitted, it behaves as if it evaluates to\n1. The return value is the exit status of the last command in commands that\nis executed, or non-zero if any of the expressions is invalid.\n\nUse the break and continue builtins to control loop execution. |
| chapter_titleBasic Shell Featuressection_titleConditional Constructsnum_wordsnum_charstextif\n\nThe syntax of the if command is:\nif test-commands; then\nconsequent-commands; [elif more-test-commands; then\n\nmore-consequents;] [else alternate-consequents;]\nfi\nThe test-commands list is executed, and if its return status is zero, the consequent-commands list is executed. If test-commands returns a non-zero status, each elif list is executed in turn, and if its exit status is zero, the corresponding more-consequents is executed and the command completes. If ‘else alternate-consequents’ is present, and the final command in the final\nif or elif clause has a non-zero exit status, then alternate-consequents is\nexecuted. The return status is the exit status of the last command executed, or zero if no condition tested true.\ncase\n\nThe syntax of the case command is:\ncase word in\n[ [(] pattern [| pattern]...) command-list;;]...\nesac\ncase will selectively execute the command-list corresponding to the first pattern\nthat matches word, proceeding from the first pattern to the last. The match is performed according to the rules described below in Section 3.5.8.1 [Pattern Matching], page 39. If the nocasematch shell option (see the description of shopt in Section 4.3.2 [The Shopt Builtin], page 78) is enabled, the match is performed without regard to the case of alphabetic characters. The ‘|’ is used to separate multiple patterns in a pattern list, and the ‘)’ operator terminates the pattern list. A pattern list and an associated command-list is known as a clause. Each clause must be terminated with ‘;;’, ‘;&’, or ‘;;&’. The word undergoes tilde expansion, parameter expansion, command substitution, process substitution, arithmetic expansion, and quote removal before the shell attempts to match the pattern. Each pattern undergoes tilde expansion, parameter expansion, command substitution, arithmetic expansion, process substitution, and quote removal. There may be an arbitrary number of case clauses, each terminated by a ‘;;’, ‘;&’, or ‘;;&’. The first pattern that matches determines the command-list that is executed. It’s a common idiom to use ‘*’ as the final pattern to define the default case, since that pattern will always match. Here is an example using case in a script that could be used to describe one interesting feature of an animal: echo -n \ read ANIMAL echo -n \\ncase $ANIMAL in\nhorse | dog | cat) echo -n \"four\";; man | kangaroo ) echo -n \"two\";; *) echo -n \"an unknown number of\";;\nesac\necho \" legs.\"\n\nIf the ‘;;’ operator is used, the case command completes after the first pattern match. Using ‘;&’ in place of ‘;;’ causes execution to continue with the command-list associated with the next clause, if any. Using ‘;;&’ in place of ‘;;’ causes the shell to test the patterns in the next clause, if any, and execute any associated command-list if the match succeeds, continuing the case statement execution as if the pattern list had not matched. The return status is zero if no pattern matches. Otherwise, the return status is the exit status of the last command-list executed. select The select construct allows the easy generation of menus. It has almost the same syntax as the for command: select name [in words...]; do commands; done First, expand the list of words following in, generating a list of items, and print the set of expanded words on the standard error stream, each preceded by a number. If the ‘in words’ is omitted, print the positional parameters, as if ‘in \"$@\"’ had been specified. select then displays the PS3 prompt and reads a line from the standard input. If the line consists of a number corresponding to one of the displayed words, then select sets the value of name to that word. If the line is empty, select displays the words and prompt again. If EOF is read, select completes and returns 1. Any other value read causes name to be set to null. The line read is saved in the variable REPLY. The commands are executed after each selection until a break command is executed, at which point the select command completes. Here is an example that allows the user to pick a filename from the current directory, and displays the name and index of the file selected. select fname in *;\ndo\necho you picked $fname \\($REPLY\\) break;\ndone\n((...)) (( expression )) The arithmetic expression is evaluated according to the rules described below . The expression undergoes the same expansions as if it were within double quotes, but unescaped double quote characters in expression are not treated specially and are removed. Since this can potentially result in empty strings, this command treats those as expressions that evaluate to 0. If the value of the expression is non-zero, the return status is 0; otherwise the return status is 1. [[...]] [[ expression ]] Evaluate the conditional expression expression and return a status of zero (true) or non-zero (false). Expressions are composed of the primaries described below\n\nin Section 6.4 [Bash Conditional Expressions], page 105. The words between the [[ and ]] do not undergo word splitting and filename expansion. The shell performs tilde expansion, parameter and variable expansion, arithmetic expansion, command substitution, process substitution, and quote removal on those words. Conditional operators such as ‘-f’ must be unquoted to be recognized as primaries. When used with [[, the ‘<’ and ‘>’ operators sort lexicographically using the current locale. When the ‘==’ and ‘!=’ operators are used, the string to the right of the operator is considered a pattern and matched according to the rules described below in Section 3.5.8.1 [Pattern Matching], page 39, as if the extglob shell option were enabled. The ‘=’ operator is identical to ‘==’. If the nocasematch shell option (see the description of shopt in Section 4.3.2 [The Shopt Builtin], page 78) is enabled, the match is performed without regard to the case of alphabetic characters. The return value is 0 if the string matches (‘==’) or does not match (‘!=’) the pattern, and 1 otherwise. If you quote any part of the pattern, using any of the shell’s quoting mechanisms, the quoted portion is matched literally. This means every character in the quoted portion matches itself, instead of having any special pattern matching meaning. An additional binary operator, ‘=~’, is available, with the same precedence as ‘==’ and ‘!=’. When you use ‘=~’, the string to the right of the operator is considered a posix extended regular expression pattern and matched accordingly (using the posix regcomp and regexec interfaces usually described in regex (3)). The return value is 0 if the string matches the pattern, and 1 if it does not. If the regular expression is syntactically incorrect, the conditional expression returns 2. If the nocasematch shell option (see the description of shopt in Section 4.3.2 [The Shopt Builtin], page 78) is enabled, the match is performed without regard to the case of alphabetic characters. You can quote any part of the pattern to force the quoted portion to be matched literally instead of as a regular expression (see above). If the pattern is stored in a shell variable, quoting the variable expansion forces the entire pattern to be matched literally. The match succeeds if the pattern matches any part of the string. If you want to force the pattern to match the entire string, anchor the pattern using the ‘^’ and ‘$’ regular expression operators. For example, the following will match a line (stored in the shell variable line)\nif there is a sequence of characters anywhere in the value consisting of any\nnumber, including zero, of characters in the space character class, immediately followed by zero or one instances of ‘a’, then a ‘b’: [[ $line =~ [[:space:]]*(a)?b ]] That means values for line like ‘aab’, ‘ aaaaaab’, ‘xaby’, and ‘ ab’ will all match, as will a line containing a ‘b’ anywhere in its value. If you want to match a character that’s special to the regular expression grammar (‘^$|[]()\\.*+?’), it has to be quoted to remove its special meaning. This\n\nmeans that in the pattern ‘xxx.txt’, the ‘.’ matches any character in the string (its usual regular expression meaning), but in the pattern ‘\’, it can only match a literal ‘.’. Likewise, if you want to include a character in your pattern that has a special meaning to the regular expression grammar, you must make sure it’s not quoted. If you want to anchor a pattern at the beginning or end of the string, for instance, you cannot quote the ‘^’ or ‘$’ characters using any form of shell quoting. If you want to match ‘initial string’ at the start of a line, the following will work: [[ $line =~ ^\ ]] but this will not: [[ $line =~ \ ]] because in the second example the ‘^’ is quoted and doesn’t have its usual special meaning. It is sometimes difficult to specify a regular expression properly without using quotes, or to keep track of the quoting used by regular expressions while paying attention to shell quoting and the shell’s quote removal. Storing the regular expression in a shell variable is often a useful way to avoid problems with quoting characters that are special to the shell. For example, the following is equivalent to the pattern used above:\npattern=’[[:space:]]*(a)?b’\n[[ $line =~ $pattern ]] Shell programmers should take special care with backslashes, since backslashes are used by both the shell and regular expressions to remove the special meaning from the following character. This means that after the shell’s word expansions complete, any backslashes remaining in parts of the pattern that were originally not quoted can remove the special meaning of pattern characters. If any part of the pattern is quoted, the shell does its best to ensure that the regular expression treats those remaining backslashes as literal, if they appeared in a quoted portion. The following two sets of commands are not equivalent:\npattern=’\\.’\n[[. =~ $pattern ]] [[. =~ \\. ]] [[. =~ \ ]] [[. =~ ’\\.’ ]] The first two matches will succeed, but the second two will not, because in the second two the backslash will be part of the pattern to be matched. In the first two examples, the pattern passed to the regular expression parser is ‘\\.’. The backslash removes the special meaning from ‘.’, so the literal ‘.’ matches. In the second two examples, the pattern passed to the regular expression parser\n\nhas the backslash quoted (e.g., ‘\\\\\\.’), which will not match the string, since it does not contain a backslash. If the string in the first examples were anything other than ‘.’, say ‘a’, the pattern would not match, because the quoted ‘.’ in the pattern loses its special meaning of matching any single character. Bracket expressions in regular expressions can be sources of errors as well, since characters that are normally special in regular expressions lose their special meanings between brackets. However, you can use bracket expressions to match special pattern characters without quoting them, so they are sometimes useful\nfor this purpose.\nThough it might seem like a strange way to write it, the following pattern will match a ‘.’ in the string: [[. =~ [.] ]] The shell performs any word expansions before passing the pattern to the regular expression functions, so you can assume that the shell’s quoting takes precedence. As noted above, the regular expression parser will interpret any unquoted backslashes remaining in the pattern after shell expansion according to its own rules. The intention is to avoid making shell programmers quote things twice as much as possible, so shell quoting should be sufficient to quote special pattern characters where that’s necessary. The array variable BASH_REMATCH records which parts of the string matched the pattern. The element of BASH_REMATCH with index 0 contains the portion of the string matching the entire regular expression. Substrings matched by parenthesized subexpressions within the regular expression are saved in the remaining BASH_REMATCH indices. The element of BASH_REMATCH with index n is the portion of the string matching the nth parenthesized subexpression. Bash sets BASH_REMATCH in the global scope; declaring it as a local variable will lead to unexpected results. Expressions may be combined using the following operators, listed in decreasing order of precedence: ( expression ) Returns the value of expression. This may be used to override the normal precedence of operators. ! expression True if expression is false. expression1 && expression2 True if both expression1 and expression2 are true. expression1 || expression2 True if either expression1 or expression2 is true. The && and || operators do not evaluate expression2 if the value of expression1 is sufficient to determine the return value of the entire conditional expression. |
| chapter_titleBasic Shell Featuressection_titleGrouping Commandsnum_wordsnum_charstextBash provides two ways to group a list of commands to be executed as a unit. When commands are grouped, redirections may be applied to the entire command list. For example, the output of all the commands in the list may be redirected to a single stream. () ( list ) Placing a list of commands between parentheses forces the shell to create a subshell, and each of the commands in list is executed in that subshell environment. Since the list is executed in a subshell, variable assignments do not remain in effect after the subshell completes. {} { list; } Placing a list of commands between curly braces causes the list to be executed in the current shell environment. No subshell is created. The semicolon (or newline) following list is required. In addition to the creation of a subshell, there is a subtle difference between these two constructs due to historical reasons. The braces are reserved words, so they must be separated from the list by blanks or other shell metacharacters. The parentheses are operators, and are recognized as separate tokens by the shell even if they are not separated from the list by whitespace. The exit status of both of these constructs is the exit status of list. |
| chapter_titleBasic Shell Featuressection_titleCoprocessesnum_wordsnum_charstextA coprocess is a shell command preceded by the coproc reserved word. A coprocess is executed asynchronously in a subshell, as if the command had been terminated with the ‘&’ control operator, with a two-way pipe established between the executing shell and the coprocess. The syntax for a coprocess is: coproc [NAME] command [redirections] This creates a coprocess named NAME. command may be either a simple command or a compound command. NAME is a shell variable name. If NAME is not supplied, the default name is COPROC. The recommended form to use for a coprocess is coproc NAME { command; } This form is preferred because simple commands result in the coprocess always being named COPROC, and it is simpler to use and more complete than the other compound commands. There are other forms of coprocesses: coproc NAME compound-command coproc compound-command coproc simple-command\n\nIf command is a compound command, NAME is optional. The word following coproc determines whether that word is interpreted as a variable name: it is interpreted as NAME\nif it is not a reserved word that introduces a compound command. If command is a simple\ncommand, NAME is not allowed; this is to avoid confusion between NAME and the first word of the simple command. When the coprocess is executed, the shell creates an array variable named NAME in the context of the executing shell. The standard output of command is connected via a pipe to a file descriptor in the executing shell, and that file descriptor is assigned to NAME[0]. The standard input of command is connected via a pipe to a file descriptor in the executing shell, and that file descriptor is assigned to NAME[1]. This pipe is established before any redirections specified by the command . The file descriptors can be utilized as arguments to shell commands and redirections using standard word expansions. Other than those created to execute command and process substitutions, the file descriptors are not available in subshells. The process ID of the shell spawned to execute the coprocess is available as the value of the variable NAME_PID. The wait builtin may be used to wait for the coprocess to terminate. Since the coprocess is created as an asynchronous command, the coproc command always returns success. The return status of a coprocess is the exit status of command. |
| chapter_titleBasic Shell Featuressection_titleGNU Parallelnum_wordsnum_charstextThere are ways to run commands in parallel that are not built into Bash. GNU Parallel is a tool to do just that. GNU Parallel, as its name suggests, can be used to build and run commands in parallel. You may run the same command with different arguments, whether they are filenames, usernames, hostnames, or lines read from files. GNU Parallel provides shorthand references to many of the most common operations (input lines, various portions of the input line, different ways to specify the input source, and so on). Parallel can replace xargs or feed commands from its input sources to several different instances of Bash. For a complete description, refer to the GNU Parallel documentation, which is available at https://www.gnu.org/software/parallel/parallel_tutorial.html. |
| chapter_titleBasic Shell Featuressection_titleShell Functionsnum_wordsnum_charstextShell functions are a way to group commands for later execution using a single name for the group. They are executed just like a \ simple command. When the name of a shell function is used as a simple command name, the shell executes the list of commands associated with that function name. Shell functions are executed in the current shell context; there is no new process created to interpret them. Functions are declared using this syntax: fname () compound-command [ redirections ] or\nfunction fname [()] compound-command [ redirections ]\nThis defines a shell function named fname. The reserved word function is optional. If the function reserved word is supplied, the parentheses are optional. The body of the\n\nfunction is the compound command compound-command. That command is usually a list enclosed between { and }, but may\nbe any compound command listed above. If the function reserved word is used, but the parentheses are not supplied, the braces are recommended. When the shell is in posix mode, fname must be a valid shell name and may not be the same as one of the special builtins. When not in posix mode, a function name can be any unquoted shell word that does not contain ‘$’. Any redirections associated with the shell function are performed when the function is executed. Function definitions are deleted using the -f option to the unset builtin. The exit status of a function definition is zero unless a syntax error occurs or a readonly\nfunction with the same name already exists. When executed, the exit status of a function\nis the exit status of the last command executed in the body. Note that for historical reasons, in the most common usage the curly braces that surround the body of the function must be separated from the body by blanks or newlines. This is because the braces are reserved words and are only recognized as such when they are separated from the command list by whitespace or another shell metacharacter. When using the braces, the list must be terminated by a semicolon, a ‘&’, or a newline. compound-command is executed whenever fname is specified as the name of a simple command. Functions are executed in the context of the calling shell; there is no new process created to interpret them (contrast this with the execution of a shell script). When a function is executed, the arguments to the function become the positional parameters during its execution. The special parameter ‘#’ that expands to the number of positional parameters is updated to reflect the new set of positional parameters. Special parameter 0 is unchanged. The first element of the FUNCNAME variable is set to the name of the function while the function is executing. All other aspects of the shell execution environment are identical between a function and its caller with these exceptions: the DEBUG and RETURN traps are not inherited unless the\nfunction has been given the trace attribute using the declare builtin or the -o functrace\noption has been enabled with the set builtin, (in which case all functions inherit the DEBUG and RETURN traps), and the ERR trap is not inherited unless the -o errtrace shell option has been enabled. the trap builtin. The FUNCNEST variable, if set to a numeric value greater than 0, defines a maximum\nfunction nesting level. Function invocations that exceed the limit cause the entire command\nto abort. If the builtin command return is executed in a function, the function completes and execution resumes with the next command after the function call. Any command associated with the RETURN trap is executed before execution resumes. When a function completes, the values of the positional parameters and the special parameter ‘#’ are restored to the values they had prior to the function’s execution. If return is supplied a numeric argument, that is the function’s return status; otherwise the function’s return status is the exit status of the last command executed before the return.\n\nVariables local to the function are declared with the local builtin (local variables). Ordinarily, variables and their values are shared between a function and its caller. These variables are visible only to the function and the commands it invokes. This is particularly important when a shell function calls other functions. In the following description, the current scope is a currently- executing function. Previous scopes consist of that function’s caller and so on, back to the \ scope, where the shell is not executing any shell function. A local variable at the current local scope is a variable declared using the local or declare builtins in the function that is currently executing. Local variables \ variables with the same name declared at previous scopes. For instance, a local variable declared in a function hides variables with the same name declared at previous scopes, including global variables: references and assignments refer to the local variable, leaving the variables at previous scopes unmodified. When the function returns, the global variable is once again visible. The shell uses dynamic scoping to control a variable’s visibility within functions. With dynamic scoping, visible variables and their values are a result of the sequence of function calls that caused execution to reach the current function. The value of a variable that a\nfunction sees depends on its value within its caller, if any, whether that caller is the global\nscope or another shell function. This is also the value that a local variable declaration shadows, and the value that is restored when the function returns. For example, if a variable var is declared as local in function func1, and func1 calls another function func2, references to var made from within func2 resolve to the local variable var from func1, shadowing any global variable named var. The following script demonstrates this behavior. When executed, the script displays In func2, var = func1 local func1() { local var=’func1 local’ func2 } func2() { echo \ }\nvar=global\nfunc1 The unset builtin also acts using the same dynamic scope: if a variable is local to the current scope, unset unsets it; otherwise the unset will refer to the variable found in any calling scope as described above. If a variable at the current local scope is unset, it remains so (appearing as unset) until it is reset in that scope or until the function returns. Once the function returns, any instance of the variable at a previous scope becomes visible. If the unset acts on a variable at a previous scope, any instance of a variable with that name\n\nthat had been shadowed becomes visible (see below how the localvar_unset shell option changes this behavior). The -f option to the declare (typeset) builtin command lists function names and definitions. The -F option to declare or typeset lists the function names only (and optionally the source file and line number,\nif the extdebug shell option is enabled). Functions may be exported so that child shell\nprocesses (those created when executing a separate shell invocation) automatically have them defined with the -f option to the export builtin. The -f option to the unset builtin deletes a function definition. Functions may be recursive. The FUNCNEST variable may be used to limit the depth of the function call stack and restrict the number of function invocations. By default, Bash places no limit on the number of recursive calls. |
| chapter_titleBasic Shell Featuressection_titleShell Parametersnum_wordsnum_charstextA parameter is an entity that stores values. It can be a name, a number, or one of the special characters listed below. A variable is a parameter denoted by a name. A variable has a value and zero or more attributes. Attributes are assigned using the declare builtin command (see the description of the declare builtin in Section 4.2 [Bash Builtins], page 61). The export and readonly builtins assign specific attributes. A parameter is set if it has been assigned a value. The null string is a valid value. Once a variable is set, it may be unset only by using the unset builtin command. A variable is assigned to using a statement of the form\nname=[value]\nIf value is not given, the variable is assigned the null string. All values undergo tilde expansion, parameter and variable expansion, command substitution, arithmetic expansion, and quote removal. If the variable has its integer attribute set, then value is evaluated as an arithmetic expression even if the $((...)) expansion is not used. Word splitting and filename expansion are not performed. Assignment statements 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 or more instances of the command builtin and retain these assignment statement properties. For example, command export var=value In the context where an assignment statement is assigning a value to a shell variable or array index, the ‘+=’ operator appends to or adds to the variable’s previous value. This includes arguments to declaration commands such as declare that accept assignment statements. When ‘+=’ is applied to a variable for which the integer attribute has been set, the variable’s current value and value are each evaluated as arithmetic expressions, and the sum of the results is assigned as the variable’s value. The current value is usually an integer constant, but may be an expression. When ‘+=’ is applied to an array variable using compound assignment, the variable’s value is not unset (as it is when using ‘=’), and new values are appended to the\n\narray beginning at one greater than the array’s maximum index (for indexed arrays), or added as additional key-value pairs in an associative array. When applied to a string-valued variable, value is expanded and appended to the variable’s value. A variable can be assigned the nameref attribute using the -n option to the declare or local builtin commands to create a nameref, or a reference to another variable. This allows variables to be manipulated indirectly. Whenever the nameref variable is referenced, assigned to, unset, or has its attributes modified (other than using or changing the nameref attribute itself), the operation is actually performed on the variable specified by the nameref variable’s value. A nameref is commonly used within shell functions to refer to a variable whose name is passed as an argument to the function. For instance, if a variable name is passed to a shell function as its first argument, running declare -n ref=$1 inside the function creates a local nameref variable ref whose value is the variable name passed as the first argument. References and assignments to ref, and changes to its attributes, are treated as references, assignments, and attribute modifications to the variable whose name was passed as $1. If the control variable in a for loop has the nameref attribute, the list of words can be a list of shell variables, and a name reference is established for each word in the list, in turn, when the loop is executed. Array variables cannot be given the nameref attribute. However, nameref variables can reference array variables and subscripted array variables. Namerefs can be unset using the -n option to the unset builtin. Otherwise, if unset is executed with the name of a nameref variable as an argument, the variable referenced by the nameref variable is unset. When the shell starts, it reads its environment and creates a shell variable from each environment variable that has a valid name, as described below. |
| chapter_titleBasic Shell Featuressection_titlePositional Parametersnum_wordsnum_charstextA positional parameter is a parameter denoted by one or more digits, other than the single digit 0. Positional parameters are assigned from the shell’s arguments when it is invoked, and may be reassigned using the set builtin command. Positional parameter N may be referenced as ${N}, or as $N when N consists of a single digit. Positional parameters may not be assigned to with assignment statements. The set and shift builtins are used to set and unset them. The positional parameters are temporarily replaced when a shell function is executed. When a positional parameter consisting of more than a single digit is expanded, it must be enclosed in braces. Without braces, a digit following ‘$’ can only refer to one of the first nine positional parameters ($1\\-$9) or the special parameter $0 (see below). |
| chapter_titleBasic Shell Featuressection_titleSpecial Parametersnum_wordsnum_charstextThe shell treats several parameters specially. These parameters may only be referenced; assignment to them is not allowed. Special parameters are denoted by one of the following characters.\n\n*\n\n($*) Expands to the positional parameters, starting from one. When the expansion is not within double quotes, each positional parameter expands to a separate word. In contexts where word expansions are performed, those words are subject to further word splitting and filename expansion. When the expansion occurs within double quotes, it expands to a single word with the value of each parameter separated by the first character of the IFS variable. That is, \ is equivalent to \, where c is the first character of the value of the IFS variable. If IFS is unset, the parameters are separated by spaces. If IFS is null, the parameters are joined without intervening separators.\n\n@\n\n($@) Expands to the positional parameters, starting from one. In contexts where word splitting is performed, this expands each positional parameter to a separate word; if not within double quotes, these words are subject to word splitting. In contexts where word splitting is not performed, such as the value portion of an assignment statement, this expands to a single word with each positional parameter separated by a space. When the expansion occurs within double quotes, and word splitting is performed, each parameter expands to a separate word. That is, \ is equivalent to \ \.... If the doublequoted expansion occurs within a word, the expansion of the first parameter is joined with the expansion of the beginning part of the original word, and the expansion of the last parameter is joined with the expansion of the last part of the original word. When there are no positional parameters, \ and $@ expand to nothing (i.e., they are removed).\n\n#\n\n($#) Expands to the number of positional parameters in decimal.\n\n?\n\n($?) Expands to the exit status of the most recently executed command.\n\n-\n\n($-, a hyphen.) Expands to the current option flags as specified upon invocation, by the set builtin command, or those set by the shell itself (such as the -i option).\n\n$\n\n($$) Expands to the process id of the shell. In a subshell, it expands to the process id of the invoking shell, not the subshell.\n\n!\n\n($!) Expands to the process id of the job most recently placed into the background, whether executed as an asynchronous command or using the bg builtin .\n\n($0) Expands to the name of the shell or shell script. This is set at shell initialization. If Bash is invoked with a file of commands, $0 is set to the name of that file. If Bash is started with the -c option, then $0 is set to the first argument after the string to be executed, if one is present. Otherwise, it is set to the filename used to invoke Bash, as given by argument zero. |
| chapter_titleBasic Shell Featuressection_titleShell Expansionsnum_wordsnum_charstextExpansion is performed on the command line after it has been split into tokens. Bash performs these expansions:\n• brace expansion\n\n• tilde expansion\n• parameter and variable expansion\n• command substitution\n• arithmetic expansion\n• word splitting\n• filename expansion\n• quote removal\nThe order of expansions is: brace expansion; tilde expansion, parameter and variable expansion, arithmetic expansion, and command substitution (done in a left-to-right fashion); word splitting; filename expansion; and quote removal. On systems that can support it, there is an additional expansion available: process substitution. This is performed at the same time as tilde, parameter, variable, and arithmetic expansion and command substitution. Quote removal is always performed last. It removes quote characters present in the original word, not ones resulting from one of the other expansions, unless they have been quoted themselves. Only brace expansion, word splitting, and filename expansion can increase the number of words of the expansion; other expansions expand a single word to a single word. The only exceptions to this are the expansions of \ and $*, and \ and ${name[*]}. |
| chapter_titleBasic Shell Featuressection_titleBrace Expansionnum_wordsnum_charstextBrace expansion is a mechanism to generate arbitrary strings sharing a common prefix and suffix, either of which can be empty. This mechanism is similar to filename expansion , but the filenames generated need not exist. Patterns to be brace expanded are formed from an optional preamble, followed by either a series of comma-separated strings or a sequence expression between a pair of braces, followed by an optional postscript. The preamble is prefixed to each string contained within the braces, and the postscript is then appended to each resulting string, expanding left to right. Brace expansions may be nested. The results of each expanded string are not sorted; brace expansion preserves left to right order. For example, bash$ echo a{d,c,b}e ade ace abe A sequence expression takes the form x..y[..incr], where x and y are either integers or letters, and incr, an optional increment, is an integer. When integers are supplied, the expression expands to each number between x and y, inclusive. If either x or y begins with a zero, each generated term will contain the same number of digits, zero-padding where necessary. When letters are supplied, the expression expands to each character lexicographically between x and y, inclusive, using the C locale. Note that both x and y must be of the same type (integer or letter). When the increment is supplied, it is used as the difference between each term. The default increment is 1 or -1 as appropriate.\n\nBrace expansion is performed before any other expansions, and any characters special to other expansions are preserved in the result. It is strictly textual. Bash does not apply any syntactic interpretation to the context of the expansion or the text between the braces. A correctly-formed brace expansion must contain unquoted opening and closing braces, and at least one unquoted comma or a valid sequence expression. Any incorrectly formed brace expansion is left unchanged. A ‘{’ or ‘,’ may be quoted with a backslash to prevent its being considered part of a brace expression. To avoid conflicts with parameter expansion, the string ‘${’ is not considered eligible for brace expansion, and inhibits brace expansion until the closing ‘}’. This construct is typically used as shorthand when the common prefix of the strings to be generated is longer than in the above example: mkdir /usr/local/src/bash/{old,new,dist,bugs} or chown root /usr/{ucb/{ex,edit},lib/{ex?.?*,how_ex}} Brace expansion introduces a slight incompatibility with historical versions of sh. sh does not treat opening or closing braces specially when 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 in the output. Bash outputs that word as ‘file1 file2’ after brace expansion. Start Bash with the +B option or disable brace expansion with the +B option to the set command for strict sh compatibility. |
| chapter_titleBasic Shell Featuressection_titleTilde Expansionnum_wordsnum_charstextIf a word begins with an unquoted tilde character (‘~’), all of the characters up to the first unquoted slash (or all characters, if there is no unquoted slash) are considered a tilde-prefix. If none of the characters in the tilde-prefix are quoted, the characters in the tilde-prefix following the tilde are treated as a possible login name. If this login name is the null string, the tilde is replaced with the value of the HOME shell variable. If HOME is unset, the tilde expands to the home directory of the user executing the shell instead. Otherwise, the tilde-prefix is replaced with the home directory associated with the specified login name. If the tilde-prefix is ‘~+’, the value of the shell variable PWD replaces the tilde-prefix. If the tilde-prefix is ‘~-’, the shell substitutes the value of the shell variable OLDPWD, if it is set. If the characters following the tilde in the tilde-prefix consist of a number N, optionally prefixed by a ‘+’ or a ‘-’, the tilde-prefix is replaced with the corresponding element from the directory stack, as it would be displayed by the dirs builtin invoked with the characters following tilde in the tilde-prefix as an argument. If the tilde-prefix, sans the tilde, consists of a number without a leading ‘+’ or ‘-’, tilde expansion assumes ‘+’. The results of tilde expansion are treated as if they were quoted, so the replacement is not subject to word splitting and filename expansion. If the login name is invalid, or the tilde expansion fails, the tilde-prefix is left unchanged. Bash checks each variable assignment for unquoted tilde-prefixes immediately following a ‘:’ or the first ‘=’, and performs tilde expansion in these cases. Consequently, one may use\n\nfilenames with tildes in assignments to PATH, MAILPATH, and CDPATH, and the shell assigns the expanded value. The following table shows how Bash treats unquoted tilde-prefixes: ~\n\nThe value of $HOME.\n\n~/foo\n\n$HOME/foo\n\n~fred/foo The directory or file foo in the home directory of the user fred. ~+/foo\n\n$PWD/foo\n\n~-/foo\n\n${OLDPWD-’~-’}/foo\n\n~N\n\nThe string that would be displayed by ‘dirs +N’.\n\n~+N\n\nThe string that would be displayed by ‘dirs +N’.\n\n~-N\n\nThe string that would be displayed by ‘dirs -N’.\n\nBash also performs tilde expansion on words satisfying the conditions of variable assignments when they appear as arguments to simple commands. Bash does not do this, except for the declaration commands listed above, when in posix mode. |
| chapter_titleBasic Shell Featuressection_titleShell Parameter Expansionnum_wordsnum_charstextThe ‘$’ character introduces parameter expansion, command substitution, or arithmetic expansion. The parameter name or symbol to be expanded may be enclosed in braces, which are optional but serve to protect the variable to be expanded from characters immediately following it which could be interpreted as part of the name. For example, if the first positional parameter has the value ‘a’, then ${11} expands to the value of the eleventh positional parameter, while $11 expands to ‘a1’. When braces are used, the matching ending brace is the first ‘}’ not escaped by a backslash or within a quoted string, and not within an embedded arithmetic expansion, command substitution, or parameter expansion. The basic form of parameter expansion is ${parameter }, which substitutes the value of parameter. The parameter is a shell parameter as described above or an array reference. The braces are required when parameter is a positional parameter with more than one digit, or when parameter is followed by a character that is not to be interpreted as part of its name. If the first character of parameter is an exclamation point (!), and parameter is not a nameref, it introduces a level of indirection. Bash uses the value formed by expanding the rest of parameter as the new parameter; this new parameter is then expanded and that value is used in the rest of the expansion, rather than the expansion of the original parameter. This is known as indirect expansion. The value is subject to tilde expansion, parameter expansion, command substitution, and arithmetic expansion. If parameter is a nameref, this expands to the name of the variable referenced by parameter instead of performing the complete indirect expansion, for compatibility. The exceptions to this are the expansions of ${!prefix*} and ${!name[@]} described below. The exclamation point must immediately follow the left brace in order to introduce indirection.\n\nIn each of the cases below, word is subject to tilde expansion, parameter expansion, command substitution, and arithmetic expansion. When not performing substring expansion, using the forms described below (e.g., ‘:-’), Bash tests for a parameter that is unset or null. Omitting the colon results in a test only\nfor a parameter that is unset. Put another way, if the colon is included, the operator tests\nfor both parameter’s existence and that its value is not null; if the colon is omitted, the\noperator tests only for existence. ${parameter:−word} If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.\n$ v=123\n$ echo ${v-unset}\n123\n$ echo ${v:-unset-or-null}\n123\n$ unset v\n$ echo ${v-unset}\nunset\n$ v=\n$ echo ${v-unset}\n$ echo ${v:-unset-or-null}\nunset-or-null ${parameter:=word} If parameter is unset or null, the expansion of word is assigned to parameter, and the result of the expansion is the final value of parameter. Positional parameters and special parameters may not be assigned in this way.\n$ unset var\n$: ${var=DEFAULT}\n$ echo $var\nDEFAULT\n$ var=\n$: ${var=DEFAULT}\n$ echo $var\n$ var=\n$: ${var:=DEFAULT}\n$ echo $var\nDEFAULT\n$ unset var\n$: ${var:=DEFAULT}\n$ echo $var\nDEFAULT\n\n${parameter:?word} If parameter is null or unset, the shell writes the expansion of word (or a message to that effect if word is not present) to the standard error and, if it is not interactive, exits with a non-zero status. An interactive shell does not exit, but does not execute the command associated with the expansion. Otherwise, the value of parameter is substituted.\n$ var=\n$: ${var:?var is unset or null} bash: var: var is unset or null\n$ echo ${var?var is unset}\n$ unset var\n$: ${var?var is unset} bash: var: var is unset $: ${var:?var is unset or null} bash: var: var is unset or null\n$ var=123\n$ echo ${var:?var is unset or null}\n123 ${parameter:+word} If parameter is null or unset, nothing is substituted, otherwise the expansion of word is substituted. The value of parameter is not used.\n$ var=123\n$ echo ${var:+var is set and not null}\nvar is set and not null\n$ echo ${var+var is set}\nvar is set\n$ var=\n$ echo ${var:+var is set and not null}\n$ echo ${var+var is set}\nvar is set\n$ unset var\n$ echo ${var+var is set}\n$ echo ${var:+var is set and not null}\n$ ${parameter:offset}\n${parameter:offset:length} This is referred to as Substring Expansion. It expands to up to length characters of the value of parameter starting at the character specified by offset. If parameter is ‘@’ or ‘*’, an indexed array subscripted by ‘@’ or ‘*’, or an associative array name, the results differ as described below. If:length is omitted (the first form above), this expands to the substring of the value of parameter starting at the character specified by offset and extending to the end of the value.\n\nIf offset is omitted, it is treated as 0. If length is omitted, but the colon after offset is present, it is treated as 0. length and offset are arithmetic expressions . If offset evaluates to a number less than zero, the value is used as an offset in characters from the end of the value of parameter. If length evaluates to a number less than zero, it is interpreted as an offset in characters from the end of the value of parameter rather than a number of characters, and the expansion is the characters between offset and that result. Note that a negative offset must be separated from the colon by at least one space to avoid being confused with the ‘:-’ expansion. Here are some examples illustrating substring expansion on parameters and subscripted arrays:\n$ string=01234567890abcdefgh\n$ echo ${string:7}\n7890abcdefgh\n$ echo ${string:7:0}\n$ echo ${string:7:2}\n78\n$ echo ${string:7:-2}\n7890abcdef\n$ echo ${string: -7}\nbcdefgh\n$ echo ${string: -7:0}\n$ echo ${string: -7:2}\nbc\n$ echo ${string: -7:-2}\nbcdef\n$ set -- 01234567890abcdefgh\n$ echo ${1:7}\n7890abcdefgh\n$ echo ${1:7:0}\n$ echo ${1:7:2}\n78\n$ echo ${1:7:-2}\n7890abcdef\n$ echo ${1: -7}\nbcdefgh\n$ echo ${1: -7:0}\n$ echo ${1: -7:2}\nbc\n$ echo ${1: -7:-2}\nbcdef\n\n$ array[0]=01234567890abcdefgh\n$ echo ${array[0]:7}\n7890abcdefgh\n$ echo ${array[0]:7:0}\n$ echo ${array[0]:7:2}\n78\n$ echo ${array[0]:7:-2}\n7890abcdef\n$ echo ${array[0]: -7}\nbcdefgh\n$ echo ${array[0]: -7:0}\n$ echo ${array[0]: -7:2}\nbc\n$ echo ${array[0]: -7:-2}\nbcdef If parameter is ‘@’ or ‘*’, the result is length positional parameters beginning at offset. A negative offset is taken relative to one greater than the greatest positional parameter, so an offset of -1 evaluates to the last positional parameter (or 0 if there are no positional parameters). It is an expansion error if length evaluates to a number less than zero. The following examples illustrate substring expansion using positional parameters:\n$ set -- 1 2 3 4 5 6 7 8 9 0 a b c d e f g h\n$ echo ${@:7},\n$ echo ${@:7:0}\n$ echo ${@:7:2}\n$ echo ${@:7:-2}\nbash: -2: substring expression < 0\n$ echo ${@: -7:2}\nb c\n$ echo ${@:0}\n./bash 1 2 3 4 5 6 7 8 9 0 a b c d e f g h\n$ echo ${@:0:2}\n./bash 1\n$ echo ${@: -7:0}\nIf parameter is an indexed array name subscripted by ‘@’ or ‘*’, the result is the length members of the array beginning with ${parameter[offset]}. A negative offset is taken relative to one greater than the maximum index of the specified array. It is an expansion error if length evaluates to a number less than zero.\n\nThese examples show how you can use substring expansion with indexed arrays:\n$ array=(0 1 2 3 4 5 6 7 8 9 0 a b c d e f g h)\n$ echo ${array[@]:7}\n$ echo ${array[@]:7:2}\n$ echo ${array[@]: -7:2}\nb c\n$ echo ${array[@]: -7:-2}\nbash: -2: substring expression < 0\n$ echo ${array[@]:0}\n0 1 2 3 4 5 6 7 8 9 0 a b c d e f g h\n$ echo ${array[@]:0:2}\n0 1\n$ echo ${array[@]: -7:0}\nSubstring expansion applied to an associative array produces undefined results. Substring indexing is zero-based unless the positional parameters are used, in which case the indexing starts at 1 by default. If offset is 0, and the positional parameters are used, $0 is prefixed to the list. ${!prefix*} ${!prefix@} Expands to the names of variables whose names begin with prefix, separated by the first character of the IFS special variable. When ‘@’ is used and the expansion appears within double quotes, each variable name expands to a separate word. ${!name[@]} ${!name[*]} If name is an array variable, expands to the list of array indices (keys) assigned in name. If name is not 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} Substitutes the length in characters of the value of parameter. If parameter is ‘*’ or ‘@’, the value substituted is the number of positional parameters. If parameter is an array name subscripted by ‘*’ or ‘@’, the value substituted is the number of elements in the array. If parameter is an indexed array name subscripted by a negative number, that number is interpreted as relative to one greater than the maximum index of parameter, so negative indices count back from the end of the array, and an index of -1 references the last element. ${parameter#word} ${parameter##word} The word is expanded to produce a pattern and matched against the expanded value of parameter according to the rules described below. If the pattern matches the beginning of the\n\nexpanded value of parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern (the ‘#’ case) or the longest matching pattern (the ‘##’ case) deleted. If parameter is ‘@’ or ‘*’, the pattern removal operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with ‘@’ or ‘*’, the pattern removal operation is applied to each member of the array in turn, and the expansion is the resultant list. ${parameter%word} ${parameter%%word} The word is expanded to produce a pattern and matched against the expanded value of parameter according to the rules described below. If the pattern matches a trailing portion of the expanded value of parameter, then the result of the expansion is the value of parameter with the shortest matching pattern (the ‘%’ case) or the longest matching pattern (the ‘%%’ case) deleted. If parameter is ‘@’ or ‘*’, the pattern removal operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with ‘@’ or ‘*’, the pattern removal operation is applied to each member of the array in turn, and the expansion is the resultant list. ${parameter/pattern/string} ${parameter//pattern/string} ${parameter/#pattern/string} ${parameter/%pattern/string} The pattern is expanded to produce a pattern and matched against the expanded value of parameter as described below. The longest match of pattern in the expanded value is replaced with string. string undergoes tilde expansion, parameter and variable expansion, arithmetic expansion, command and process substitution, and quote removal. In the first form above, only the first match is replaced. If there are two slashes separating parameter and pattern (the second form above), all matches of pattern are replaced with string. If pattern is preceded by ‘#’ (the third form above), it must match at the beginning of the expanded value of parameter. If pattern is preceded by ‘%’ (the fourth form above), it must match at the end of the expanded value of parameter. If the expansion of string is null, matches of pattern are deleted and the ‘/’ following pattern may be omitted. If the patsub_replacement shell option is enabled using shopt, any unquoted instances of ‘&’ in string are replaced with the matching portion of pattern. This is intended to duplicate a common sed idiom. Quoting any part of string inhibits replacement in the expansion of the quoted portion, including replacement strings stored in shell variables. Backslash escapes ‘&’ in string; the backslash is removed in order to permit a literal ‘&’ in the replacement string. Users should take care if string is double-quoted to\n\navoid unwanted interactions between the backslash and double-quoting, since backslash has special meaning within double quotes. Pattern substitution performs the check for unquoted ‘&’ after expanding string, so users should ensure to properly quote any occurrences of ‘&’ they want to be taken literally in the replacement and ensure any instances of ‘&’ they want to be replaced are unquoted. For instance,\nvar=abcdef\nrep=’& ’\necho ${var/abc/& } echo \ echo ${var/abc/$rep} echo \ will display four lines of \, while\nvar=abcdef\nrep=’& ’\necho ${var/abc/\\& } echo \ echo ${var/abc/\} echo ${var/abc/\} will display four lines of \. Like the pattern removal operators, double quotes surrounding the replacement string quote the expanded characters, while double quotes enclosing the entire parameter substitution do not, since the expansion is performed in a context that doesn’t take any enclosing double quotes into account. Since backslash can escape ‘&’, it can also escape a backslash in the replacement string. This means that ‘\\\\’ will insert a literal backslash into the replacement, so these two echo commands\nvar=abcdef\nrep=’\\\\&xyz’\necho ${var/abc/\\\\&xyz} echo ${var/abc/$rep} will both output ‘\\abcxyzdef’. It should rarely be necessary to enclose only string in double quotes. If the nocasematch shell option (see the description of shopt in Section 4.3.2 [The Shopt Builtin], page 78) is enabled, the match is performed without regard to the case of alphabetic characters. If parameter is ‘@’ or ‘*’, the substitution operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with ‘@’ or ‘*’, the substitution operation is applied to each member of the array in turn, and the expansion is the resultant list.\n\n${parameter^pattern} ${parameter^^pattern} ${parameter,pattern} ${parameter,,pattern} This expansion modifies the case of alphabetic characters in parameter. First, the pattern is expanded to produce a pattern as described below in Section 3.5.8.1 [Pattern Matching], page 39. Bash then examines characters in the expanded value of parameter against pattern as described below. If a character matches the pattern, its case is converted. The pattern should not attempt to match more than one character. Using ‘^’ converts lowercase letters matching pattern to uppercase; ‘,’ converts matching uppercase letters to lowercase. The ‘^’ and ‘,’ variants examine the first character in the expanded value and convert its case if it matches pattern; the ‘^^’ and ‘,,’ variants examine all characters in the expanded value and convert each one that matches pattern. If pattern is omitted, it is treated like a ‘?’, which matches every character. If parameter is ‘@’ or ‘*’, the case modification operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with ‘@’ or ‘*’, the case modification operation is applied to each member of the array in turn, and the expansion is the resultant list. ${parameter@operator} The expansion is either a transformation of the value of parameter or information about parameter itself, depending on the value of operator. Each operator is a single letter: U\n\nThe expansion is a string that is the value of parameter with lowercase alphabetic characters converted to uppercase.\n\nu\n\nThe expansion is a string that is the value of parameter with the first character converted to uppercase, if it is alphabetic.\n\nL\n\nThe expansion is a string that is the value of parameter with uppercase alphabetic characters converted to lowercase.\n\nQ\n\nThe expansion is a string that is the value of parameter quoted in a format that can be reused as input.\n\nE\n\nThe expansion is a string that is the value of parameter with backslash escape sequences expanded as with the $’...’ quoting mechanism.\n\nP\n\nThe expansion is a string that is the result of expanding the value of parameter as if it were a prompt string.\n\nA\n\nThe expansion is a string in the form of an assignment statement or declare command that, if evaluated, recreates parameter with its attributes and value.\n\nK\n\nProduces a possibly-quoted version of the value of parameter, except that it prints the values of indexed and associative arrays as a sequence of quoted key-value pairs. The keys and values are quoted in a format that can be reused as input.\n\na\n\nThe expansion is a string consisting of flag values representing parameter’s attributes.\n\nk\n\nLike the ‘K’ transformation, but expands the keys and values of indexed and associative arrays to separate words after word splitting.\n\nIf parameter is ‘@’ or ‘*’, the operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with ‘@’ or ‘*’, the operation is applied to each member of the array in turn, and the expansion is the resultant list. The result of the expansion is subject to word splitting and filename expansion as described below. |
| chapter_titleBasic Shell Featuressection_titleCommand Substitutionnum_wordsnum_charstextCommand substitution allows the output of a command to replace the command itself. The standard form of command substitution occurs when a command is enclosed as follows: $(command) or (deprecated) ‘command‘. Bash performs command substitution by executing command in a subshell environment and replacing the command substitution with the standard output of the command, with any trailing newlines deleted. Embedded newlines are not deleted, but they may be removed during word splitting. The command substitution $(cat file) can be replaced by the equivalent but faster $(< file). With the old-style backquote form of substitution, backslash retains its literal meaning except when followed by ‘$’, ‘‘’, or ‘\\’. The first backquote not preceded by a backslash terminates the command substitution. When using the $(command) form, all characters between the parentheses make up the command; none are treated specially. There is an alternate form of command substitution: ${c command; } which executes command in the current execution environment and captures its output, again with trailing newlines removed. The character c following the open brace must be a space, tab, newline, or ‘|’, and the close brace must be in a position where a reserved word may appear (i.e., preceded by a command terminator such as semicolon). Bash allows the close brace to be joined to the remaining characters in the word without being followed by a shell metacharacter as a reserved word would usually require. Any side effects of command take effect immediately in the current execution environment and persist in the current environment after the command completes (e.g., the exit builtin exits the shell).\n\nThis type of command substitution superficially resembles executing an unnamed shell\nfunction: local variables are created as when a shell function is executing, and the return\nbuiltin forces command to complete; however, the rest of the execution environment, including the positional parameters, is shared with the caller. If the first character following the open brace is a ‘|’, the construct expands to the value of the REPLY shell variable after command executes, without removing any trailing newlines, and the standard output of command remains the same as in the calling shell. Bash creates REPLY as an initially-unset local variable when command executes, and restores REPLY to the value it had before the command substitution after command completes, as with any local variable. For example, this construct expands to ‘12345’, and leaves the shell variable X unchanged in the current execution environment: ${ local X=12345; echo $X; } (not declaring X as local would modify its value in the current environment, as with normal shell function execution), while this construct does not require any output to expand to ‘12345’: ${| REPLY=12345; } and restores REPLY to the value it had before the command substitution. Command substitutions may be nested. To nest when using the backquoted form, escape the inner backquotes with backslashes. If the substitution appears within double quotes, Bash does not perform word splitting and filename expansion on the results. |
| chapter_titleBasic Shell Featuressection_titleArithmetic Expansionnum_wordsnum_charstextArithmetic expansion evaluates an arithmetic expression and substitutes the result. The format for arithmetic expansion is: $(( expression )) The expression undergoes the same expansions as if it were within double quotes, but unescaped double quote characters in expression are not treated specially and are removed. All tokens in the expression undergo parameter and variable expansion, command substitution, and quote removal. The result is treated as the arithmetic expression to be evaluated. Since the way Bash handles double quotes can potentially result in empty strings, arithmetic expansion treats those as expressions that evaluate to 0. Arithmetic expansions may be nested. The evaluation is performed according to the rules listed below. If the expression is invalid, Bash prints a message indicating failure to the standard error, does not perform the substitution, and does not execute the command associated with the expansion. |
| chapter_titleBasic Shell Featuressection_titleProcess Substitutionnum_wordsnum_charstextProcess substitution allows a process’s input or output to be referred to using a filename. It takes the form of <(list)\n\nor >(list) The process list is run asynchronously, and its input or output appears as a filename. This filename is passed as an argument to the current command as the result of the expansion. If the >(list) form is used, writing to the file provides input for list. If the <(list) form is used, reading the file obtains the output of list. Note that no space may appear between the < or > and the left parenthesis, otherwise the construct would be interpreted as a redirection. Process substitution is supported on systems that support named pipes (fifos) or the /dev/fd method of naming open files. When available, process substitution is performed simultaneously with parameter and variable expansion, command substitution, and arithmetic expansion. |
| chapter_titleBasic Shell Featuressection_titleWord Splittingnum_wordsnum_charstextThe shell scans the results of parameter expansion, command substitution, and arithmetic expansion that did not occur within double quotes for word splitting. Words that were not expanded are not split. The shell treats each character of $IFS as a delimiter, and splits the results of the other expansions into fields using these characters as field terminators. An IFS whitespace character is whitespace as defined above that appears in the value of IFS. Space, tab, and newline are always considered IFS whitespace, even if they don’t appear in the locale’s space category. If IFS is unset, word splitting behaves as if its value were <space><tab><newline>, and treats these characters as IFS whitespace. If the value of IFS is null, no word splitting occurs, but implicit null arguments (see below) are still removed. Word splitting begins by removing sequences of IFS whitespace characters from the beginning and end of the results of the previous expansions, then splits the remaining words. If the value of IFS consists solely of IFS whitespace, any sequence of IFS whitespace characters delimits a field, so a field consists of characters that are not unquoted IFS whitespace, and null fields result only from quoting. If IFS contains a non-whitespace character, then any character in the value of IFS that is not IFS whitespace, along with any adjacent IFS whitespace characters, delimits a field. This means that adjacent non-IFS-whitespace delimiters produce a null field. A sequence of IFS whitespace characters also delimits a field. Explicit null arguments (\ or ’’) are retained and passed to commands as empty strings. Unquoted implicit null arguments, resulting from the expansion of parameters that have no values, are removed. Expanding a parameter with no value within double quotes produces a null field, which is retained and passed to a command as an empty string. When a quoted null argument appears as part of a word whose expansion is non-null, word splitting removes the null argument portion, leaving the non-null expansion. That is, the word -d’’ becomes -d after word splitting and null argument removal. |
| chapter_titleBasic Shell Featuressection_titleFilename Expansionnum_wordsnum_charstextAfter word splitting, unless the -f option has been set, Bash scans each word for the characters ‘*’, ‘?’, and ‘[’. If one of these characters appears, and is not quoted, then the word is regarded as a pattern, and replaced with a sorted list of filenames matching the pattern, subject to the value of the GLOBSORT shell variable. If no matching filenames are found, and the shell option nullglob is disabled, the word is left unchanged. If the nullglob option is set, and no matches are found, the word is removed. If the failglob shell option is set, and no matches are found, Bash prints an error message and does not execute the command. If the shell option nocaseglob is enabled, the match is performed without regard to the case of alphabetic characters. When a pattern is used for filename expansion, the character ‘.’ at the start of a filename or immediately following a slash must be matched explicitly, unless the shell option dotglob is set. In order to match the filenames. and.., the pattern must begin with ‘.’ (for example, ‘.?’), even if dotglob is set. If the globskipdots shell option is enabled, the filenames. and.. never match, even if the pattern begins with a ‘.’. When not matching filenames, the ‘.’ character is not treated specially. When matching a filename, the slash character must always be matched explicitly by a slash in the pattern, but in other matching contexts it can be matched by a special pattern character as described below. See the description of shopt in Section 4.3.2 [The Shopt Builtin], page 78, for a description of the nocaseglob, nullglob, globskipdots, failglob, and dotglob options. The GLOBIGNORE shell variable may be used to restrict the set of file names matching a pattern. If GLOBIGNORE is set, each matching file name that also matches one of the patterns in GLOBIGNORE is removed from the list of matches. If the nocaseglob option is set, the matching against the patterns in GLOBIGNORE is performed without regard to case. The filenames. and.. are always ignored when GLOBIGNORE is set and not null. However, setting GLOBIGNORE to a non-null value has the effect of enabling the dotglob shell option, so all other filenames beginning with a ‘.’ match. To get the old behavior of ignoring filenames beginning with a ‘.’, make ‘.*’ one of the patterns in GLOBIGNORE. The dotglob option is disabled when GLOBIGNORE is unset. The GLOBIGNORE pattern matching honors the setting of the extglob shell option. The value of the GLOBSORT shell variable controls how the results of pathname expansion are sorted, as described below. |
| chapter_titleBasic Shell Featuressection_titlePattern Matchingnum_wordsnum_charstextAny character that appears in a pattern, other than the special pattern characters described below, matches itself. The nul character may not occur in a pattern. A backslash escapes the following character; the escaping backslash is discarded when matching. The special pattern characters must be quoted if they are to be matched literally. The special pattern characters have the following meanings: *\n\nMatches any string, including the null string. When the globstar shell option is enabled, and ‘*’ is used in a filename expansion context, two adjacent ‘*’s used\n\nas a single pattern match all files and zero or more directories and subdirectories. If followed by a ‘/’, two adjacent ‘*’s match only directories and subdirectories. ?\n\nMatches any single character.\n\n[...]\n\nMatches any one of the characters enclosed between the brackets. This is known as a bracket expression and matches a single character. A pair of characters separated by a hyphen denotes a range expression; any character that falls between those two characters, inclusive, using the current locale’s collating sequence and character set, matches. If the first character following the ‘[’ is a ‘!’ or a ‘^’ then any character not within the range matches. To match a ‘−’, include it as the first or last character in the set. To match a ‘]’, include it as the first character in the set. The sorting order of characters in range expressions, and the characters included in the range, are determined by the current locale and the values of the LC_ COLLATE and LC_ALL shell variables, if set. For example, in the default C locale, ‘[a-dx-z]’ is equivalent to ‘[abcdxyz]’. Many locales sort characters in dictionary order, and in these locales ‘[a-dx-z]’ is typically not equivalent to ‘[abcdxyz]’; it might be equivalent to ‘[aBbCcDdxYyZz]’, for example. To obtain the traditional interpretation of ranges in bracket expressions, you can force the use of the C locale by setting the LC_COLLATE or LC_ALL environment variable to the value ‘C’, or enable the globasciiranges shell option. Within a bracket expression, character classes can be specified using the syntax [:class:], where class is one of the following classes defined in the posix standard: alnum alpha ascii blank cntrl digit graph lower print punct space upper word xdigit A character class matches any character belonging to that class. The word character class matches letters, digits, and the character ‘_’. For instance, the following pattern will match any character belonging to the space character class in the current locale, then any upper case letter or ‘!’, a dot, and finally any lower case letter or a hyphen. [[:space:]][[:upper:]!].[-[:lower:]] Within a bracket expression, an equivalence class can be specified using the syntax [=c=], which matches all characters with the same collation weight (as defined by the current locale) as the character c. Within a bracket expression, the syntax [.symbol.] matches the collating symbol symbol.\n\nIf the extglob shell option is enabled using the shopt builtin, the shell recognizes several extended pattern matching operators. In the following description, a pattern-list is a list of one or more patterns separated by a ‘|’. When matching filenames, the dotglob shell option determines the set of filenames that are tested, as described above. Composite patterns may be formed using one or more of the following sub-patterns: ?(pattern-list) Matches zero or one occurrence of the given patterns.\n\n*(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. The extglob option changes the behavior of the parser, since the parentheses are normally treated as operators with syntactic meaning. To ensure that extended matching patterns are parsed correctly, make sure that extglob is enabled before parsing constructs containing the patterns, including shell functions and command substitutions. When matching filenames, the dotglob shell option determines the set of filenames that are tested: when dotglob is enabled, the set of filenames includes all files beginning with ‘.’, but the filenames. and.. must be matched by a pattern or sub-pattern that begins with a dot; when it is disabled, the set does not include any filenames beginning with ‘.’ unless the pattern or sub-pattern begins with a ‘.’. If the globskipdots shell option is enabled, the filenames. and.. never appear in the set. As above, ‘.’ only has a special meaning when matching filenames. Complicated extended pattern matching against long strings is slow, especially when the patterns contain alternations and the strings contain multiple matches. Using separate matches against shorter strings, or using arrays of strings instead of a single long string, may be faster. |
| chapter_titleBasic Shell Featuressection_titleQuote Removalnum_wordsnum_charstextAfter the preceding expansions, all unquoted occurrences of the characters ‘\\’, ‘’’, and ‘\} |
| {: , : , : 529, : 3334, : } |
| {: , : , : 39, : 231, : } |
| {: , : , : 131, : 743, : } |
| {: , : , : 51, : 293, : } |
| {: , : , : 86, : 530, : } |
| {: , : , : 51, : 327, : } |
| {: , : , : 246, : 1557, : } |
| {: , : , : 61, : 392, : } |
| {: , : , : 158, : 884, : } |
| {: , : , : 57, : 364, : } |
| {: , : , : 42, : 226, : } |
| {: , : , : 282, : 1805, : } |
| {: , : , : 348, : 1982, : } |
| {: , : , : 466, : 2808, : } |
| {: , : , : 256, : 1587, : } |
| {: , : , : 311, : 1808, : } |
| {: , : , : 602, : 3514, : } |
| {: , : , : 730, : 4357, : } |
| {: , : , : 3821, : 21987, : } |
| {: , : , : 4958, : 29771, : \\C-x\\C-r\.\nice\} |
| {: , : , : 1408, : 8401, : } |
| {: , : , : 1964, : 12324, : string\The mail in mailfile has been read\} |
| {: , : , : 113, : 729, : } |
| {: , : , : 19, : 126, : } |
| {: , : , : 340, : 2026, : /usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin\} |
| {: , : , : 5328, : 32590, : main\} |
| {: , : , : 7, : 47, : } |
| {: , : , : 852, : 5197, : } |
| {: , : , : 737, : 4392, : $BASH_ENV\$BASH_ENV\} |
| {: , : , : 69, : 432, : } |
| {: , : , : 87, : 515, : $-\$PS1\} |
| {: , : , : 446, : 2620, : } |
| {: , : , : 781, : 4396, : sticky\} |
| {: , : , : 463, : 2849, : } |
| {: , : , : 486, : 2791, : ls -F\} |
| {: , : , : 1141, : 7034, : } |
| {: , : , : 80, : 500, : top\} |
| {: , : , : 607, : 3498, : } |
| {: , : , : 370, : 2263, : Weekday Month Date\Tue May 26\ttys0\} |
| {: , : , : 375, : 2305, : } |
| {: , : , : 58, : 352, : } |
| {: , : , : 242, : 1572, : } |
| {: , : , : 2385, : 14321, : ’) is treated specially when it appears in a backquoted\ncommand substitution in the body of a here-document that undergoes expansion. That means, for example, that a backslash preceding a double quote character will escape it and the backslash will be removed.\n16. Command substitutions don’t set the ‘?’ special parameter. The exit status of a simple\ncommand without a command word is still the exit status of the last command substitution that occurred while evaluating the variable assignments and redirections in that command, but that does not happen until after all of the assignments and redirections.\n\n17. Literal tildes that appear as the first character in elements of the PATH variable are not\nexpanded as described above under Section 3.5.2 [Tilde Expansion], page 26.\n18. Command lookup finds posix special builtins before shell functions, including output\nprinted by the type and command builtins.\n19. Even if a shell function whose name contains a slash was defined before entering posix\nmode, the shell will not execute a function whose name contains one or more slashes.\n20. When a command in the hash table no longer exists, Bash will re-search $PATH to find\nthe new location. This is also available with ‘shopt -s checkhash’.\n21. Bash will not insert a command without the execute bit set into the command hash\ntable, even if it returns it as a (last-ditch) result from a $PATH search.\n22. The message printed by the job control code and builtins when a job exits with a\nnon-zero status is ‘Done(status)’.\n23. The message printed by the job control code and builtins when a job is stopped is\n‘Stopped(signame)’, where signame is, for example, SIGTSTP.\n24. If the shell is interactive, Bash does not perform job notifications between executing\ncommands in lists separated by ‘;’ or newline. Non-interactive shells print status messages after a foreground job in a list completes.\n25. If the shell is interactive, Bash waits until the next prompt before printing the status\nof a background job that changes status or a foreground job that terminates due to a signal. Non-interactive shells print status messages after a foreground job completes.\n26. Bash permanently removes jobs from the jobs table after notifying the user of their\ntermination via the wait or jobs builtins. It removes the job from the jobs list after notifying the user of its termination, but the status is still available via wait, as long as wait is supplied a pid argument.\n27. The vi editing mode will invoke the vi editor directly when the ‘v’ command is run,\ninstead of checking $VISUAL and $EDITOR.\n28. Prompt expansion enables the posix PS1 and PS2 expansions of ‘!’ to the history\nnumber and ‘!!’ to ‘!’, and Bash performs parameter expansion on the values of PS1 and PS2 regardless of the setting of the promptvars option.\n29. The default history file is ~/.sh_history (this is the default value the shell assigns to\n$HISTFILE).\n30. The ‘!’ character does not introduce history expansion within a double-quoted string,\neven if the histexpand option is enabled.\n31. When printing shell function definitions (e.g., by type), Bash does not print the\nfunction reserved word unless necessary.\n32. Non-interactive shells exit if a syntax error in an arithmetic expansion results in an\ninvalid expression.\n33. Non-interactive shells exit if a parameter expansion error occurs.\n34. If a posix special builtin returns an error status, a non-interactive shell exits. The fatal\nerrors are those listed in the posix standard, and include things like passing incorrect options, redirection errors, variable assignment errors for assignments preceding the command name, and so on.\n\n35. A non-interactive shell exits with an error status if a variable assignment error occurs\nwhen no command name follows the assignment statements. A variable assignment error occurs, for example, when trying to assign a value to a readonly variable.\n36. A non-interactive shell exits with an error status if a variable assignment error occurs\nin an assignment statement preceding a special builtin, but not with any other simple command. For any other simple command, the shell aborts execution of that command, and execution continues at the top level (\).\n37. A non-interactive shell exits with an error status if the iteration variable in a for\nstatement or the selection variable in a select statement is a readonly variable or has an invalid name.\n38. Non-interactive shells exit if filename in. filename is not found.\n39. Non-interactive shells exit if there is a syntax error in a script read with the. or source\nbuiltins, or in a string processed by the eval builtin.\n40. Non-interactive shells exit if the export, readonly or unset builtin commands get an\nargument that is not a valid identifier, and they are not operating on shell functions. These errors force an exit because these are special builtins.\n41. Assignment statements preceding posix special builtins persist in the shell environment\nafter the builtin completes.\n42. The command builtin does not prevent builtins that take assignment statements as arguments from expanding them as assignment statements; when not in posix mode,\ndeclaration commands lose their assignment statement expansion properties when preceded by command.\n43. Enabling posix mode has the effect of setting the inherit_errexit option, so subshells\nspawned to execute command substitutions inherit the value of the -e option from the parent shell. When the inherit_errexit option is not enabled, Bash clears the -e option in such subshells.\n44. Enabling posix mode has the effect of setting the shift_verbose option, so numeric\narguments to shift that exceed the number of positional parameters will result in an error message.\n45. Enabling posix mode has the effect of setting the interactive_comments option.\n46. The. and source builtins do not search the current directory for the filename argument\nif it is not found by searching PATH.\n47. When the alias builtin displays alias definitions, it does not display them with a\nleading ‘alias ’ unless the -p option is supplied.\n48. The bg builtin uses the required format to describe each job placed in the background,\nwhich does not include an indication of whether the job is the current or previous job.\n49. When the cd builtin is invoked in logical mode, and the pathname constructed from\n$PWD and the directory name supplied as an argument does not refer to an existing directory, cd will fail instead of falling back to physical mode.\n50. When the cd builtin cannot change a directory because the length of the pathname\nconstructed from $PWD and the directory name supplied as an argument exceeds PATH_ MAX when canonicalized, cd will attempt to use the supplied directory name.\n\n51. When the xpg_echo option is enabled, Bash does not attempt to interpret any arguments to echo as options. echo displays each argument after converting escape\nsequences.\n52. The export and readonly builtin commands display their output in the format required by posix.\n53. When listing the history, the fc builtin does not include an indication of whether or\nnot a history entry has been modified.\n54. The default editor used by fc is ed.\n55. fc treats extra arguments as an error instead of ignoring them.\n56. If there are too many arguments supplied to fc -s, fc prints an error message and\nreturns failure.\n57. The output of ‘kill -l’ prints all the signal names on a single line, separated by spaces,\nwithout the ‘SIG’ prefix.\n58. The kill builtin does not accept signal names with a ‘SIG’ prefix.\n59. The kill builtin returns a failure status if any of the pid or job arguments are invalid\nor if sending the specified signal to any of them fails. In default mode, kill returns success if the signal was successfully sent to any of the specified processes.\n60. The printf builtin uses double (via strtod) to convert arguments corresponding to\nfloating point conversion specifiers, instead of long double if it’s available. The ‘L’ length modifier forces printf to use long double if it’s available.\n61. The pwd builtin verifies that the value it prints is the same as the current directory,\neven if it is not asked to check the file system with the -P option.\n62. The read builtin may be interrupted by a signal for which a trap has been set. If Bash\nreceives a trapped signal while executing read, the trap handler executes and read returns an exit status greater than 128.\n63. When the set builtin is invoked without options, it does not display shell function\nnames and definitions.\n64. When the set builtin is invoked without options, it displays variable values without\nquotes, unless they contain shell metacharacters, even if the result contains nonprinting characters.\n65. The test builtin compares strings using the current locale when evaluating the ‘<’ and\n‘>’ binary operators.\n66. The test builtin’s -t unary primary requires an argument. Historical versions of test\nmade the argument optional in certain cases, and Bash attempts to accommodate those\nfor backwards compatibility.\n67. The trap builtin displays signal names without the leading SIG.\n68. The trap builtin doesn’t check the first argument for a possible signal specification\nand revert the signal handling to the original disposition if it is, unless that argument consists solely of digits and is a valid signal number. If users want to reset the handler\nfor a given signal to the original disposition, they should use ‘-’ as the first argument.\n69. trap -p without arguments displays signals whose dispositions are set to SIG DFL and\nthose that were ignored when the shell started, not just trapped signals.\n\n70. The type and command builtins will not report a non-executable file as having been\nfound, though the shell will attempt to execute such a file if it is the only so-named file found in $PATH.\n71. The ulimit builtin uses a block size of 512 bytes for the -c and -f options.\n72. The unset builtin with the -v option specified returns a fatal error if it attempts to\nunset a readonly or non-unsettable variable, which causes a non-interactive shell to exit.\n73. When asked to unset a variable that appears in an assignment statement preceding\nthe command, the unset builtin attempts to unset a variable of the same name in the current or previous scope as well. This implements the required \ behavior.\n74. The arrival of SIGCHLD when a trap is set on SIGCHLD does not interrupt the wait\nbuiltin and cause it to return immediately. The trap command is run once for each child that exits.\n75. Bash removes an exited background process’s status from the list of such statuses after\nthe wait builtin returns it. There is additional posix behavior that Bash does not implement by default even when in posix mode. Specifically:\n1. posix requires that word splitting be byte-oriented. That is, each byte in the value of\nIFS potentially splits a word, even if that byte is part of a multibyte character in IFS or part of multibyte character in the word. Bash allows multibyte characters in the value of IFS, treating a valid multibyte character as a single delimiter, and will not split a valid multibyte character even if one of the bytes composing that character appears in IFS. This is posix interpretation 1560, further modified by issue 1924.\n2. The fc builtin checks $EDITOR as a program to edit history entries if FCEDIT is unset,\nrather than defaulting directly to ed. fc uses ed if EDITOR is unset.\n3. As noted above, Bash requires the xpg_echo option to be enabled for the echo builtin\nto be fully conformant. Bash can be configured to be posix-conformant by default, by specifying the --enablestrict-posix-default to configure when building. |
| chapter_titleBash Featuressection_titleShell Compatibility Modenum_wordsnum_charstextBash-4.0 introduced the concept of a shell compatibility level, specified as a set of options to the shopt builtin (compat31, compat32, compat40, compat41, and so on). There is only one current compatibility level – each option is mutually exclusive. The compatibility level is intended to allow users to select behavior from previous versions that is incompatible with newer versions while they migrate scripts to use current features and behavior. It’s intended to be a temporary solution. This section does not mention behavior that is standard for a particular version (e.g., setting compat32 means that quoting the right hand side of the regexp matching operator quotes special regexp characters in the word, which is default behavior in bash-3.2 and subsequent versions).\n\nIf a user enables, say, compat32, it may affect the behavior of other compatibility levels up to and including the current compatibility level. The idea is that each compatibility level controls behavior that changed in that version of Bash, but that behavior may have been present in earlier versions. For instance, the change to use locale-based comparisons with the [[ command came in bash-4.1, and earlier versions used ASCII-based comparisons, so enabling compat32 will enable ASCII-based comparisons as well. That granularity may not be sufficient for all uses, and as a result users should employ compatibility levels carefully. Read the documentation for a particular feature to find out the current behavior. Bash-4.3 introduced a new shell variable: BASH_COMPAT. The value assigned to this variable (a decimal version number like 4.2, or an integer corresponding to the compatNN option, like 42) determines the compatibility level. Starting with bash-4.4, Bash began deprecating older compatibility levels. Eventually, the options will be removed in favor of BASH_COMPAT. Bash-5.0 was the final version for which there was an individual shopt option for the previous version. BASH_COMPAT is the only mechanism to control the compatibility level in versions newer than bash-5.0. The following table describes the behavior changes controlled by each compatibility level setting. The compatNN tag is used as shorthand for setting the compatibility level to NN using one of the following mechanisms. For versions prior to bash-5.0, the compatibility level may be set using the corresponding compatNN shopt option. For bash-4.3 and later versions, the BASH_COMPAT variable is preferred, and it is required for bash-5.1 and later versions. compat31\n• Quoting the rhs of the [[ command’s regexp matching operator (=~) has\nno special effect compat40\n• The ‘<’ and ‘>’ operators to the [[ command do not consider the current\nlocale when comparing strings; they use ASCII ordering. Bash versions prior to bash-4.1 use ASCII collation and strcmp(3); bash-4.1 and later use the current locale’s collation sequence and strcoll(3). compat41\n• In posix mode, time may be followed by options and still be recognized\nas a reserved word (this is posix interpretation 267).\n• In posix mode, the parser requires that an even number of single quotes\noccur in the word portion of a double-quoted ${... } parameter expansion and treats them specially, so that characters within the single quotes are considered quoted (this is posix interpretation 221). compat42\n• The replacement string in double-quoted pattern substitution does not\nundergo quote removal, as it does in versions after bash-4.2.\n• In posix mode, single quotes are considered special when expanding the\nword portion of a double-quoted ${... } parameter expansion and can be used to quote a closing brace or other special character (this is part of\n\nposix interpretation 221); in later versions, single quotes are not special within double-quoted word expansions. compat43\n• Word expansion errors are considered non-fatal errors that cause the current command to fail, even in posix mode (the default behavior is to make\nthem fatal errors that cause the shell to exit).\n• When executing a shell function, the loop state (while/until/etc.) is not\nreset, so break or continue in that function will break or continue loops in the calling context. Bash-4.4 and later reset the loop state to prevent this. compat44\n• The shell sets up the values used by BASH_ARGV and BASH_ARGC so they\ncan expand to the shell’s positional parameters even if extended debugging mode is not enabled.\n• A subshell inherits loops from its parent context, so break or continue\nwill cause the subshell to exit. Bash-5.0 and later reset the loop state to prevent the exit.\n• Variable assignments preceding builtins like export and readonly that set\nattributes continue to affect variables with the same name in the calling environment even if the shell is not in posix mode. compat50 (set using BASH_COMPAT)\n• Bash-5.1 changed the way $RANDOM is generated to introduce slightly more\nrandomness. If the shell compatibility level is set to 50 or lower, it reverts to the method from bash-5.0 and previous versions, so seeding the random number generator by assigning a value to RANDOM will produce the same sequence as in bash-5.0.\n• If the command hash table is empty, Bash versions prior to bash-5.1 printed\nan informational message to that effect, even when producing output that can be reused as input. Bash-5.1 suppresses that message when the -l option is supplied. compat51 (set using BASH_COMPAT)\n• The unset builtin will unset the array a given an argument like ‘a[@]’.\nBash-5.2 will unset an element with key ‘@’ (associative arrays) or remove all the elements without unsetting the array (indexed arrays).\n• Arithmetic commands ( ((... )) ) and the expressions in an arithmetic for\nstatement can be expanded more than once.\n• Expressions used as arguments to arithmetic operators in the [[ conditional\ncommand can be expanded more than once.\n• The expressions in substring parameter brace expansion can be expanded\nmore than once.\n• The expressions in the $((... )) word expansion can be expanded more\nthan once.\n\n• Arithmetic expressions used as indexed array subscripts can be expanded\nmore than once.\n• test -v, when given an argument of ‘A[@]’, where A is an existing associative array, will return true if the array has any set elements. Bash-5.2\nwill look for and report on a key named ‘@’.\n• the ${parameter[:]=value } word expansion will return value, before any\nvariable-specific transformations have been performed (e.g., converting to lowercase). Bash-5.2 will return the final value assigned to the variable.\n• Parsing command substitutions will behave as if extended globbing is enabled, so that parsing a\ncommand substitution containing an extglob pattern (say, as part of a shell\nfunction) will not fail. This assumes the intent is to enable extglob before\nthe command is executed and word expansions are performed. It will fail at word expansion time if extglob hasn’t been enabled by the time the command is executed. compat52 (set using BASH_COMPAT)\n• The test builtin uses its historical algorithm to parse parenthesized subexpressions when given five or more arguments.\n• If the -p or -P option is supplied to the bind builtin, bind treats any arguments remaining after option processing as bindable command names, and\ndisplays any key sequences bound to those commands, instead of treating the arguments as key sequences to bind.\n• Interactive shells will notify the user of completed jobs while sourcing a\nscript. Newer versions defer notification until script execution completes. |
| chapter_titleJob Controlsection_titleJob Controlnum_wordsnum_charstextThis chapter discusses what job control is, how it works, and how Bash allows you to access its facilities. |
| chapter_titleJob Controlsection_titleJob Control Basicsnum_wordsnum_charstextJob control refers to the ability to selectively stop (suspend) the execution of processes and continue (resume) their execution at a later point. A user typically employs this facility via an interactive interface supplied jointly by the operating system kernel’s terminal driver and Bash. The shell associates a job with each pipeline. It keeps a table of currently executing jobs, which the jobs command will display. Each job has a job number, which jobs displays between brackets. Job numbers start at 1. When Bash starts a job asynchronously, it prints a line that looks like: [1] 25647 indicating that this job is job number 1 and that the process id of the last process in the pipeline associated with this job is 25647. All of the processes in a single pipeline are members of the same job. Bash uses the job abstraction as the basis for job control. To facilitate the implementation of the user interface to job control, each process has a process group id, and the operating system maintains the notion of a current terminal process group id. This terminal process group id is associated with the controlling terminal. Processes that have the same process group ID are said to be part of the same process group. Members of the foreground process group (processes whose process group id is equal to the current terminal process group id) receive keyboard-generated signals such as SIGINT. Processes in the foreground process group are said to be foreground processes. Background processes are those whose process group id differs from the controlling terminal’s; such processes are immune to keyboard-generated signals. Only foreground processes are allowed to read from or, if the user so specifies with stty tostop, write to the controlling terminal. The system sends a SIGTTIN (SIGTTOU) signal to background processes which attempt to read from (write to when tostop is in effect) the terminal, which, unless caught, suspends the process. If the operating system on which Bash is running supports job control, Bash contains facilities to use it. Typing the suspend character (typically ‘^Z’, Control-Z) while a process is running stops that process and returns control to Bash. Typing the delayed suspend character (typically ‘^Y’, Control-Y) causes the process to stop when it attempts to read input from the terminal, and returns control to Bash. The user then manipulates the state of this job, using the bg command to continue it in the background, the fg command to continue it in the foreground, or the kill command to kill it. The suspend character takes effect immediately, and has the additional side effect of discarding any pending output and typeahead. If you want to force a background process to stop, or stop a process that’s not associated with your terminal session, send it the SIGSTOP signal using kill. There are a number of ways to refer to a job in the shell. The ‘%’ character introduces a job specification (jobspec). Job number n may be referred to as ‘%n’. A job may also be referred to using a prefix of the name used to start it, or using a substring that appears in its command line. For\n\nexample, ‘%ce’ refers to a job whose command name begins with ‘ce’. Using ‘%?ce’, on the other hand, refers to any job containing the string ‘ce’ in its command line. If the prefix or substring matches more than one job, Bash reports an error. The symbols ‘%%’ and ‘%+’ refer to the shell’s notion of the current job. A single ‘%’ (with no accompanying job specification) also refers to the current job. ‘%-’ refers to the previous job. When a job starts in the background, a job stops while in the foreground, or a job is resumed in the background, it becomes the current job. The job that was the current job becomes the previous job. When the current job terminates, the previous job becomes the current job. If there is only a single job, ‘%+’ and ‘%-’ can both be used to refer to that job. In output pertaining to jobs (e.g., the output of the jobs command), the current job is always marked with a ‘+’, and the previous job with a ‘-’. Simply naming a job can be used to bring it into the foreground: ‘%1’ is a synonym for ‘fg %1’, bringing job 1 from the background into the foreground. Similarly, ‘%1 &’ resumes job 1 in the background, equivalent to ‘bg %1’. The shell learns immediately whenever a job changes state. Normally, Bash waits until it is about to print a prompt before notifying the user about changes in a job’s status so as to not interrupt any other output, though it will notify of changes in a job’s status after a foreground command in a list completes, before executing the next command in the list. If the -b option to the set builtin is enabled, Bash reports status changes immediately. Bash executes any trap on SIGCHLD for each child process that terminates. When a job terminates and Bash notifies the user about it, Bash removes the job from the jobs table. It will not appear in jobs output, but wait will report its exit status, as long as it’s supplied the process ID associated with the job as an argument. When the table is empty, job numbers start over at 1. If a user attempts to exit Bash while jobs are stopped, (or running, if the checkjobs option is enabled – see Section 4.3.2 [The Shopt Builtin], page 78), the shell prints a warning message, and if the checkjobs option is enabled, lists the jobs and their statuses. The jobs command may then be used to inspect their status. If the user immediately attempts to exit again, without an intervening command, Bash does not print another warning, and terminates any stopped jobs. When the shell is waiting for a job or process using the wait builtin, and job control is enabled, wait will return when the job changes state. The -f option causes wait to wait\nuntil the job or process terminates before returning. |
| chapter_titleJob Controlsection_titleJob Control Builtinsnum_wordsnum_charstextbg bg [jobspec...] Resume each suspended job jobspec in the background, as if it had been started with ‘&’. If jobspec is not supplied, the shell uses its notion of the current job. bg returns zero unless it is run when job control is not enabled, or, when run with job control enabled, any jobspec was not found or specifies a job that was started without job control.\n\nfg fg [jobspec] Resume the job jobspec in the foreground and make it the current job. If jobspec is not supplied, fg resumes the current job. The return status is that of the command placed into the foreground, or non-zero if run when job control is disabled or, when run with job control enabled, jobspec does not specify a valid job or jobspec specifies a job that was started without job control. jobs jobs [-lnprs] [jobspec] jobs -x command [arguments] The first form lists the active jobs. The options have the following meanings: -l\n\nList process ids in addition to the normal information.\n\n-n\n\nDisplay information only about jobs that have changed status since the user was last notified of their status.\n\n-p\n\nList only the process id of the job’s process group leader.\n\n-r\n\nDisplay only running jobs.\n\n-s\n\nDisplay only stopped jobs.\n\nIf jobspec is supplied, jobs restricts output to information about that job. If jobspec is not supplied, jobs lists the status of all jobs. The return status is zero unless an invalid option is encountered or an invalid jobspec is supplied. If the -x option is supplied, jobs replaces any jobspec found in command or arguments with the corresponding process group id, and executes command, passing it arguments, returning its exit status. kill kill [-s sigspec] [-n signum] [-sigspec] id [...] kill -l|-L [exit_status] Send a signal specified by sigspec or signum to the processes named by each id. Each id may be a job specification jobspec or process id pid. sigspec is either a case-insensitive signal name such as SIGINT (with or without the SIG prefix) or a signal number; signum is a signal number. If sigspec and signum are not present, kill sends SIGTERM. The -l option lists the signal names. If any arguments are supplied when -l is supplied, kill lists the names of the signals corresponding to the arguments, and the return status is zero. exit status is a number specifying a signal number or the exit status of a process terminated by a signal; if it is supplied, kill prints the name of the signal that caused the process to terminate. kill assumes that process exit statuses are greater than 128; anything less than that is a signal number. The -L option is equivalent to -l. The return status is zero if at least one signal was successfully sent, or non-zero\nif an error occurs or an invalid option is encountered.\n\nwait wait [-fn] [-p varname] [id...] Wait until the child process specified by each id exits and return the exit status of the last id. Each id may be a process id pid or a job specification jobspec;\nif a jobspec is supplied, wait waits for all processes in the job.\nIf no options or ids are supplied, wait waits for all running background jobs and the last-executed process substitution, if its process id is the same as $!, and the return status is zero. If the -n option is supplied, wait waits for any one of the ids or, if no ids are supplied, any job or process substitution, to complete and returns its exit status. If none of the supplied ids is a child of the shell, or if no arguments are supplied and the shell has no unwaited-for children, the exit status is 127. If the -p option is supplied, wait assigns the process or job identifier of the job for which the exit status is returned to the variable varname named by the option argument. The variable, which cannot be readonly, will be unset initially, before any assignment. This is useful only when used with the -n option. Supplying the -f option, when job control is enabled, forces wait to wait for each id to terminate before returning its status, instead of returning when it changes status. If none of the ids specify one of the shell’s an active child processes, the return status is 127. If wait is interrupted by a signal, any varname will remain unset, and the return status will be greater than 128, as described above. Otherwise, the return status is the exit status of the last id. disown disown [-ar] [-h] [id...] Without options, remove each id from the table of active jobs. Each id may be a job specification jobspec or a process id pid; if id is a pid, disown uses the job containing pid as jobspec. If the -h option is supplied, disown does not remove the jobs corresponding to each id from the jobs table, but rather marks them so the shell does not send SIGHUP to the job if the shell receives a SIGHUP. If no id is supplied, the -a option means to remove or mark all jobs; the -r option without an id argument removes or marks running jobs. If no id is supplied, and neither the -a nor the -r option is supplied, disown removes or marks the current job. The return value is 0 unless an id does not specify a valid job. suspend suspend [-f] Suspend the execution of this shell until it receives a SIGCONT signal. A login shell, or a shell without job control enabled, cannot be suspended; the -f option will override this and force the suspension. The return status is 0 unless the shell is a login shell or job control is not enabled and -f is not supplied.\n\nWhen job control is not active, the kill and wait builtins do not accept jobspec arguments. They must be supplied process ids. |
| chapter_titleJob Controlsection_titleJob Control Variablesnum_wordsnum_charstextauto_resume This variable controls how the shell interacts with the user and job control. If this variable exists then simple commands consisting of only a single word, without redirections, are treated as candidates for resumption of an existing job. There is no ambiguity allowed; if there is more than one job beginning with or containing the word, then this selects the most recently accessed job. The name of a stopped job, in this context, is the command line used to start it, as displayed by jobs. If this variable is set to the value ‘exact’, the word must match the name of a stopped job exactly; if set to ‘substring’, the word needs to match a substring of the name of a stopped job. The ‘substring’ value provides functionality analogous to the ‘%?string’ job id. If set to any other value (e.g., ‘prefix’), the word must be a prefix of a stopped job’s name; this provides functionality analogous to the ‘%string’ job id. |
| chapter_titleCommand Line Editingsection_titleCommand Line Editingnum_wordsnum_charstextThis chapter describes the basic features of the gnu command line editing interface. Command line editing is provided by the Readline library, which is used by several different programs, including Bash. Command line editing is enabled by default when using an interactive shell, unless the --noediting option is supplied at shell invocation. Line editing is also used when using the -e option to the read builtin command. By default, the line editing commands are similar to those of Emacs; a vi-style line editing interface is also available. Line editing can be enabled at any time using the -o emacs or -o vi options to the set builtin command, or disabled using the +o emacs or +o vi options to set. |
| chapter_titleCommand Line Editingsection_titleIntroduction to Line Editingnum_wordsnum_charstextThe following paragraphs use Emacs style to describe the notation used to represent keystrokes. The text C-k is read as ‘Control-K’ and describes the character produced when the k key is pressed while the Control key is depressed. The text M-k is read as ‘Meta-K’ and describes the character produced when the Meta key (if you have one) is depressed, and the k key is pressed (a meta character), then both are released. The Meta key is labeled ALT or Option on many keyboards. On keyboards with two keys labeled ALT (usually to either side of the space bar), the ALT on the left side is generally set to work as a Meta key. One of the ALT keys may also be configured as some other modifier, such as a Compose key for typing accented characters. On some keyboards, the Meta key modifier produces characters with the eighth bit (0200) set. You can use the enable-meta-key variable to control whether or not it does this, if the keyboard allows it. On many others, the terminal or terminal emulator converts the metafied key to a key sequence beginning with ESC. If you do not have a Meta or ALT key, or another key working as a Meta key, you can generally achieve the latter effect by typing ESC first, and then typing k. The ESC character is known as the meta prefix). Either process is known as metafying the k key. If your Meta key produces a key sequence with the ESC meta prefix, you can make M-key key bindings you specify (see Key Bindings in Section 8.3.1 [Readline Init File Syntax], page 133) do the same thing by setting the force-meta-prefix variable. The text M-C-k is read as ‘Meta-Control-k’ and describes the character produced by metafying C-k. In addition, several keys have their own names. Specifically, DEL, ESC, LFD, SPC, RET, and TAB all stand for themselves when seen in this text, or in an init file. If your keyboard lacks a LFD key, typing C-j will output the appropriate character. The RET key may be labeled Return or Enter on some keyboards. |
| chapter_titleCommand Line Editingsection_titleReadline Interactionnum_wordsnum_charstextOften during an interactive session you type in a long line of text, only to notice that the first word on the line is misspelled. The Readline library gives you a set of commands for\n\nmanipulating the text as you type it in, allowing you to just fix your typo, and not forcing you to retype the majority of the line. Using these editing commands, you move the cursor to the place that needs correction, and delete or insert the text of the corrections. Then, when you are satisfied with the line, you simply press RET. You do not have to be at the end of the line to press RET; the entire line is accepted regardless of the location of the cursor within the line. |
| chapter_titleCommand Line Editingsection_titleReadline Bare Essentialsnum_wordsnum_charstextIn order to enter characters into the line, simply type them. The typed character appears where the cursor was, and then the cursor moves one space to the right. If you mistype a character, you can use your erase character to back up and delete the mistyped character. Sometimes you may mistype a character, and not notice the error until you have typed several other characters. In that case, you can type C-b to move the cursor to the left, and\nthen correct your mistake. Afterwards, you can move the cursor to the right with C-f.\nWhen you add text in the middle of a line, you will notice that characters to the right of the cursor are ‘pushed over’ to make room for the text that you have inserted. Likewise, when you delete text behind the cursor, characters to the right of the cursor are ‘pulled back’ to fill in the blank space created by the removal of the text. These are the bare essentials for editing the text of an input line: C-b\n\nMove back one character.\n\nC-f\n\nMove forward one character.\n\nDEL or Backspace Delete the character to the left of the cursor. C-d\n\nDelete the character underneath the cursor.\n\nPrinting characters Insert the character into the line at the cursor. C-_ or C-x C-u Undo the last editing command. You can undo all the way back to an empty line. Depending on your configuration, the Backspace key might be set to delete the character to the left of the cursor and the DEL key set to delete the character underneath the cursor, like C-d, rather than the character to the left of the cursor. |
| chapter_titleCommand Line Editingsection_titleReadline Movement Commandsnum_wordsnum_charstextThe above table describes the most basic keystrokes that you need in order to do editing of the input line. For your convenience, many other commands are available in addition to C-b, C-f, C-d, and DEL. Here are some commands for moving more rapidly within the line. C-a\n\nMove to the start of the line.\n\nC-e\n\nMove to the end of the line.\n\nM-f\n\nMove forward a word, where a word is composed of letters and digits.\n\nM-b\n\nMove backward a word.\n\nChapter 8: Command Line Editing\n\nC-l\n\nClear the screen, reprinting the current line at the top.\n\nNotice how C-f moves forward a character, while M-f moves forward a word. It is a loose convention that control keystrokes operate on characters while meta keystrokes operate on words. |
| chapter_titleCommand Line Editingsection_titleReadline Killing Commandsnum_wordsnum_charstextKilling text means to delete the text from the line, but to save it away for later use, usually by yanking (re-inserting) it back into the line. (‘Cut’ and ‘paste’ are more recent jargon for ‘kill’ and ‘yank’.) If the description for a command says that it ‘kills’ text, then you can be sure that you can get the text back in a different (or the same) place later. When you use a kill command, the text is saved in a kill-ring. Any number of consecutive kills save all of the killed text together, so that when you yank it back, you get it all. The kill ring is not line specific; the text that you killed on a previously typed line is available to be yanked back later, when you are typing another line. Here is the list of commands for killing text. C-k\n\nKill the text from the current cursor position to the end of the line.\n\nM-d\n\nKill from the cursor to the end of the current word, or, if between words, to the end of the next word. Word boundaries are the same as those used by M-f.\n\nM-DEL\n\nKill from the cursor to the start of the current word, or, if between words, to the start of the previous word. Word boundaries are the same as those used by M-b.\n\nC-w\n\nKill from the cursor to the previous whitespace. This is different than M-DEL because the word boundaries differ.\n\nHere is how to yank the text back into the line. Yanking means to copy the mostrecently-killed text from the kill buffer into the line at the current cursor position. C-y\n\nYank the most recently killed text back into the buffer at the cursor.\n\nM-y\n\nRotate the kill-ring, and yank the new top. You can only do this if the prior command is C-y or M-y. |
| chapter_titleCommand Line Editingsection_titleReadline Argumentsnum_wordsnum_charstextYou can pass numeric arguments to Readline commands. Sometimes the argument acts as a repeat count, other times it is the sign of the argument that is significant. If you pass a negative argument to a command which normally acts in a forward direction, that command will act in a backward direction. For example, to kill text back to the start of the line, you might type ‘M-- C-k’. The general way to pass numeric arguments to a command is to type meta digits before the command. If the first ‘digit’ typed is a minus sign (‘-’), then the sign of the argument will be negative. Once you have typed one meta digit to get the argument started, you can type the remainder of the digits, and then the command. For example, to give the C-d command an argument of 10, you could type ‘M-1 0 C-d’, which will delete the next ten characters on the input line. |
| chapter_titleCommand Line Editingsection_titleSearching for Commands in the Historynum_wordsnum_charstextReadline provides commands for searching through the command history for lines containing a specified string. There are two search modes: incremental and non-incremental. Incremental searches begin before the user has finished typing the search string. As each character of the search string is typed, Readline displays the next entry from the history matching the string typed so far. An incremental search requires only as many characters as needed to find the desired history entry. When using emacs editing mode, type C-r to search backward in the history for a particular string. Typing C-s searches forward through the history. The characters present in the value of the isearch-terminators variable are used to terminate an incremental search. If that variable has not been assigned a value, the ESC and C-j characters terminate an incremental search. C-g aborts an incremental search and restores the original line. When the search is terminated, the history entry containing the search string becomes the current line. To find other matching entries in the history list, type C-r or C-s as appropriate. This searches backward or forward in the history for the next entry matching the search string typed so far. Any other key sequence bound to a Readline command terminates the search and executes that command. For instance, a RET terminates the search and accepts the line, thereby executing the command from the history list. A movement command will terminate the search, make the last line found the current line, and begin editing. Readline remembers the last incremental search string. If two C-rs are typed without any intervening characters defining a new search string, Readline uses any remembered search string. Non-incremental searches read the entire search string before starting to search for matching history entries. The search string may be typed by the user or be part of the contents of the current line. |
| chapter_titleCommand Line Editingsection_titleReadline Init Filenum_wordsnum_charstextAlthough the Readline library comes with a set of Emacs-like keybindings installed by default, it is possible to use a different set of keybindings. Any user can customize programs that use Readline by putting commands in an inputrc file, conventionally in their home directory. The name of this file is taken from the value of the shell variable INPUTRC. If that variable is unset, the default is ~/.inputrc. If that file does not exist or cannot be read, Readline looks for /etc/inputrc. The bind builtin command can also be used to set Readline keybindings and variables. When a program that uses the Readline library starts up, Readline reads the init file and sets any variables and key bindings it contains. In addition, the C-x C-r command re-reads this init file, thus incorporating any changes that you might have made to it. |
| chapter_titleCommand Line Editingsection_titleReadline Init File Syntaxnum_wordsnum_charstextThere are only a few basic constructs allowed in the Readline init file. Blank lines are ignored. Lines beginning with a ‘#’ are comments. Lines beginning with a ‘$’ indicate conditional constructs. Other lines denote variable settings and key bindings.\n\nVariable Settings You can modify the run-time behavior of Readline by altering the values of variables in Readline using the set command within the init file. The syntax is simple: set variable value Here, for example, is how to change from the default Emacs-like key binding to use vi line editing commands: set editing-mode vi Variable names and values, where appropriate, are recognized without regard to case. Unrecognized variable names are ignored. Boolean variables (those that can be set to on or off) are set to on if the value is null or empty, on (case-insensitive), or 1. Any other value results in the variable being set to off. The bind -V command lists the current Readline variable names and values. A great deal of run-time behavior is changeable with the following variables. active-region-start-color A string variable that controls the text color and background when displaying the text in the active region (see the description of enable-active-region below). This string must not take up any physical character positions on the display, so it should consist only of terminal escape sequences. It is output to the terminal before displaying the text in the active region. This variable is reset to the default value whenever the terminal type changes. The default value is the string that puts the terminal in standout mode, as obtained from the terminal’s terminfo description. A sample value might be ‘\\e[01;33m’. active-region-end-color A string variable that “undoes” the effects of active-regionstart-color and restores “normal” terminal display appearance after displaying text in the active region. This string must not take up any physical character positions on the display, so it should consist only of terminal escape sequences. It is output to the terminal after displaying the text in the active region. This variable is reset to the default value whenever the terminal type changes. The default value is the string that restores the terminal from standout mode, as obtained from the terminal’s terminfo description. A sample value might be ‘\\e[0m’. bell-style Controls what happens when Readline wants to ring the terminal bell. If set to ‘none’, Readline never rings the bell. If set to ‘visible’, Readline uses a visible bell if one is available. If set to ‘audible’ (the default), Readline attempts to ring the terminal’s bell.\n\nbind-tty-special-chars If set to ‘on’ (the default), Readline attempts to bind the control characters that are treated specially by the kernel’s terminal driver to their Readline equivalents. These override the default Readline bindings described here. Type ‘stty -a’ at a Bash prompt to see your current terminal settings, including the special control characters (usually cchars). blink-matching-paren If set to ‘on’, Readline attempts to briefly move the cursor to an opening parenthesis when a closing parenthesis is inserted. The default is ‘off’. colored-completion-prefix If set to ‘on’, when listing completions, Readline displays the common prefix of the set of possible completions using a different color. The color definitions are taken from the value of the LS_COLORS environment variable. If there is a color definition in LS_COLORS for the custom suffix ‘readline-colored-completion-prefix’, Readline uses this color for the common prefix instead of its default. The default is ‘off’. colored-stats If set to ‘on’, Readline displays possible completions using different colors to indicate their file type. The color definitions are taken from the value of the LS_COLORS environment variable. The default is ‘off’. comment-begin The string to insert at the beginning of the line by the insert-comment command. The default value is \. completion-display-width The number of screen columns used to display possible matches when performing completion. The value is ignored if it is less than 0 or greater than the terminal screen width. A value of 0 causes matches to be displayed one per line. The default value is -1. completion-ignore-case If set to ‘on’, Readline performs filename matching and completion in a case-insensitive fashion. The default value is ‘off’. completion-map-case If set to ‘on’, and completion-ignore-case is enabled, Readline treats hyphens (‘-’) and underscores (‘_’) as equivalent when performing\ncase-insensitive filename matching and completion. The default\nvalue is ‘off’. completion-prefix-display-length The maximum length in characters of the common prefix of a list of possible completions that is displayed without modification. When\n\nset to a value greater than zero, Readline replaces common prefixes longer than this value with an ellipsis when displaying possible completions. If a completion begins with a period, and Readline is completing filenames, it uses three underscores instead of an ellipsis. completion-query-items The number of possible completions that determines when the user is asked whether the list of possibilities should be displayed. If the number of possible completions is greater than or equal to this value, Readline asks whether or not the user wishes to view them; otherwise, Readline simply lists the completions. This variable must be set to an integer value greater than or equal to zero. A zero value means Readline should never ask; negative values are treated as zero. The default limit is 100. convert-meta If set to ‘on’, Readline converts characters it reads that have the eighth bit set to an ascii key sequence by clearing the eighth bit and prefixing an ESC character, converting them to a meta-prefixed key sequence. The default value is ‘on’, but Readline sets it to ‘off’\nif the locale contains characters whose encodings may include bytes\nwith the eighth bit set. This variable is dependent on the LC_CTYPE locale category, and may change if the locale changes. This variable also affects key bindings; see the description of force-meta-prefix below. disable-completion If set to ‘On’, Readline inhibits word completion. Completion characters are inserted into the line as if they had been mapped to self-insert. The default is ‘off’. echo-control-characters When set to ‘on’, on operating systems that indicate they support it, Readline echoes a character corresponding to a signal generated from the keyboard. The default is ‘on’. editing-mode The editing-mode variable controls the default set of key bindings. By default, Readline starts up in emacs editing mode, where the keystrokes are most similar to Emacs. This variable can be set to either ‘emacs’ or ‘vi’. emacs-mode-string If the show-mode-in-prompt variable is enabled, this string is displayed immediately before the last line of the primary prompt when emacs editing mode is active. The value is expanded like a key binding, so the standard set of meta- and control- prefixes and backslash escape sequences is available. The ‘\\1’ and ‘\\2’ escapes begin and end sequences of non-printing characters, which can be used to embed a terminal control sequence into the mode string. The default is ‘@’.\n\nenable-active-region point is the current cursor position, and mark refers to a saved cursor position. The text between the point and mark is referred to as the region. When this variable is set to ‘On’, Readline allows certain commands to designate the region as active. When the region is active, Readline highlights the text in the region using the value of the active-region-start-color, which defaults to the string that enables the terminal’s standout mode. The active region shows the text inserted by bracketed-paste and any matching text found by incremental and non-incremental history searches. The default is ‘On’. enable-bracketed-paste When set to ‘On’, Readline configures the terminal to insert each paste into the editing buffer as a single string of characters, instead of treating each character as if it had been read from the keyboard. This is called putting the terminal into bracketed paste mode; it prevents Readline from executing any editing commands bound to key sequences appearing in the pasted text. The default is ‘On’. enable-keypad When set to ‘on’, Readline tries to enable the application keypad when it is called. Some systems need this to enable the arrow keys. The default is ‘off’. enable-meta-key When set to ‘on’, Readline tries to enable any meta modifier key the terminal claims to support when it is called. On many terminals, the Meta key is used to send eight-bit characters; this variable checks for the terminal capability that indicates the terminal can enable and disable a mode that sets the eighth bit of a character (0200) if the Meta key is held down when the character is typed (a meta character). The default is ‘on’. expand-tilde If set to ‘on’, Readline attempts tilde expansion when it attempts word completion. The default is ‘off’. force-meta-prefix If set to ‘on’, Readline modifies its behavior when binding key sequences containing \\M- or Meta- (see Key Bindings in Section 8.3.1 [Readline Init File Syntax], page 133) by converting a key sequence of the form \\M-C or Meta-C to the two-character sequence ESC C (adding the meta prefix). If force-meta-prefix is set to ‘off’ (the default), Readline uses the value of the convert-meta variable to determine whether to perform this conversion: if convert-meta is ‘on’, Readline performs the conversion described above; if it is ‘off’, Readline converts C to a meta character by setting the eighth bit (0200). The default is ‘off’.\n\nhistory-preserve-point If set to ‘on’, the history code attempts to place the point (the current cursor position) at the same location on each history line retrieved with previous-history or next-history. The default is ‘off’. history-size Set the maximum number of history entries saved in the history list. If set to zero, any existing history entries are deleted and no new entries are saved. If set to a value less than zero, the number of history entries is not limited. By default, Bash sets the maximum number of history entries to the value of the HISTSIZE shell variable. If you try to set history-size to a non-numeric value, the maximum number of history entries will be set to 500. horizontal-scroll-mode Setting this variable to ‘on’ means that the text of the lines being edited will scroll horizontally on a single screen line when the lines are longer than the width of the screen, instead of wrapping onto a new screen line. This variable is automatically set to ‘on’ for terminals of height 1. By default, this variable is set to ‘off’. input-meta If set to ‘on’, Readline enables eight-bit input (that is, it does not clear the eighth bit in the characters it reads), regardless of what the terminal claims it can support. The default value is ‘off’, but Readline sets it to ‘on’ if the locale contains characters whose encodings may include bytes with the eighth bit set. This variable is dependent on the LC_CTYPE locale category, and its value may change if the locale changes. The name meta-flag is a synonym\nfor input-meta.\nisearch-terminators The string of characters that should terminate an incremental search without subsequently executing the character as a command. If this variable has not been given a value, the characters ESC and C-j terminate an incremental search. keymap\n\nSets Readline’s idea of the current keymap for key binding commands. Built-in keymap names are emacs, emacs-standard, emacs-meta, emacs-ctlx, vi, vi-move, vi-command, and vi-insert. vi is equivalent to vi-command (vi-move is also a synonym); emacs is equivalent to emacs-standard. Applications may add additional names. The default value is emacs; the value of the editing-mode variable also affects the default keymap.\n\nkeyseq-timeout Specifies the duration Readline will wait for a character when reading an ambiguous key sequence (one that can form a complete key\n\nsequence using the input read so far, or can take additional input to complete a longer key sequence). If Readline doesn’t receive any input within the timeout, it uses the shorter but complete key sequence. Readline uses this value to determine whether or not input is available on the current input source (rl_instream by default). The value is specified in milliseconds, so a value of 1000 means that Readline will wait one second for additional input. If this variable is set to a value less than or equal to zero, or to a non-numeric value, Readline waits until another key is pressed to decide which key sequence to complete. The default value is 500. mark-directories If set to ‘on’, completed directory names have a slash appended. The default is ‘on’. mark-modified-lines When this variable is set to ‘on’, Readline displays an asterisk (‘*’) at the start of history lines which have been modified. This variable is ‘off’ by default. mark-symlinked-directories If set to ‘on’, completed names which are symbolic links to directories have a slash appended, subject to the value of mark-directories. The default is ‘off’. match-hidden-files This variable, when set to ‘on’, forces Readline to match files whose names begin with a ‘.’ (hidden files) when performing filename completion. If set to ‘off’, the user must include the leading ‘.’ in the filename to be completed. This variable is ‘on’ by default. menu-complete-display-prefix If set to ‘on’, menu completion displays the common prefix of the list of possible completions (which may be empty) before cycling through the list. The default is ‘off’. output-meta If set to ‘on’, Readline displays characters with the eighth bit set directly rather than as a meta-prefixed escape sequence. The default is ‘off’, but Readline sets it to ‘on’ if the locale contains characters whose encodings may include bytes with the eighth bit set. This variable is dependent on the LC_CTYPE locale category, and its value may change if the locale changes. page-completions If set to ‘on’, Readline uses an internal pager resembling more(1) to display a screenful of possible completions at a time. This variable is ‘on’ by default. prefer-visible-bell See bell-style.\n\nprint-completions-horizontally If set to ‘on’, Readline displays completions with matches sorted horizontally in alphabetical order, rather than down the screen. The default is ‘off’. revert-all-at-newline If set to ‘on’, Readline will undo all changes to history lines before returning when executing accept-line. By default, history lines may be modified and retain individual undo lists across calls to readline(). The default is ‘off’. search-ignore-case If set to ‘on’, Readline performs incremental and non-incremental history list searches in a case-insensitive fashion. The default value is ‘off’. show-all-if-ambiguous This alters the default behavior of the completion functions. If set to ‘on’, words which have more than one possible completion cause the matches to be listed immediately instead of ringing the bell. The default value is ‘off’. show-all-if-unmodified This alters the default behavior of the completion functions in a fashion similar to show-all-if-ambiguous. If set to ‘on’, words which have more than one possible completion without any possible partial completion (the possible completions don’t share a common prefix) cause the matches to be listed immediately instead of ringing the bell. The default value is ‘off’. show-mode-in-prompt If set to ‘on’, add a string to the beginning of the prompt indicating the editing mode: emacs, vi command, or vi insertion. The mode strings are user-settable (e.g., emacs-mode-string). The default value is ‘off’. skip-completed-text If set to ‘on’, this alters the default completion behavior when inserting a single match into the line. It’s only active when performing completion in the middle of a word. If enabled, Readline does not insert characters from the completion that match characters after point in the word being completed, so portions of the word following the cursor are not duplicated. For instance, if this is enabled, attempting completion when the cursor is after the first ‘e’ in ‘Makefile’ will result in ‘Makefile’ rather than ‘Makefilefile’, assuming there is a single possible completion. The default value is ‘off’. vi-cmd-mode-string If the show-mode-in-prompt variable is enabled, this string is displayed immediately before the last line of the primary prompt when\n\nvi editing mode is active and in command mode. The value is expanded like a key binding, so the standard set of meta- and controlprefixes and backslash escape sequences is available. The ‘\\1’ and ‘\\2’ escapes begin and end sequences of non-printing characters, which can be used to embed a terminal control sequence into the mode string. The default is ‘(cmd)’. vi-ins-mode-string If the show-mode-in-prompt variable is enabled, this string is displayed immediately before the last line of the primary prompt when vi editing mode is active and in insertion mode. The value is expanded like a key binding, so the standard set of meta- and controlprefixes and backslash escape sequences is available. The ‘\\1’ and ‘\\2’ escapes begin and end sequences of non-printing characters, which can be used to embed a terminal control sequence into the mode string. The default is ‘(ins)’. visible-stats If set to ‘on’, a character denoting a file’s type is appended to the filename when listing possible completions. The default is ‘off’. Key Bindings The syntax for controlling key bindings in the init file is simple. First you need to find the name of the command that you want to change. The following sections contain tables of the command name, the default keybinding, if any, and a short description of what the command does. Once you know the name of the command, simply place on a line in the init file the name of the key you wish to bind the command to, a colon, and then the name of the command. There can be no space between the key name and the colon – that will be interpreted as part of the key name. The name of the key can be expressed in different ways, depending on what you find most comfortable. In addition to command names, Readline allows keys to be bound to a string that is inserted when the key is pressed (a macro). The difference between a macro and a command is that a macro is enclosed in single or double quotes. The bind -p command displays Readline function names and bindings in a format that can be put directly into an initialization file. Builtins], page 61. keyname: function-name or macro keyname is the name of a key spelled out in English. For example: Control-u: universal-argument Meta-Rubout: backward-kill-word Control-o: \ In the example above, C-u is bound to the function universal-argument, M-DEL is bound to the function backward-kill-word, and C-o is bound to run the macro expressed on the right hand side (that is, to insert the text ‘> output’ into the line).\n\nThis key binding syntax recognizes a number of symbolic character names: DEL, ESC, ESCAPE, LFD, NEWLINE, RET, RETURN, RUBOUT (a destructive backspace), SPACE, SPC, and TAB. \: function-name or macro keyseq differs from keyname above in that strings denoting an entire key sequence can be specified, by placing the key sequence in double quotes. Some gnu Emacs style key escapes can be used, as in the following example, but none of the special character names are recognized. \: universal-argument \: re-read-init-file \: \ In the above example, C-u is again bound to the function universal-argument (just as it was in the first example), ‘C-x C-r’ is bound to the function re-read-init-file, and ‘ESC [ 1 1 ~’ is bound to insert the text ‘Function Key 1’. The following gnu Emacs style escape sequences are available when specifying key sequences: \\C-\n\nA control prefix.\n\n\\M-\n\nAdding the meta prefix or converting the following character to a meta character, as described above under force-meta-prefix (see Variable Settings in Section 8.3.1 [Readline Init File Syntax], page 133).\n\n\\e\n\nAn escape character.\n\n\\\\\n\nBackslash.\n\n\\\, a double quotation mark.\n\n\\’\n\n’, a single quote or apostrophe.\n\nIn addition to the gnu Emacs style escape sequences, a second set of backslash escapes is available:\n\\a\n\nalert (bell)\n\n\\b\n\nbackspace\n\n\\d\n\ndelete\n\n\\f\n\nform feed\n\n\\n\n\nnewline\n\n\\r\n\ncarriage return\n\n\\t\n\nhorizontal tab\n\n\\v\n\nvertical tab\n\n\\nnn\n\nThe eight-bit character whose value is the octal value nnn (one to three digits).\n\nThe eight-bit character whose value is the hexadecimal value HH (one or two hex digits).\n\n\\xHH\n\nWhen entering the text of a macro, single or double quotes must be used to indicate a macro definition. Unquoted text is assumed to be a function name. The backslash escapes described above are expanded in the macro body. Backslash will quote any other character in the macro text, including ‘\\\C-x\\\\\\\\\\} |
| {: , : , : 534, : 3298, : \\C-xq\\\eb\\\\} |
| {: , : , : 374, : 2463, : \\M-OD\\\M-OC\\\M-OA\\\M-OB\\\M-[D\\\M-[C\\\M-[A\\\M-[B\\\M-\\C-OD\\\M-\\C-OC\\\M-\\C-OA\\\M-\\C-OB\\\M-\\C-[D\\\M-\\C-[C\\\M-\\C-[A\\\M-\\C-[B\\\C-xp\PATH=${PATH}\\e\\C-e\\C-a\\ef\\C-f\\\C-x\\\: \\\\\n# insert a backslash (testing backslash escapes\n# in sequences and macros)\n\: \\n# Quote the current or previous word\n\: \\\ef\\\\n# Add a binding to refresh the line, which is unbound\n\: redraw-current-line\n# Edit variable on current line.\n\: \ $endif\n# use a visible bell if one is available\nset bell-style visible\n# don’t strip characters to 7 bits when reading\nset input-meta on\n# allow iso-latin1 characters to be inserted rather\n# than converted to prefix-meta sequences\nset convert-meta off\n# display characters with the eighth bit set directly\n# rather than as meta-prefixed characters\nset output-meta on\n# if there are 150 or more possible completions for a word,\n# ask whether or not the user wants to see all of them\nset completion-query-items 150\n\n# For FTP\n$if Ftp \: \ \: \ \: yank-last-arg $endif |
| chapter_titleCommand Line Editingsection_titleBindable Readline Commandsnum_wordsnum_charstextThis section describes Readline commands that may be bound to key sequences. You can list your key bindings by executing bind -P or, for a more terse format, suitable for an inputrc file, bind -p. Command names without an accompanying key sequence are unbound by default. In the following descriptions, point refers to the current cursor position, and mark refers to a cursor position saved by the set-mark command. The text between the point and mark is referred to as the region. Readline has the concept of an active region: when the region is active, Readline redisplay highlights the region using the value of the active-regionstart-color variable. The enable-active-region variable turns this on and off. Several commands set the region to active; those are noted below. |
| chapter_titleCommand Line Editingsection_titleCommands For Movingnum_wordsnum_charstextbeginning-of-line (C-a) Move to the start of the current line. This may also be bound to the Home key on some keyboards. end-of-line (C-e) Move to the end of the line. This may also be bound to the End key on some keyboards. forward-char (C-f) Move forward a character. This may also be bound to the right arrow key on some keyboards. backward-char (C-b) Move back a character. This may also be bound to the left arrow key on some keyboards. forward-word (M-f) Move forward to the end of the next word. Words are composed of letters and digits. backward-word (M-b) Move back to the start of the current or previous word. Words are composed of letters and digits. shell-forward-word (M-C-f) Move forward to the end of the next word. Words are delimited by non-quoted shell metacharacters. shell-backward-word (M-C-b) Move back to the start of the current or previous word. Words are delimited by non-quoted shell metacharacters.\n\nprevious-screen-line () Attempt to move point to the same physical screen column on the previous physical screen line. This will not have the desired effect if the current Readline line does not take up more than one physical line or if point is not greater than the length of the prompt plus the screen width. next-screen-line () Attempt to move point to the same physical screen column on the next physical screen line. This will not have the desired effect if the current Readline line does not take up more than one physical line or if the length of the current Readline line is not greater than the length of the prompt plus the screen width. clear-display (M-C-l) Clear the screen and, if possible, the terminal’s scrollback buffer, then redraw the current line, leaving the current line at the top of the screen. clear-screen (C-l) Clear the screen, then redraw the current line, leaving the current line at the top of the screen. If given a numeric argument, this refreshes the current line without clearing the screen. redraw-current-line () Refresh the current line. By default, this is unbound. |
| chapter_titleCommand Line Editingsection_titleCommands For Manipulating The Historynum_wordsnum_charstextaccept-line (Newline or Return) Accept the line regardless of where the cursor is. If this line is non-empty, add it to the history list according to the setting of the HISTCONTROL and HISTIGNORE variables. If this line is a modified history line, then restore the history line to its original state. previous-history (C-p) Move ‘back’ through the history list, fetching the previous command. This may also be bound to the up arrow key on some keyboards. next-history (C-n) Move ‘forward’ through the history list, fetching the next command. This may also be bound to the down arrow key on some keyboards. beginning-of-history (M-<) Move to the first line in the history. end-of-history (M->) Move to the end of the input history, i.e., the line currently being entered. reverse-search-history (C-r) Search backward starting at the current line and moving ‘up’ through the history as necessary. This is an incremental search. This command sets the region to the matched text and activates the region.\n\nforward-search-history (C-s) Search forward starting at the current line and moving ‘down’ through the history as necessary. This is an incremental search. This command sets the region to the matched text and activates the region. non-incremental-reverse-search-history (M-p) Search backward starting at the current line and moving ‘up’ through the history as necessary using a non-incremental search for a string supplied by the user. The search string may match anywhere in a history line. non-incremental-forward-search-history (M-n) Search forward starting at the current line and moving ‘down’ through the history as necessary using a non-incremental search for a string supplied by the user. The search string may match anywhere in a history line. history-search-backward () Search backward through the history for the string of characters between the start of the current line and the point. The search string must match at the beginning of a history line. This is a non-incremental search. By default, this command is unbound, but may be bound to the Page Down key on some keyboards. history-search-forward () Search forward through the history for the string of characters between the start of the current line and the point. The search string must match at the beginning of a history line. This is a non-incremental search. By default, this command is unbound, but may be bound to the Page Up key on some keyboards. history-substring-search-backward () Search backward through the history for the string of characters between the start of the current line and the point. The search string may match anywhere in a history line. This is a non-incremental search. By default, this command is unbound. history-substring-search-forward () Search forward through the history for the string of characters between the start of the current line and the point. The search string may match anywhere in a history line. This is a non-incremental search. By default, this command is unbound. yank-nth-arg (M-C-y) Insert the first argument to the previous command (usually the second word on the previous line) at point. With an argument n, insert the nth word from the previous command (the words in the previous command begin with word 0). A negative argument inserts the nth word from the end of the previous command. Once the argument n is computed, this uses the history expansion facilities to extract the nth word, as if the ‘!n’ history expansion had been specified. yank-last-arg (M-. or M-_) Insert last argument to the previous command (the last word of the previous history entry). With a numeric argument, behave exactly like yank-nth-arg.\n\nSuccessive calls to yank-last-arg move back through the history list, inserting the last word (or the word specified by the argument to the first call) of each line in turn. Any numeric argument supplied to these successive calls determines the direction to move through the history. A negative argument switches the direction through the history (back or forward). This uses the history expansion facilities to extract the last word, as if the ‘!$’ history expansion had been specified. operate-and-get-next (C-o) Accept the current line for return to the calling application as if a newline had been entered, and fetch the next line relative to the current line from the history\nfor editing. A numeric argument, if supplied, specifies the history entry to use\ninstead of the current line. fetch-history () With a numeric argument, fetch that entry from the history list and make it the current line. Without an argument, move back to the first entry in the history list. |
| chapter_titleCommand Line Editingsection_titleCommands For Changing Textnum_wordsnum_charstextend-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 characters 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 the same character as the tty eof character, as C-d commonly is, see above for the effects. This may also be bound to the Delete key on some keyboards. backward-delete-char (Rubout) Delete the character behind the cursor. A numeric argument means to kill the characters, saving them on the kill ring, instead of deleting them. forward-backward-delete-char () Delete the character under the cursor, unless the cursor is at the end of the line, in which case the character behind the cursor is deleted. By default, this is not bound to a key. quoted-insert (C-q or C-v) Add the next character typed to the line verbatim. This is how to insert key sequences like C-q, for example. self-insert (a, b, A, 1,!,...) Insert the character typed. bracketed-paste-begin () This function is intended to be bound to the \ escape sequence sent by some terminals, and such a binding is assigned by default. It allows Readline to insert the pasted text as a single unit without treating each character as if it had been read from the keyboard. The characters are inserted\n\nas if each one was bound to self-insert instead of executing any editing commands. Bracketed paste sets the region (the characters between point and the mark) to the inserted text. It sets the active region. transpose-chars (C-t) Drag the character before the cursor forward over the character at the cursor, moving the cursor forward as well. If the insertion point is at the end of the line, then this transposes the last two characters of the line. Negative arguments have no effect. transpose-words (M-t) Drag the word before point past the word after point, moving point past that word as well. If the insertion point is at the end of the line, this transposes the last two words on the line. shell-transpose-words (M-C-t) Drag the word before point past the word after point, moving point past that word as well. If the insertion point is at the end of the line, this transposes the last two words on the line. Word boundaries are the same as shell-forwardword and shell-backward-word. upcase-word (M-u) Uppercase the current (or following) word. With a negative argument, uppercase the previous word, but do not move the cursor. downcase-word (M-l) Lowercase the current (or following) word. With a negative argument, lowercase the previous word, but do not move the cursor. capitalize-word (M-c) Capitalize the current (or following) word. With a negative argument, capitalize the previous word, but do not move the cursor. overwrite-mode () Toggle overwrite mode. With an explicit positive numeric argument, switches to overwrite mode. With an explicit non-positive numeric argument, switches to insert mode. This command affects only emacs mode; vi mode does overwrite differently. Each call to readline() starts in insert mode. In overwrite mode, characters bound to self-insert replace the text at point rather than pushing the text to the right. Characters bound to backward-delete-char replace the character before point with a space. By default, this command is unbound, but may be bound to the Insert key on some keyboards. |
| chapter_titleCommand Line Editingsection_titleKilling And Yankingnum_wordsnum_charstextkill-line (C-k) Kill the text from point to the end of the current line. With a negative numeric argument, kill backward from the cursor to the beginning of the line.\n\nbackward-kill-line (C-x Rubout) Kill backward from the cursor to the beginning of the current line. With a negative numeric argument, kill forward from the cursor to the end of the line. unix-line-discard (C-u) Kill backward from the cursor to the beginning of the current line. kill-whole-line () Kill all characters on the current line, no matter where point is. By default, this is unbound. kill-word (M-d) Kill from point to the end of the current word, or if between words, to the end of the next word. Word boundaries are the same as forward-word. backward-kill-word (M-DEL) Kill the word behind point. Word boundaries are the same as backward-word. shell-kill-word (M-C-d) Kill from point to the end of the current word, or if between words, to the end of the next word. Word boundaries are the same as shell-forward-word. shell-backward-kill-word () Kill the word behind point. Word boundaries are the same as shell-backwardword. unix-word-rubout (C-w) Kill the word behind point, using white space as a word boundary, saving the killed text on the kill-ring. unix-filename-rubout () Kill the word behind point, using white space and the slash character as the word boundaries, saving the killed text on the kill-ring. delete-horizontal-space () Delete all spaces and tabs around point. By default, this is unbound. kill-region () Kill the text in the current region. By default, this command is unbound. copy-region-as-kill () Copy the text in the region to the kill buffer, so it can be yanked right away. By default, this command is unbound. copy-backward-word () Copy the word before point to the kill buffer. The word boundaries are the same as backward-word. By default, this command is unbound. copy-forward-word () Copy the word following point to the kill buffer. The word boundaries are the same as forward-word. By default, this command is unbound. yank (C-y) Yank the top of the kill ring into the buffer at point.\n\nyank-pop (M-y) Rotate the kill-ring, and yank the new top. You can only do this if the prior command is yank or yank-pop. |
| chapter_titleCommand Line Editingsection_titleSpecifying Numeric Argumentsnum_wordsnum_charstextdigit-argument (M-0, M-1,... M--) Add this digit to the argument already accumulating, or start a new argument. M-- starts a negative argument. universal-argument () This is another way to specify an argument. If this command is followed by one or more digits, optionally with a leading minus sign, those digits define the argument. If the command is followed by digits, executing universal-argument again ends the numeric argument, but is otherwise ignored. As a special case,\nif this command is immediately followed by a character that is neither a digit\nnor minus sign, the argument count for the next command is multiplied by four. The argument count is initially one, so executing this function the first time makes the argument count four, a second time makes the argument count sixteen, and so on. By default, this is not bound to a key. |
| chapter_titleCommand Line Editingsection_titleLetting Readline Type For Younum_wordsnum_charstextcomplete (TAB) Attempt to perform completion on the text before point. The actual completion performed is application-specific. Bash attempts completion by first checking\nfor any programmable completions for the command word, otherwise treating the text as a variable (if\nthe text begins with ‘$’), username (if the text begins with ‘~’), hostname (if the text begins with ‘@’), or command (including aliases, functions, and builtins) in turn. If none of these produces a match, it falls back to filename completion. possible-completions (M-?) List the possible completions of the text before point. When displaying completions, Readline sets the number of columns used for display to the value of completion-display-width, the value of the environment variable COLUMNS, or the screen width, in that order. insert-completions (M-*) Insert all completions of the text before point that would have been generated by possible-completions, separated by a space. menu-complete () Similar to complete, but replaces the word to be completed with a single match from the list of possible completions. Repeatedly executing menu-complete steps through the list of possible completions, inserting each match in turn. At the end of the list of completions, menu-complete rings the bell (subject to the setting of bell-style) and restores the original text. An argument of n moves n positions forward in the list of matches; a negative argument moves backward through the list. This command is intended to be bound to TAB, but is unbound by default.\n\nmenu-complete-backward () Identical to menu-complete, but moves backward through the list of possible completions, as if menu-complete had been given a negative argument. This command is unbound by default. export-completions () Perform completion on the word before point as described above and write the list of possible completions to Readline’s output stream using the following format, writing information on separate lines:\n• the number of matches N;\n• the word being completed;\n• S:E, where S and E are the start and end offsets of the word in the Readline\nline buffer; then\n• each match, one per line\nIf there are no matches, the first line will be “0”, and this command does not print any output after the S:E. If there is only a single match, this prints a single line containing it. If there is more than one match, this prints the common prefix of the matches, which may be empty, on the first line after the S:E, then the matches on subsequent lines. In this case, N will include the first line with the common prefix. The user or application should be able to accommodate the possibility of a blank line. The intent is that the user or application reads N lines after the line containing S:E to obtain the match list. This command is unbound by default. delete-char-or-list () Deletes the character under the cursor if not at the beginning or end of the line (like delete-char). At the end of the line, it behaves identically to possible-completions. This command is unbound by default. complete-filename (M-/) Attempt filename completion on the text before point. possible-filename-completions (C-x /) List the possible completions of the text before point, treating it as a filename. complete-username (M-~) Attempt completion on the text before point, treating it as a username. possible-username-completions (C-x ~) List the possible completions of the text before point, treating it as a username. complete-variable (M-$) Attempt completion on the text before point, treating it as a shell variable. possible-variable-completions (C-x $) List the possible completions of the text before point, treating it as a shell variable. complete-hostname (M-@) Attempt completion on the text before point, treating it as a hostname.\n\npossible-hostname-completions (C-x @) List the possible completions of the text before point, treating it as a hostname. complete-command (M-!) Attempt completion on the text before point, treating it as a command name. Command completion attempts to match the text against aliases, reserved words, shell functions, shell builtins, and finally executable filenames, in that order. possible-command-completions (C-x!) List the possible completions of the text before point, treating it as a command name. dynamic-complete-history (M-TAB) Attempt completion on the text before point, comparing the text against history list entries for possible completion matches. dabbrev-expand () Attempt menu completion on the text before point, comparing the text against lines from the history list for possible completion matches. complete-into-braces (M-{) Perform filename completion and insert the list of possible completions enclosed within braces so the list is available to the shell. |
| chapter_titleCommand Line Editingsection_titleKeyboard Macrosnum_wordsnum_charstextstart-kbd-macro (C-x () Begin saving the characters typed into the current keyboard macro. end-kbd-macro (C-x )) Stop saving the characters typed into the current keyboard macro and save the definition. call-last-kbd-macro (C-x e) Re-execute the last keyboard macro defined, by making the characters in the macro appear as if typed at the keyboard. print-last-kbd-macro () Print the last keyboard macro defined in a format suitable for the inputrc file. |
| chapter_titleCommand Line Editingsection_titleSome Miscellaneous Commandsnum_wordsnum_charstextre-read-init-file (C-x C-r) Read in the contents of the inputrc file, and incorporate any bindings or variable assignments found there. abort (C-g) Abort the current editing command and ring the terminal’s bell (subject to the setting of bell-style).\n\ndo-lowercase-version (M-A, M-B, M-x,...)\nIf the metafied character x is upper case, run the command that is bound to the corresponding metafied lower case character. The behavior is undefined if x is already lower case. prefix-meta (ESC) Metafy the next character typed. Typing ‘ESC f’ is equivalent to typing M-f. undo (C-_ or C-x C-u) Incremental undo, separately remembered for each line. revert-line (M-r) Undo all changes made to this line. This is like executing the undo command enough times to get back to the initial state. tilde-expand (M-&) Perform tilde expansion on the current word. set-mark (C-@) Set the mark to the point. If a numeric argument is supplied, set the mark to that position. exchange-point-and-mark (C-x C-x) Swap the point with the mark. Set the current cursor position to the saved position, then set the mark to the old cursor position. character-search (C-]) Read a character and move point to the next occurrence of that character. A negative argument searches for previous occurrences. character-search-backward (M-C-]) Read a character and move point to the previous occurrence of that character. A negative argument searches for subsequent occurrences. skip-csi-sequence () Read enough characters to consume a multi-key sequence such as those defined\nfor keys like Home and End. CSI sequences begin with a Control Sequence Indicator (CSI), usually ESC [. If this sequence is bound to \, keys producing\nCSI sequences have 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, insert the value of the comment-begin variable at the beginning of the current line. If a numeric argument is supplied, this command acts as a toggle: if the characters at the beginning of the line do not match the value of comment-begin, insert the value; otherwise delete the characters in comment-begin from the beginning of the line. In either case, the line is accepted as if a newline had been typed. The default value of comment-begin causes this command to make the current line a shell comment. If a numeric argument causes the comment character to be removed, the line will be executed by the shell.\n\ndump-functions () Print all of the functions and their key bindings to the Readline output stream. If a numeric argument is supplied, the output is formatted in such a way that it can be made part of an inputrc file. This command is unbound by default. dump-variables () Print all of the settable variables and their values to the Readline output stream. If a numeric argument is supplied, the output is formatted in such a way that it can be made part of an inputrc file. This command is unbound by default. dump-macros () Print all of the Readline key sequences bound to macros and the strings they output to the Readline output stream. If a numeric argument is supplied, the output is formatted in such a way that it can be made part of an inputrc file. This command is unbound by default. execute-named-command (M-x) Read a bindable Readline command name from the input and execute the function to which it’s bound, as if the key sequence to which it was bound appeared in the input. If this function is supplied with a numeric argument, it passes that argument to the function it executes. spell-correct-word (C-x s) Perform spelling correction on the current word, treating it as a directory or filename, in the same way as the cdspell shell option. Word boundaries are the same as those used by shell-forward-word. glob-complete-word (M-g) Treat the word before point as a pattern for pathname expansion, with an asterisk implicitly appended, then use the pattern to generate a list of matching file names for possible completions. glob-expand-word (C-x *) Treat the word before point as a pattern for pathname expansion, and insert the list of matching file names, replacing the word. If a numeric argument is supplied, append a ‘*’ before pathname expansion. glob-list-expansions (C-x g) Display the list of expansions that would have been generated by glob-expandword, and redisplay the line. If a numeric argument is supplied, append a ‘*’ before pathname expansion. shell-expand-line (M-C-e) Expand the line by performing shell word expansions. This performs alias and history expansion, $’string’ and $\ quoting, tilde expansion, parameter and variable expansion, arithmetic expansion, command and process substitution, word splitting, and quote removal. An explicit argument suppresses command and process substitution. history-expand-line (M-^) Perform history expansion on the current line.\n\nmagic-space () Perform history expansion on the current line and insert a space. alias-expand-line () Perform alias expansion on the current line. history-and-alias-expand-line () Perform history and alias expansion on the current line. insert-last-argument (M-. or M-_) A synonym for yank-last-arg. edit-and-execute-command (C-x C-e) Invoke an editor on the current command line, and execute the result as shell commands. Bash attempts to invoke $VISUAL, $EDITOR, and emacs as the editor, in that order. display-shell-version (C-x C-v) Display version information about the current instance of Bash. |
| chapter_titleCommand Line Editingsection_titleReadline vi Modenum_wordsnum_charstextWhile the Readline library does not have a full set of vi editing functions, it does contain enough to allow simple editing of the line. The Readline vi mode behaves as specified in the sh description in the posix standard. You can use the ‘set -o emacs’ and ‘set -o vi’ commands to switch interactively between emacs and vi editing modes, The Readline default is emacs mode. When you enter a line in vi mode, you are already placed in ‘insertion’ mode, as if you had typed an ‘i’. Pressing ESC switches you into ‘command’ mode, where you can edit the text of the line with the standard vi movement keys, move to previous history lines with ‘k’ and subsequent lines with ‘j’, and so forth. |
| chapter_titleCommand Line Editingsection_titleProgrammable Completionnum_wordsnum_charstextWhen the user attempts word completion for a command or an argument to a command\nfor which a completion specification (a compspec) has been defined using the complete\nbuiltin, Readline invokes the programmable completion facilities. First, Bash identifies the command name. If a compspec has been defined for that command, the compspec is used to generate the list of possible completions for the word. If the command word is the empty string (completion attempted at the beginning of an empty line), Bash uses any compspec defined with the -E option to complete. The -I option to complete indicates that the command word is the first non-assignment word on the line, or after a command delimiter such as ‘;’ or ‘|’. This usually indicates command name completion. If the command word is a full pathname, Bash searches for a compspec for the full pathname first. If there is no compspec for the full pathname, Bash attempts to find a\n\ncompspec for the portion following the final slash. If those searches do not result in a compspec, or if there is no compspec for the command word, Bash uses any compspec defined with the -D option to complete as the default. If there is no default compspec, Bash performs alias expansion on the command word as a final resort, and attempts to find a compspec for the command word resulting from any successful expansion. If a compspec is not found, Bash performs its default completion described above. Otherwise, once a compspec has been found, Bash uses it to generate the list of matching words. First, Bash performs the actions specified by the compspec. This only returns matches which are prefixes of the word being completed. When the -f or -d option is used for filename or directory name completion, Bash uses shell the variable FIGNORE to filter the matches. Next, programmable completion generates matches specified by a pathname expansion pattern supplied as an argument to the -G option. The words generated by the pattern need not match the word being completed. Bash uses the FIGNORE variable to filter the matches, but does not use the GLOBIGNORE shell variable. Next, completion considers the string specified as the argument to the -W option. The string is first split using the characters in the IFS special variable as delimiters. This honors shell quoting within the string, in order to provide a mechanism for the words to contain shell metacharacters or characters in the value of IFS. Each word is then expanded using brace expansion, tilde expansion, parameter and variable expansion, command substitution, and arithmetic expansion, as described above. The results are split using the rules described above. The results of the expansion are prefix-matched against the word being completed, and the matching words become possible completions. After these matches have been generated, Bash executes any shell function or command specified with the -F and -C options. When the command or function is invoked, Bash assigns values to the COMP_LINE, COMP_POINT, COMP_KEY, and COMP_TYPE variables as described above. If a shell function is being invoked, Bash also sets the COMP_WORDS and COMP_CWORD variables. When the function or command is invoked, the first argument ($1) is the name of the command whose arguments 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 the current command line. There is no filtering of the generated completions against the word being completed; the function or command has complete freedom in generating the matches and they do not need to match a prefix of the word. Any function specified with -F is invoked first. The function may use any of the shell facilities, including the compgen and compopt builtins described below, to generate the matches. It must put the possible completions in the COMPREPLY array variable, one per array element. Next, any command specified with the -C option is invoked in an environment equivalent to command substitution. It should print a list of completions, one per line, to the standard output. Backslash will escape a newline, if necessary. These are added to the set of possible completions.\n\nAfter generating all of the possible completions, Bash applies any filter specified with the -X option to the completions in the list. The filter is a pattern as used for pathname expansion; a ‘&’ in the pattern is replaced with the text of the word being completed. A literal ‘&’ may be escaped with a backslash; the backslash is removed before attempting a match. Any completion that matches the pattern is removed from the list. A leading ‘!’ negates the pattern; in this case Bash removes any completion that does not match the pattern. If the nocasematch shell option is enabled (see the description of shopt in Section 4.3.2 [The Shopt Builtin], page 78), Bash performs the match without regard to the\ncase of alphabetic characters.\nFinally, programmable completion adds any prefix and suffix specified with the -P and -S options, respectively, to each completion, and returns the result to Readline 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 was defined, Bash attempts directory name completion. If the -o plusdirs option was supplied to complete when the compspec was defined, Bash attempts directory name completion and adds any matches to the set of possible completions. By default, if a compspec is found, whatever it generates is returned to the completion code as the full set of possible completions. The default Bash completions and the Readline default of filename completion are disabled. If the -o bashdefault option was supplied to complete when the compspec was defined, and the compspec generates no matches, Bash attempts its default completions. If the compspec and, if attempted, the default Bash completions generate no matches, and the -o default option was supplied to complete when the compspec was defined, programmable completion performs Readline’s default completion. The options supplied to complete and compopt can control how Readline treats the completions. For instance, the -o fullquote option tells Readline to quote the matches as if they were filenames. See the description of complete for details. When a compspec indicates that it wants directory name completion, the programmable completion functions force Readline to append a slash to completed names which are symbolic links to directories, subject to the value of the mark-directories Readline variable, regardless of the setting of the mark-symlinked-directories Readline variable. There is some support for dynamically modifying completions. This is most useful when used in combination with a default completion specified with -D. It’s possible for shell functions executed as completion functions to indicate that completion should be retried by returning an exit status of 124. If a shell function returns 124, and changes the compspec associated with the command on which completion is being attempted (supplied as the first argument when the function is executed), programmable completion restarts from the beginning, with an attempt to find a new compspec for that command. This can be used to build a set of completions dynamically as completion is attempted, rather than loading them all at once.\n\nFor instance, assuming that there is a library of compspecs, each kept in a file corresponding to the name of the command, the following default completion function would load completions dynamically: _completion_loader() { . \ >/dev/null 2>&1 && return 124 } complete -D -F _completion_loader -o bashdefault -o default |
| chapter_titleCommand Line Editingsection_titleProgrammable Completion Builtinsnum_wordsnum_charstextThree builtin commands are available to manipulate the programmable completion facilities: one to specify how the arguments to a particular command are to be completed, and two to modify the completion as it is happening. compgen compgen [-V varname] [option] [word] Generate possible completion matches for word according to the options, which may be any option accepted by the complete builtin with the exceptions of -p, -r, -D, -E, and -I, and write the matches to the standard output. If the -V option is supplied, compgen stores the generated completions into the indexed array variable varname instead of writing them to the standard output. When using the -F or -C options, the various shell variables set by the programmable completion facilities, while available, will not have useful values. The matches will be generated in the same way as if the programmable completion code had generated them directly from a completion specification with the same flags. If word is specified, only those completions matching word will be displayed or stored. The return value is true unless an invalid option is supplied, or no matches were generated. complete complete [-abcdefgjksuv] [-o comp-option] [-DEI] [-A action] [-G globpat] [-W wordlist] [-F function] [-C command] [-X filterpat] [-P prefix] [-S suffix] name [name...] complete -pr [-DEI] [name...] Specify how arguments to each name should be completed. If the -p option is supplied, or if no options or names are supplied, print existing completion specifications in a way that allows them to be reused as input. The -r option removes a completion specification for each name, or, if no names are supplied, all completion specifications. The -D option indicates that other supplied options and actions should apply to the “default” command completion; that is, completion attempted on a command for which no completion has previously been defined. The -E option indicates that other supplied options and actions should apply to “empty” command completion; that is, completion attempted on a blank line. The -I option\n\nindicates that other supplied options and actions should apply to completion on the initial non-assignment word on the line, or after a command delimiter such as ‘;’ or ‘|’, which is usually command name completion. If multiple options are supplied, the -D option takes precedence over -E, and both take precedence over -I. If any of -D, -E, or -I are supplied, any other name arguments are ignored; these completions only apply to the case specified by the option. The process of applying these completion specifications when word completion is attempted is described above. Other options, if specified, have the following meanings. The arguments to the -G, -W, and -X options (and, if necessary, the -P and -S options) should be quoted to protect them from expansion before the complete builtin is invoked. -o comp-option The comp-option controls several aspects of the compspec’s behavior beyond the simple generation of completions. comp-option may be one of: bashdefault Perform the rest of the default Bash completions if the compspec generates no matches. default\n\nUse Readline’s default filename completion if the compspec generates no matches.\n\ndirnames\n\nPerform directory name completion if the compspec generates no matches.\n\nfilenames Tell Readline that the compspec generates filenames, so it can perform any filename-specific processing (such as adding a slash to directory names, quoting special characters, or suppressing trailing spaces). This option is intended to be used with shell functions specified with -F. fullquote Tell Readline to quote all the completed words even if they are not filenames. noquote\n\nTell Readline not to quote the completed words if they are filenames (quoting filenames is the default).\n\nnosort\n\nTell Readline not to sort the list of possible completions alphabetically.\n\nnospace\n\nTell Readline not to append a space (the default) to words completed at the end of the line.\n\nplusdirs\n\nAfter generating any matches defined by the compspec, attempt directory name completion and add any matches to the results of the other actions.\n\n-A action The action may be one of the following to generate a list of possible completions: alias\n\nAlias names. May also be specified as -a.\n\narrayvar\n\nArray variable names.\n\nbinding\n\nReadline key binding names.\n\nbuiltin\n\nNames of shell builtin commands. May also be specified as -b.\n\ncommand\n\nCommand names. May also be specified as -c.\n\ndirectory Directory names. May also be specified as -d. disabled\n\nNames of disabled shell builtins.\n\nenabled\n\nNames of enabled shell builtins.\n\nexport\n\nNames of exported shell variables. May also be specified as -e.\n\nfile\n\nFile and directory names, similar to Readline’s filename completion. May also be specified as -f.\n\nfunction\n\nNames of shell functions.\n\ngroup\n\nGroup names. May also be specified as -g.\n\nhelptopic Help topics as accepted by the help builtin. hostname\n\nHostnames, as taken from the file specified by the HOSTFILE shell variable.\n\njob\n\nJob names, if job control is active. May also be specified as -j.\n\nkeyword\n\nShell reserved words. May also be specified as -k.\n\nrunning\n\nNames of running jobs, if job control is active.\n\nservice\n\nService names. May also be specified as -s.\n\nsetopt\n\nValid arguments for the -o option to the set builtin .\n\nshopt\n\nShell option names as accepted by the shopt builtin .\n\nsignal\n\nSignal names.\n\nstopped\n\nNames of stopped jobs, if job control is active.\n\nuser\n\nUser names. May also be specified as -u.\n\nvariable\n\nNames of all shell variables. May also be specified as -v.\n\n-C command command is executed in a subshell environment, and its output is used as the possible completions. Arguments are passed as with the -F option. -F function The shell function function is executed in the current shell environment. When it is executed, the first argument ($1) is the name of the command whose arguments 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, as described above. When function finishes, programmable completion retrieves the possible completions from the value of the COMPREPLY array variable. -G globpat Expand the filename expansion pattern globpat to generate the possible completions. -P prefix Add prefix to the beginning of each possible completion after all other options have been applied. -S suffix Append suffix to each possible completion after all other options have been applied. -W wordlist Split the wordlist using the characters in the IFS special variable as delimiters, and expand each resulting word. Shell quoting is honored within wordlist in order to provide a mechanism for the words to contain shell metacharacters or characters in the value of IFS. The possible completions are the members of the resultant list which match a prefix of the word being completed. -X filterpat filterpat is a pattern as used for filename expansion. It is applied to the list of possible completions generated by the preceding options and arguments, and each completion matching filterpat is removed from the list. A leading ‘!’ in filterpat negates the pattern; in this\ncase, any completion not matching filterpat is removed.\nThe return value is true unless an invalid option is supplied, an option other than -p, -r, -D, -E, or -I is supplied without a name argument, an attempt is made to remove a completion specification for a name for which no specification exists, or an error occurs adding a completion specification. compopt compopt [-o option] [-DEI] [+o option] [name]\n\nModify completion options for each name according to the options, or for the currently-executing completion if no names are supplied. If no options are given, display the completion options for each name or the current completion. The possible values of option are those valid for the complete builtin described above. The -D option indicates that other supplied options should apply to the “default” command completion; the -E option indicates that other supplied options should apply to “empty” command completion; and the -I option indicates that other supplied options should apply to completion on the initial word on the line. These are determined in the same way as the complete builtin. If multiple options are supplied, the -D option takes precedence over -E, and both take precedence over -I The return value is true unless an invalid option is supplied, an attempt is made to modify the options for a name for which no completion specification exists, or an output error occurs. |
| chapter_titleCommand Line Editingsection_titleA Programmable Completion Examplenum_wordsnum_charstextThe most common way to obtain additional completion functionality beyond the default actions complete and compgen provide is to use a shell function and bind it to a particular command using complete -F. The following function provides completions for the cd builtin. It is a reasonably good example of what shell functions must do when used for completion. This function uses the word passed as $2 to determine the directory name to complete. You can also use the COMP_WORDS array variable; the current word is indexed by the COMP_CWORD variable. The function relies on the complete and compgen builtins to do much of the work, adding only the things that the Bash cd does beyond accepting basic directory names: tilde expansion, searching directories in $CDPATH, which is described above, and basic support\nfor the cdable_vars shell option. _comp_\ncd modifies the value of IFS so that it contains only a newline to accommodate file names containing spaces and tabs – compgen prints the possible completions it generates one per line. Possible completions go into the COMPREPLY array variable, one completion per array element. The programmable completion system retrieves the completions from there when the function returns.\n# A completion function for the cd builtin\n# based on the cd completion function from the bash_completion package\n_comp_cd() { local IFS=$’ \\t\\n’\n# normalize IFS\nlocal cur _skipdot _cdpath local i j k\n# Tilde expansion, which also expands tilde to full pathname\ncase \ in\n\nChapter 8: Command Line Editing\n\n\\~*) *)\nesac\n\neval cur=\;;\ncur=$2;;\n\n# no cdpath or absolute pathname -- straight directory completion\nif [[ -z \ ]] || [[ \ == @(./*|../*|/*) ]]; then\n# compgen prints paths one per line; could also use while loop\nIFS=$’\\n’\nCOMPREPLY=( $(compgen -d -- \) )\nIFS=$’ \\t\\n’\n# CDPATH+directories in the current directory if not in CDPATH\nelse\nIFS=$’\\n’\n_skipdot=false\n# preprocess CDPATH to convert null directory names to.\n_cdpath=${CDPATH/#:/.:}\n_cdpath=${_cdpath//::/:.:}\n_cdpath=${_cdpath/%:/:.}\nfor i in ${_cdpath//:/$’\\n’}; do\nif [[ $i -ef. ]]; then _skipdot=true; fi\nk=\\nfor j in $( compgen -d -- \ ); do\nCOMPREPLY[k++]=${j#$i/}\n# cut off directory\ndone\ndone\n$_skipdot || COMPREPLY+=( $(compgen -d -- \) )\nIFS=$’ \\t\\n’\nfi\n# variable names if appropriate shell option set and no completions\nif shopt -q cdable_vars && [[ ${#COMPREPLY[@]} -eq 0 ]]; then\nCOMPREPLY=( $(compgen -v -- \) )\nfi\nreturn 0 } We install the completion function using the -F option to complete:\n# Tell readline to quote appropriate and append slashes to directories;\n# use the bash default completion for other arguments\ncomplete -o filenames -o nospace -o bashdefault -F _comp_cd cd Since we’d like Bash and Readline to take care of some of the other details for us, we use several other options to tell Bash and Readline what to do. The -o filenames option tells Readline that the possible completions should be treated as filenames, and quoted appropriately. That option will also cause Readline to append a slash to filenames it can determine are directories (which is why we might want to extend _comp_cd to append a slash if we’re using directories found via CDPATH: Readline can’t tell those completions are\n\ndirectories). The -o nospace option tells Readline to not append a space character to the directory name, in case we want to append to it. The -o bashdefault option brings in the rest of the “Bash default” completions – possible completions that Bash adds to the default Readline set. These include things like command name completion, variable completion for words beginning with ‘$’ or ‘${’, completions containing pathname expansion patterns, and so on. Once installed using complete, _comp_cd will be called every time we attempt word completion for a cd command. Many more examples – an extensive collection of completions for most of the common GNU, Unix, and Linux commands – are available as part of the bash completion project. This is installed by default on many GNU/Linux distributions. Originally written by Ian Macdonald, the project now lives at https: / / github. com / scop / bash-completion /. There are ports for other systems such as Solaris and Mac OS X. An older version of the bash completion package is distributed with bash in the examples/complete subdirectory. |
| chapter_titleUsing History Interactivelysection_titleUsing History Interactivelynum_wordsnum_charstextThis chapter describes how to use the gnu History Library interactively, from a user’s standpoint. It should be considered a user’s guide. For information on using the gnu History Library in other programs, see the gnu Readline Library Manual. |
| chapter_titleUsing History Interactivelysection_titleBash History Facilitiesnum_wordsnum_charstextWhen the -o history option to the set builtin is enabled, the shell provides access to the command history, the list of commands previously typed. The value of the HISTSIZE shell variable is used as the number of commands to save in a history list: the shell saves the text of the last $HISTSIZE commands (default 500). The shell stores each command in the history list prior to parameter and variable expansion but after history expansion is performed, subject to the values of the shell variables HISTIGNORE and HISTCONTROL. When the shell starts up, Bash initializes the history list by reading history entries from the file named by the HISTFILE variable (default ~/.bash_history). This is referred to as the history file. The history file is truncated, if necessary, to contain no more than the number of history entries specified by the value of the HISTFILESIZE variable. If HISTFILESIZE is unset, or set to null, a non-numeric value, or a numeric value less than zero, the history file is not truncated. When the history file is read, lines beginning with the history comment character followed immediately by a digit are interpreted as timestamps for the following history entry. These timestamps are optionally displayed depending on the value of the HISTTIMEFORMAT variable . When present, history timestamps delimit history entries, making multi-line entries possible. When a shell with history enabled exits, Bash copies the last $HISTSIZE entries from the history list to the file named by $HISTFILE. If the histappend shell option is set, Bash appends the entries to the history file, otherwise it overwrites the history file. If HISTFILE is unset or null, or if the history file is unwritable, the history is not saved. After saving the history, Bash truncates the history file to contain no more than $HISTFILESIZE lines as described above. If the HISTTIMEFORMAT variable is set, the shell writes the timestamp information associated with each history entry to the history file, marked with the history comment character, so timestamps are preserved across shell sessions. When the history file is read, lines beginning with the history comment character followed immediately by a digit are interpreted as timestamps for the following history entry. As above, when using HISTTIMEFORMAT, the timestamps delimit multi-line history entries. The fc builtin command will list or edit and re-execute a portion of the history list. The history builtin can display or modify the history list and manipulate the history file. When using command-line editing, search commands are available in each editing mode that provide access to the history list. The shell allows control over which commands are saved on the history list. The HISTCONTROL and HISTIGNORE variables are used to save only a subset of the commands entered. If the cmdhist shell option is enabled, the shell attempts to save each line of a multi-line command in the same history entry, adding semicolons where necessary to\n\npreserve syntactic correctness. The lithist shell option modifies cmdhist by saving the command with embedded newlines instead of semicolons. The shopt builtin is used to set these options. |
| chapter_titleUsing History Interactivelysection_titleBash History Builtinsnum_wordsnum_charstextBash provides two builtin commands which manipulate the history list and history file. fc fc [-e ename] [-lnr] [first] [last] fc -s [pat=rep] [command] The first form selects a range of commands from first to last from the history list and displays or edits and re-executes them. Both first and last may be specified as a string (to locate the most recent command beginning with that string) or as a number (an index into the history list, where a negative number is used as an offset from the current command number). When listing, a first or last of 0 is equivalent to -1 and -0 is equivalent to the current command (usually the fc command); otherwise 0 is equivalent to -1 and -0 is invalid. If last is not specified, it is set to the current command for listing and to first otherwise. If first is not specified, it is set to the previous command for editing and −16 for listing. If the -l flag is supplied, the commands are listed on standard output. The -n flag suppresses the command numbers when listing. The -r flag reverses the order of the listing. Otherwise, fc invokes the editor named by ename on a file containing those commands. If ename is not supplied, fc uses the value of the following variable expansion: ${FCEDIT:-${EDITOR:-vi}}. This says to use the value of the FCEDIT variable if set, or the value of the EDITOR variable if that is set, or vi if neither is set. When editing is complete, fc reads the file of edited commands and echoes and executes them. In the second form, fc re-executes command after replacing each instance of pat in the selected command with rep. command is interpreted the same as first above. A useful alias to use with the fc command 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 zero unless an invalid option is encountered or first or last specify history lines out of range. When editing and re-executing a file of commands, the return value is the value of the last command executed or failure if an error occurs with the temporary file. If the second form is used, the return status is that of the re-executed command, unless command does not specify a valid history entry, in which case fc returns a non-zero status. history history [n]\n\nhistory -c history -d offset history -d start-end history [-anrw] [filename] history -ps arg With no options, display the history list with numbers. Entries prefixed with a ‘*’ have been modified. An argument of n lists only the last n entries. If the shell variable HISTTIMEFORMAT is set and not null, it is used as a format string for strftime(3) to display the time stamp associated with each displayed history entry. If history uses HISTTIMEFORMAT, it does not print an intervening space between the formatted time stamp and the history entry. Options, if supplied, have the following meanings: -c\n\nClear the history list. This may be combined with the other options to replace the history list.\n\n-d offset Delete the history entry at position offset. If offset is positive, it should be specified as it appears when the history is displayed. If offset is negative, it is interpreted as relative to one greater than the last history position, so negative indices count back from the end of the history, and an index of ‘-1’ refers to the current history -d command. -d start-end Delete the range of history entries between positions start and end, inclusive. Positive and negative values for start and end are interpreted as described above. -a\n\nAppend the \ history lines to the history file. These are history lines entered since the beginning of the current Bash session, but not already appended to the history file.\n\n-n\n\nRead the history lines not already read from the history file and add them to the current history list. These are lines appended to the history file since the beginning of the current Bash session.\n\n-r\n\nRead the history file and append its contents to the history list.\n\n-w\n\nWrite the current history list to the history file, overwriting the history file.\n\n-p\n\nPerform history substitution on the args and display the result on the standard output, without storing the results in the history list.\n\n-s\n\nAdd the args to the end of the history list as a single entry. The last command in the history list is removed before adding the args.\n\nIf a filename argument is supplied with any of the -w, -r, -a, or -n options, Bash uses filename as the history file. If not, it uses the value of the HISTFILE variable. If HISTFILE is unset or null, these options have no effect. If the HISTTIMEFORMAT variable is set, history writes the time stamp information associated with each history entry to the history file, marked with the\n\nhistory comment character as described above. When the history file is read, lines beginning with the history comment character followed immediately by a digit are interpreted as timestamps for the following history entry. The return value is 0 unless an invalid option is encountered, an error occurs\nwhile reading or writing the history file, an invalid offset or range is supplied\nas an argument to -d, or the history expansion supplied as an argument to -p fails. |
| chapter_titleUsing History Interactivelysection_titleHistory Expansionnum_wordsnum_charstextThe shell provides a history expansion feature that is similar to the history expansion provided by csh (also referred to as history substitution where appropriate). This section describes the syntax used to manipulate the history information. History expansion is enabled by default for interactive shells, and can be disabled using the +H option to the set builtin command. Non-interactive shells do not perform history expansion by default, but it can be enabled with set -H. History expansions introduce words from the history list into the input stream, making it easy to repeat commands, insert the arguments to a previous command into the current input line, or fix errors in previous commands quickly. History expansion is performed immediately after a complete line is read, before the shell breaks it into words, and is performed on each line individually. Bash attempts to inform the history expansion functions about quoting still in effect from previous lines. History expansion takes place in two parts. The first is to determine which entry from the history list should be used during substitution. The second is to select portions of that entry to include into the current one. The entry selected from the history is called the event, and the portions of that entry that are acted upon are words. Various modifiers are available to manipulate the selected words. The entry is split into words in the same fashion that Bash does when reading input, so that several words surrounded by quotes are considered one word. The event designator selects the event, the optional word designator selects words from the event, and various optional modifiers are available to manipulate the selected words. History expansions are introduced by the appearance of the history expansion character, which is ‘!’ by default. History expansions may appear anywhere in the input, but do not nest. History expansion implements shell-like quoting conventions: a backslash can be used to remove the special handling for the next character; single quotes enclose verbatim sequences of characters, and can be used to inhibit history expansion; and characters enclosed within double quotes may be subject to history expansion, since backslash can escape the history expansion character, but single quotes may not, since they are not treated specially within double quotes. When using the shell, only ‘\\’ and ‘’’ may be used to escape the history expansion character, but the history expansion character is also treated as quoted if it immediately precedes the closing double quote in a double-quoted string.\n\nSeveral characters inhibit history expansion if found immediately following the history expansion character, even if it is unquoted: space, tab, newline, carriage return, ‘=’, and the other shell metacharacters. There is a special abbreviation for substitution, active when the quick substitution character (described above under histchars) is the first character on the line. It selects the previous history list entry, using an event designator equivalent to!!, and substitutes one string for another in that entry. It is described below. This is the only history expansion that does not begin with the history expansion character. Several shell options settable with the shopt builtin modify history expansion behavior If the histverify shell option is enabled, and Readline is being used, history substitutions are not immediately passed to the shell parser. Instead, the expanded line is reloaded into the Readline editing buffer for further modification. If Readline is being used, and the histreedit shell option is enabled, a failed history expansion is reloaded into the Readline editing buffer for correction. The -p option to the history builtin command shows what a history expansion will do before using it. The -s option to the history builtin may be used to add commands to the end of the history list without actually executing them, so that they are available for subsequent recall. This is most useful in conjunction with Readline. The shell allows control of the various characters used by the history expansion mechanism with the histchars variable, as explained above. The shell uses the history comment character to mark history timestamps when writing the history file. |
| chapter_titleUsing History Interactivelysection_titleEvent Designatorsnum_wordsnum_charstextAn event designator is a reference to an entry in the history list. The event designator consists of the portion of the word beginning with the history expansion character, and ending with the word designator if one is present, or the end of the word. Unless the reference is absolute, events are relative to the current position in the history list. !\n\nStart a history substitution, except when followed by a space, tab, the end of the line, ‘=’, or the rest of the shell metacharacters defined above.\n\n!n\n\nRefer to history list entry n.\n\n!-n\n\nRefer to the history entry minus n.\n\n!!\n\nRefer to the previous entry. This is a synonym for ‘!-1’.\n\n!string\n\nRefer to the most recent command preceding the current position in the history list starting with string.\n\n!?string[?] Refer to the most recent command preceding the current position in the history list containing string. The trailing ‘?’ may be omitted if the string is followed immediately by a newline. If string is missing, this uses the string from the most recent search; it is an error if there is no previous search string.\n\n^string1^string2^ Quick Substitution. Repeat the last command, replacing string1 with string2. Equivalent to!!:s^string1^string2^. The entire command line typed so far.\n\n!# |
| chapter_titleUsing History Interactivelysection_titleWord Designatorsnum_wordsnum_charstextWord designators are used to select desired words from the event. They are optional; if the word designator isn’t supplied, the history expansion uses the entire event. A ‘:’ separates the event specification from the word designator. It may be omitted if the word designator begins with a ‘^’, ‘$’, ‘*’, ‘-’, or ‘%’. Words are numbered from the beginning of the line, with the first word being denoted by 0 (zero). That first word is usually the command word, and the arguments begin with the second word. Words are inserted into the current line separated by single spaces. For example, !!\n\ndesignates the preceding command. When you type this, the preceding command is repeated in toto.\n\n!!:$\n\ndesignates the last word of the preceding command. This may be shortened to !$.\n\n!fi:2\n\ndesignates the second argument of the most recent command starting with the letters fi.\n\nHere are the word designators: 0 (zero)\n\nThe 0th word. For the shell, and many other, applications, this is the command word.\n\nn\n\nThe nth word.\n\n^\n\nThe first argument: word 1.\n\n$\n\nThe last word. This is usually the last argument, but expands to the zeroth word if there is only one word in the line.\n\n%\n\nThe first word matched by the most recent ‘?string?’ search, if the search string begins with a character that is part of a word. By default, searches begin at the end of each line and proceed to the beginning, so the first word matched is the one closest to the end of the line.\n\nx-y\n\nA range of words; ‘-y’ abbreviates ‘0-y’.\n\n*\n\nAll of the words, except the 0th. This is a synonym for ‘1-$’. It is not an error to use ‘*’ if there is just one word in the event; it expands to the empty string in that case.\n\nx*\n\nAbbreviates ‘x-$’.\n\nx-\n\nAbbreviates ‘x-$’ like ‘x*’, but omits the last word. If ‘x’ is missing, it defaults to 0.\n\nIf a word designator is supplied without an event specification, the previous command is used as the event, equivalent to!!. |
| chapter_titleUsing History Interactivelysection_titleModifiersnum_wordsnum_charstextAfter the optional word designator, you can add a sequence of one or more of the following modifiers, each preceded by a ‘:’. These modify, or edit, the word or words selected from the history event. h\n\nRemove a trailing filename component, leaving only the head.\n\nt\n\nRemove all leading filename components, leaving the tail.\n\nr\n\nRemove a trailing suffix of the form ‘.suffix’, leaving the basename.\n\ne\n\nRemove all but the trailing suffix.\n\np\n\nPrint the new command but do not execute it.\n\nq\n\nQuote the substituted words, escaping further substitutions.\n\nx\n\nQuote the substituted words as with ‘q’, but break into words at spaces, tabs, and newlines. The ‘q’ and ‘x’ modifiers are mutually exclusive; expansion uses the last one supplied.\n\ns/old/new/ Substitute new for the first occurrence of old in the event line. Any character may be used as the delimiter in place of ‘/’. The delimiter may be quoted in old and new with a single backslash. If ‘&’ appears in new, it is replaced with old. A single backslash quotes the ‘&’ in old and new. If old is null, it is set to the last old substituted, or, if no previous history substitutions took place, the last string in a!?string[?] search. If new is null, each matching old is deleted. The final delimiter is optional if it is the last character on the input line. & g a G\n\nRepeat the previous substitution. Cause changes to be applied over the entire event line. This is used in conjunction with ‘s’, as in gs/old/new/, or with ‘&’. Apply the following ‘s’ or ‘&’ modifier once to each word in the event. |
| chapter_titleInstalling Bashsection_titleInstalling Bashnum_wordsnum_charstextThis chapter provides basic instructions for installing Bash on the various supported platforms. The distribution supports the gnu operating systems, nearly every version of Unix, and several non-Unix systems such as BeOS and Interix. Other independent ports exist for Windows platforms. |
| chapter_titleInstalling Bashsection_titleBasic Installationnum_wordsnum_charstextThese are installation instructions for Bash. The simplest way to compile Bash is:\n1. cd to the directory containing the source code and type ‘./configure’ to configure\nBash for your system. If you’re using csh on an old version of System V, you might need to type ‘sh./configure’ instead to prevent csh from trying to execute configure itself. Running configure takes some time. While running, it prints messages telling which features it is checking for.\n2. Type ‘make’ to compile Bash and build the bashbug bug reporting script.\n3. Optionally, type ‘make tests’ to run the Bash test suite.\n4. Type ‘make install’ to install bash and bashbug. This will also install the manual pages and Info file, message translation files, some supplemental documentation, a\nnumber of example loadable builtin commands, and a set of header files for developing loadable builtins. You may need additional privileges to install bash to your desired destination, which may require ‘sudo make install’. More information about controlling the locations where bash and other files are installed is below. The configure shell script attempts to guess correct values for various system-dependent variables used during compilation. It uses those values to create a Makefile in each directory of the package (the top directory, the builtins, doc, po, and support directories, each directory under lib, and several others). It also creates a config.h file containing system-dependent definitions. Finally, it creates a shell script named config.status that you can run in the future to recreate the current configuration, a file config.cache that saves the results of its tests to speed up reconfiguring, and a file config.log containing compiler output (useful mainly for debugging configure). If at some point config.cache contains results you don’t want to keep, you may remove or edit it. To find out more about the options and arguments that the configure script understands, type bash-4.2$./configure --help at the Bash prompt in your Bash source directory. If you want to build Bash in a directory separate from the source directory – to build\nfor multiple architectures, for example – just use the full path to the configure script. The\nfollowing commands will build Bash in a directory under /usr/local/build from the source code in /usr/local/src/bash-4.4: mkdir /usr/local/build/bash-4.4\n\ncd /usr/local/build/bash-4.4 bash /usr/local/src/bash-4.4/configure make\n\nabout building in a directory separate from the source. If you need to do unusual things to compile Bash, please try to figure out how configure could check whether or not to do them, and mail diffs or instructions to bash-maintainers@gnu.org so they can be considered for the next release. The file configure.ac is used to create configure by a program called Autoconf. You only need configure.ac if you want to change it or regenerate configure using a newer version of Autoconf. If you do this, make sure you are using Autoconf version 2.69 or newer. You can remove the program binaries and object files from the source code directory by typing ‘make clean’. To also remove the files that configure created (so you can compile Bash for a different kind of computer), type ‘make distclean’. |
| chapter_titleInstalling Bashsection_titleCompilers and Optionsnum_wordsnum_charstextSome systems require unusual options for compilation or linking that the configure script does not know about. You can give configure initial values for variables by setting them in the environment. Using a Bourne-compatible shell, you can do that on the command line like this:\nCC=c89 CFLAGS=-O2 LIBS=-lposix./configure\nOn systems that have the env program, you can do it like this: env CPPFLAGS=-I/usr/local/include LDFLAGS=-s./configure The configuration process uses GCC to build Bash if it is available. |
| chapter_titleInstalling Bashsection_titleCompiling For Multiple Architecturesnum_wordsnum_charstextYou can compile Bash for more than one kind of computer at the same time, by placing the object files for each architecture in their own directory. To do this, you must use a version of make that supports the VPATH variable, such as GNU make. cd to the directory where you want the object files and executables to go and run the configure script from the source directory. You may need to supply the --srcdir=PATH argument to tell configure where the source files are. configure automatically checks for the source code in the directory that configure is in and in... If you have to use a make that does not support the VPATH variable, you can compile Bash\nfor one architecture at a time in the source code directory. After you have installed Bash\nfor one architecture, use ‘make distclean’ before reconfiguring for another architecture.\nAlternatively, if your system supports symbolic links, you can use the support/mkclone script to create a build tree which has symbolic links back to each file in the source directory. Here’s an example that creates a build directory in the current directory from a source directory /usr/gnu/src/bash-2.0: bash /usr/gnu/src/bash-2.0/support/mkclone -s /usr/gnu/src/bash-2.0. The mkclone script requires Bash, so you must have already built Bash for at least one architecture before you can create build directories for other architectures. |
| chapter_titleInstalling Bashsection_titleInstallation Namesnum_wordsnum_charstextBy default, ‘make install’ will install into /usr/local/bin, /usr/local/man, etc.; that is, the installation prefix defaults to /usr/local. You can specify an installation prefix other than /usr/local by giving configure the option --prefix=PATH, or by specifying a value for the prefix ‘make’ variable when running ‘make install’ (e.g., ‘make install\nprefix=PATH’). The prefix variable provides a default for exec_prefix and other variables\nused when installing Bash. You can specify separate installation prefixes for architecture-specific files and architecture-independent files. If you give configure the option --exec-prefix=PATH, ‘make install’ will use PATH as the prefix for installing programs and libraries. Documentation and other data files will still use the regular prefix. If you would like to change the installation locations for a single run, you can specify these variables as arguments to make: ‘make install exec_prefix=/’ will install bash and bashbug into /bin instead of the default /usr/local/bin. If you want to see the files Bash will install and where it will install them without changing anything on your system, specify the variable DESTDIR as an argument to make. Its value should be the absolute directory path you’d like to use as the root of your sample installation tree. For example, mkdir /fs1/bash-install make install DESTDIR=/fs1/bash-install will install bash into /fs1/bash-install/usr/local/bin/bash, the documentation into directories within /fs1/bash-install/usr/local/share, the example loadable builtins into /fs1/bash-install/usr/local/lib/bash, and so on. You can use the usual exec_ prefix and prefix variables to alter the directory paths beneath the value of DESTDIR. The GNU Makefile standards provide a more complete description of these variables and their effects. |
| chapter_titleInstalling Bashsection_titleSpecifying the System Typenum_wordsnum_charstextThere may be some features configure can not figure out automatically, but needs to determine by the type of host Bash will run on. Usually configure can figure that out, but\nif it prints a message saying it can not guess the host type, give it the --host=TYPE option.\n‘TYPE’ can either be a short name for the system type, such as ‘sun4’, or a canonical name with three fields: ‘CPU-COMPANY-SYSTEM’ (e.g., ‘i386-unknown-freebsd4.2’). See the file support/config.sub for the possible values of each field. |
| chapter_titleInstalling Bashsection_titleSharing Defaultsnum_wordsnum_charstextIf you want to set default values for configure scripts to share, you can create a site shell script called config.site that gives default values for variables like CC, cache_ file, and prefix. configure looks for PREFIX/share/config.site if it exists, then PREFIX/etc/config.site if it exists. Or, you can set the CONFIG_SITE environment variable to the location of the site script. A warning: the Bash configure looks for a site script, but not all configure scripts do. |
| chapter_titleInstalling Bashsection_titleOperation Controlsnum_wordsnum_charstextconfigure recognizes the following options to control how it operates. --cache-file=file Use and save the results of the tests in file instead of./config.cache. Set file to /dev/null to disable caching, for debugging configure. --help\n\nPrint a summary of the options to configure, and exit.\n\n--quiet --silent -q\n\nDo not print messages saying which checks are being made.\n\n--srcdir=dir Look for the Bash source code in directory dir. Usually configure can determine that directory automatically. --version Print the version of Autoconf used to generate the configure script, and exit. configure also accepts some other, not widely used, boilerplate options. ‘configure --help’ prints the complete list. |
| chapter_titleInstalling Bashsection_titleOptional Featuresnum_wordsnum_charstextThe Bash configure has a number of --enable-feature options, where feature indicates an optional part of Bash. There are also several --with-package options, where package is something like ‘bash-malloc’ or ‘afs’. To turn off the default use of a package, use --without-package. To configure Bash without a feature that is enabled by default, use --disable-feature. Here is a complete list of the --enable- and --with- options that the Bash configure recognizes. --with-afs Define if you are using the Andrew File System from Transarc. --with-bash-malloc Use the Bash version of malloc in the directory lib/malloc. This is not the same malloc that appears in gnu libc, but a custom version originally derived from the 4.2 bsd malloc. This malloc is very fast, but wastes some space on each allocation, though it uses several techniques to minimize the waste. This option is enabled by default. The NOTES file contains a list of systems for which this should be turned off, and configure disables this option automatically for a number of systems. --with-curses Use the curses library instead of the termcap library. configure usually chooses this automatically, since most systems include the termcap functions in the curses library. --with-gnu-malloc A synonym for --with-bash-malloc.\n\n--with-installed-readline[=PREFIX] Define this to make Bash link with a locally-installed version of Readline rather than the version in lib/readline. This works only with Readline 5.0 and later versions. If PREFIX is yes or not supplied, configure uses the values of the make variables includedir and libdir, which are subdirectories of prefix by default, to find the installed version of Readline if it is not in the standard system include and library directories. If PREFIX is no, Bash links with the version in lib/readline. If PREFIX is set to any other value, configure treats it as a directory pathname and looks for the installed version of Readline in subdirectories of that directory (include files in PREFIX/include and the library in PREFIX/lib). The Bash default is to link with a static library built in the lib/readline subdirectory of the build directory. --with-libintl-prefix[=PREFIX] Define this to make Bash link with a locally-installed version of the libintl library instead of the version in lib/intl. --with-libiconv-prefix[=PREFIX] Define this to make Bash look for libiconv in PREFIX instead of the standard system locations. The Bash distribution does not include this library. --enable-minimal-config This produces a shell with minimal features, closer to the historical Bourne shell. There are several --enable- options that alter how Bash is compiled, linked, and installed, rather than changing run-time features. --enable-largefile Enable support for large files (http://www.unix.org/version2/whatsnew/ lfs20mar.html) if the operating system requires special compiler options to build programs which can access large files. This is enabled by default, if the operating system provides large file support. --enable-profiling This builds a Bash binary that produces profiling information to be processed by gprof each time it is executed. --enable-separate-helpfiles Use external files for the documentation displayed by the help builtin instead of storing the text internally. --enable-static-link This causes Bash to be linked statically, if gcc is being used. This could be used to build a version to use as root’s shell. The ‘minimal-config’ option can be used to disable all of the following options, but it is processed first, so individual options may be enabled using ‘enable-feature’. All of the following options except ‘disabled-builtins’, ‘direxpand-default’,\n\nfor ‘alt-array-implementation’,\n‘strict-posix-default’, and\n\n‘xpg-echo-default’ are enabled by default, unless the operating system does not provide the necessary support. --enable-alias Allow alias expansion and include the alias and unalias builtins. --enable-alt-array-implementation This builds Bash using an alternate implementation of arrays that provides faster access at the expense of using more memory (sometimes many times more, depending on how sparse an array is). --enable-arith-for-command Include support for the alternate form of the for command that behaves like the C language for statement. --enable-array-variables Include support for one-dimensional array shell variables. --enable-bang-history Include support for csh-like history substitution. --enable-bash-source-fullpath-default Set the default value of the bash_source_fullpath shell option described above under Section 4.3.2 [The Shopt Builtin], page 78, to be enabled. This controls how filenames are assigned to the BASH_SOURCE array variable. --enable-brace-expansion Include csh-like brace expansion ( b{a,b}c 7→ bac bbc ). [Brace Expansion], page 25, for a complete description. --enable-casemod-attributes Include support for case-modifying attributes in the declare builtin and assignment statements. Variables with the uppercase attribute, for example, will have their values converted to uppercase upon assignment. --enable-casemod-expansion Include support for case-modifying word expansions. --enable-command-timing Include support for recognizing time as a reserved word and for displaying timing statistics for the pipeline following time. This allows timing pipelines, shell compound commands, shell builtins, and shell functions, which an external command cannot do easily. --enable-cond-command Include support for the [[ conditional command.. --enable-cond-regexp Include support for matching posix regular expressions using the ‘=~’ binary operator in the [[ conditional command..\n\n--enable-coprocesses Include support for coprocesses and the coproc reserved word. --enable-debugger Include support for the Bash debugger (distributed separately). --enable-dev-fd-stat-broken If calling stat on /dev/fd/N returns different results than calling fstat on file descriptor N, supply this option to enable a workaround. This has implications\nfor conditional commands that test file attributes.\n--enable-direxpand-default Cause the direxpand shell option to be enabled by default when the shell starts. It is normally disabled by default. --enable-directory-stack Include support for a csh-like directory stack and the pushd, popd, and dirs builtins. --enable-disabled-builtins Allow builtin commands to be invoked via ‘builtin xxx’ even after xxx has been disabled using ‘enable -n xxx’.\nfor details of the builtin and enable builtin commands.\n--enable-dparen-arithmetic Include support for the ((...)) command. --enable-extended-glob Include support for the extended pattern matching features described above under Section 3.5.8.1 [Pattern Matching], page 39. --enable-extended-glob-default Set the default value of the extglob shell option described above under Section 4.3.2 [The Shopt Builtin], page 78, to be enabled. --enable-function-import Include support for importing function definitions exported by another instance of the shell from the environment. This option is enabled by default. --enable-glob-asciiranges-default Set the default value of the globasciiranges shell option described above under Section 4.3.2 [The Shopt Builtin], page 78, to be enabled. This controls the behavior of character ranges when used in pattern matching bracket expressions. --enable-help-builtin Include the help builtin, which displays help on shell builtins and variables. --enable-history Include command history and the fc and history builtin commands.\n\n--enable-job-control This enables the job control features,\nif the operating system supports them.\n--enable-multibyte This enables support for multibyte characters if the operating system provides the necessary support. --enable-net-redirections This enables the special handling of filenames of the form /dev/tcp/host/port and /dev/udp/host/port when used in redirections. --enable-process-substitution This enables process substitution if the operating system provides the necessary support. --enable-progcomp Enable the programmable completion facilities. If Readline is not enabled, this option has no effect. --enable-prompt-string-decoding Turn on the interpretation of a number of backslash-escaped characters in the $PS0, $PS1, $PS2, and $PS4 prompt strings. Prompt], page 114, for a complete list of prompt string escape sequences. --enable-readline Include support for command-line editing and history with the Bash version of the Readline library. --enable-restricted Include support for a restricted shell. If this is enabled, Bash enters a restricted mode when called as rbash.\nfor a description of restricted mode.\n--enable-select Include the select compound command, which allows generation of simple menus. --enable-single-help-strings Store the text displayed by the help builtin as a single string for each help topic. This aids in translating the text to different languages. You may need to disable this if your compiler cannot handle very long string literals. --enable-strict-posix-default Make Bash posix-conformant by default. --enable-translatable-strings Enable support for $\ translatable strings. --enable-usg-echo-default A synonym for --enable-xpg-echo-default.\n\n--enable-xpg-echo-default Make the echo builtin expand backslash-escaped characters by default, without requiring the -e option. This sets the default value of the xpg_echo shell option to on, which makes the Bash echo behave more like the version specified in the Single Unix Specification, version 3.\nfor a description of the escape sequences that echo recognizes.\nThe file config-top.h contains C Preprocessor ‘#define’ statements for options which are not settable from configure. Some of these are not meant to be changed; beware of the consequences if you do. Read the comments associated with each definition for more information about its effect. |
| |