From 77c107ff99739b3e9db6e23913e8fe3dda9c1a46 Mon Sep 17 00:00:00 2001 From: Llewellyn van der Merwe Date: Sat, 26 Sep 2020 11:10:19 +0200 Subject: [PATCH] Week 4: Assignment - Directory Structure --- week-04/bash.txt | 4852 +++++++++++++++++++++++++++++++++++++++++++++ week-04/csh.txt | 1200 +++++++++++ week-04/korn.txt | 2564 ++++++++++++++++++++++++ week-04/week4.log | 40 + week-04/week4.sh | 133 ++ 5 files changed, 8789 insertions(+) create mode 100644 week-04/bash.txt create mode 100644 week-04/csh.txt create mode 100644 week-04/korn.txt create mode 100644 week-04/week4.log create mode 100755 week-04/week4.sh diff --git a/week-04/bash.txt b/week-04/bash.txt new file mode 100644 index 0000000..5087158 --- /dev/null +++ b/week-04/bash.txt @@ -0,0 +1,4852 @@ +BASH(1) General Commands Manual BASH(1) + +NAME + bash - GNU Bourne-Again SHell + +SYNOPSIS + bash [options] [command_string | file] + +COPYRIGHT + Bash is Copyright (C) 1989-2018 by the Free Software Foundation, Inc. + +DESCRIPTION + Bash is an sh-compatible command language interpreter that executes commands read from the standard + input or from a file. Bash also incorporates useful features from the Korn and C shells (ksh and + csh). + + Bash is intended to be a conformant implementation of the Shell and Utilities portion of the IEEE + POSIX specification (IEEE Standard 1003.1). Bash can be configured to be POSIX-conformant by de‐ + fault. + +OPTIONS + All of the single-character shell options documented in the description of the set builtin command, + including -o, can be used as options when the shell is invoked. In addition, bash interprets the + following options when it is invoked: + + -c If the -c option is present, then commands are read from the first non-option argument + command_string. If there are arguments after the command_string, the first argument is + assigned to $0 and any remaining arguments are assigned to the positional parameters. The + assignment to $0 sets the name of the shell, which is used in warning and error messages. + -i If the -i option is present, the shell is interactive. + -l Make bash act as if it had been invoked as a login shell (see INVOCATION below). + -r If the -r option is present, the shell becomes restricted (see RESTRICTED SHELL below). + -s If the -s option is present, or if no arguments remain after option processing, then com‐ + mands are read from the standard input. This option allows the positional parameters to + be set when invoking an interactive shell or when reading input through a pipe. + -v Print shell input lines as they are read. + -x Print commands and their arguments as they are executed. + -D A list of all double-quoted strings preceded by $ is printed on the standard output. + These are the strings that are subject to language translation when the current locale is + not C or POSIX. This implies the -n option; no commands will be executed. + [-+]O [shopt_option] + shopt_option is one of the shell options accepted by the shopt builtin (see SHELL BUILTIN + COMMANDS below). If shopt_option is present, -O sets the value of that option; +O unsets + it. If shopt_option is not supplied, the names and values of the shell options accepted + by shopt are printed on the standard output. If the invocation option is +O, the output + is displayed in a format that may be reused as input. + -- A -- signals the end of options and disables further option processing. Any arguments af‐ + ter the -- are treated as filenames and arguments. An argument of - is equivalent to --. + + Bash also interprets a number of multi-character options. These options must appear on the command + line before the single-character options to be recognized. + + --debugger + Arrange for the debugger profile to be executed before the shell starts. Turns on extended + debugging mode (see the description of the extdebug option to the shopt builtin below). + --dump-po-strings + Equivalent to -D, but the output is in the GNU gettext po (portable object) file format. + --dump-strings + Equivalent to -D. + --help Display a usage message on standard output and exit successfully. + --init-file file + --rcfile file + Execute commands from file instead of the system wide initialization file /etc/bash.bashrc + and the standard personal initialization file ~/.bashrc if the shell is interactive (see IN‐ + VOCATION below). + + --login + Equivalent to -l. + + --noediting + Do not use the GNU readline library to read command lines when the shell is interactive. + + --noprofile + Do not read either the system-wide startup file /etc/profile or any of the personal initial‐ + ization files ~/.bash_profile, ~/.bash_login, or ~/.profile. By default, bash reads these + files when it is invoked as a login shell (see INVOCATION below). + + --norc Do not read and execute the system wide initialization file /etc/bash.bashrc and the personal + initialization file ~/.bashrc if the shell is interactive. This option is on by default if + the shell is invoked as sh. + + --posix + Change the behavior of bash where the default operation differs from the POSIX standard to + match the standard (posix mode). See SEE ALSO below for a reference to a document that de‐ + tails how posix mode affects bash's behavior. + + --restricted + The shell becomes restricted (see RESTRICTED SHELL below). + + --verbose + Equivalent to -v. + + --version + Show version information for this instance of bash on the standard output and exit success‐ + fully. + +ARGUMENTS + If arguments remain after option processing, and neither the -c nor the -s option has been supplied, + the first argument is assumed to be the name of a file containing shell commands. If bash is in‐ + voked in this fashion, $0 is set to the name of the file, and the positional parameters are set to + the remaining arguments. Bash reads and executes commands from this file, then exits. Bash's exit + status is the exit status of the last command executed in the script. If no commands are executed, + the exit status is 0. An attempt is first made to open the file in the current directory, and, if + no file is found, then the shell searches the directories in PATH for the script. + +INVOCATION + A login shell is one whose first character of argument zero is a -, or one started with the --login + option. + + An interactive shell is one started without non-option arguments (unless -s is specified) and with‐ + out the -c option whose standard input and error are both connected to terminals (as determined by + isatty(3)), or one started with the -i option. PS1 is set and $- includes i if bash is interactive, + allowing a shell script or a startup file to test this state. + + The following paragraphs describe how bash executes its startup files. If any of the files exist + but cannot be read, bash reports an error. Tildes are expanded in filenames as described below un‐ + der Tilde Expansion in the EXPANSION section. + + When bash is invoked as an interactive login shell, or as a non-interactive shell with the --login + option, it first reads and executes commands from the file /etc/profile, if that file exists. After + reading that file, it looks for ~/.bash_profile, ~/.bash_login, and ~/.profile, in that order, and + reads and executes commands from the first one that exists and is readable. The --noprofile option + may be used when the shell is started to inhibit this behavior. + + When an interactive login shell exits, or a non-interactive login shell executes the exit builtin + command, bash reads and executes commands from the file ~/.bash_logout, if it exists. + + When an interactive shell that is not a login shell is started, bash reads and executes commands + from /etc/bash.bashrc and ~/.bashrc, if these files exist. This may be inhibited by using the + --norc option. The --rcfile file option will force bash to read and execute commands from file in‐ + stead of /etc/bash.bashrc and ~/.bashrc. + + When bash is started non-interactively, to run a shell script, for example, it looks for the vari‐ + able BASH_ENV in the environment, expands its value if it appears there, and uses the expanded value + as the name of a file to read and execute. Bash behaves as if the following command were executed: + if [ -n "$BASH_ENV" ]; then . "$BASH_ENV"; fi + but the value of the PATH variable is not used to search for the filename. + + If bash is invoked with the name sh, it tries to mimic the startup behavior of historical versions + of sh as closely as possible, while conforming to the POSIX standard as well. When invoked as an + interactive login shell, or a non-interactive shell with the --login option, it first attempts to + read and execute commands from /etc/profile and ~/.profile, in that order. The --noprofile option + may be used to inhibit this behavior. When invoked as an interactive shell with the name sh, bash + looks for the variable ENV, expands its value if it is defined, and uses the expanded value as the + name of a file to read and execute. Since a shell invoked as sh does not attempt to read and exe‐ + cute commands from any other startup files, the --rcfile option has no effect. A non-interactive + shell invoked with the name sh does not attempt to read any other startup files. When invoked as + sh, bash enters posix mode after the startup files are read. + + When bash is started in posix mode, as with the --posix command line option, it follows the POSIX + standard for startup files. In this mode, interactive shells expand the ENV variable and commands + are read and executed from the file whose name is the expanded value. No other startup files are + read. + + Bash attempts to determine when it is being run with its standard input connected to a network con‐ + nection, as when executed by the remote shell daemon, usually rshd, or the secure shell daemon sshd. + If bash determines it is being run in this fashion, it reads and executes commands from ~/.bashrc + and ~/.bashrc, if these files exist and are readable. It will not do this if invoked as sh. The + --norc option may be used to inhibit this behavior, and the --rcfile option may be used to force an‐ + other file to be read, but neither rshd nor sshd generally invoke the shell with those options or + allow them to be specified. + + If the shell is started with the effective user (group) id not equal to the real user (group) id, + and the -p option is not supplied, no startup files are read, shell functions are not inherited from + the environment, the SHELLOPTS, BASHOPTS, CDPATH, and GLOBIGNORE variables, if they appear in the + environment, are ignored, and the effective user id is set to the real user id. If the -p option is + supplied at invocation, the startup behavior is the same, but the effective user id is not reset. + +DEFINITIONS + The following definitions are used throughout the rest of this document. + blank A space or tab. + word A sequence of characters considered as a single unit by the shell. Also known as a token. + name A word consisting only of alphanumeric characters and underscores, and beginning with an al‐ + phabetic character or an underscore. Also referred to as an identifier. + metacharacter + A character that, when unquoted, separates words. One of the following: + | & ; ( ) < > space tab newline + control operator + A token that performs a control function. It is one of the following symbols: + || & && ; ;; ;& ;;& ( ) | |& + +RESERVED WORDS + Reserved words are words that have a special meaning to the shell. The following words are recog‐ + nized as reserved when unquoted and either the first word of a simple command (see SHELL GRAMMAR be‐ + low) or the third word of a case or for command: + + ! case coproc do done elif else esac fi for function if in select then until while { } time [[ ]] + +SHELL GRAMMAR + Simple Commands + A simple command is a sequence of optional variable assignments followed by blank-separated words + and redirections, and terminated by a control operator. The first word specifies the command to be + executed, and is passed as argument zero. The remaining words are passed as arguments to the in‐ + voked command. + + The return value of a simple command is its exit status, or 128+n if the command is terminated by + signal n. + + Pipelines + A 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]] [ ! ] command [ [|⎪|&] command2 ... ] + + The standard output of command is connected via a pipe to the standard input of command2. This con‐ + nection is performed before any redirections specified by the command (see REDIRECTION below). If + |& is used, command'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 stan‐ + dard error to the standard output is performed after any redirections specified by the command. + + The return status of a pipeline is the exit status of the last command, unless the pipefail option + is enabled. If pipefail is enabled, the pipeline's return status is the value of the last (right‐ + most) command to exit with a non-zero status, or zero if all commands exit successfully. If the re‐ + served word ! precedes a pipeline, the exit status of that pipeline is the logical negation of the + exit status as described above. The shell waits for all commands in the pipeline to terminate be‐ + fore returning a value. + + If the time reserved word precedes a pipeline, the elapsed as well as user and system time consumed + by its execution are reported when the pipeline terminates. 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 re‐ + served word if the next token begins with a `-'. The TIMEFORMAT variable may be set to a format + string that specifies how the timing information should be displayed; see the description of TIME‐ + FORMAT under Shell Variables below. + + When the shell is in posix mode, time may be followed by a newline. In this case, the shell dis‐ + plays the total user and system time consumed by the shell and its children. The TIMEFORMAT vari‐ + able may be used to specify the format of the time information. + + Each command in a pipeline is executed as a separate process (i.e., in a subshell). See COMMAND EX‐ + ECUTION ENVIRONMENT for a description of a subshell environment. If the lastpipe option is enabled + using the shopt builtin (see the description of shopt below), the last element of a pipeline may be + run by the shell process. + + Lists + A list is a sequence of one or more pipelines separated by one of the operators ;, &, &&, or ||, and + optionally terminated by one of ;, &, or . + + Of these list operators, && and || have equal precedence, followed by ; and &, which have equal + precedence. + + A sequence of one or more newlines may appear in a list instead of a semicolon to delimit commands. + + If a command is terminated by the control operator &, the shell executes the command in the back‐ + ground in a subshell. The shell does not wait for the command to finish, and the return status is + 0. These are referred to as asynchronous commands. Commands separated by a ; are executed sequen‐ + tially; 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 && and || control opera‐ + tors, 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. + + Compound Commands + A compound command is one of the following. In most cases a list in a 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. + + (list) list is executed in a subshell environment (see COMMAND EXECUTION ENVIRONMENT below). Vari‐ + able assignments and builtin commands that affect the shell's environment do not remain in + effect after the command completes. The return status is the exit status of list. + + { list; } + list is simply executed in the current shell environment. list must be terminated with a + newline or semicolon. This is known as a group command. The return status is the exit sta‐ + tus of list. Note that unlike the metacharacters ( and ), { and } are reserved words and + must occur where a reserved word is permitted to be recognized. Since they do not cause a + word break, they must be separated from list by whitespace or another shell metacharacter. + + ((expression)) + The expression is evaluated according to the rules described below under ARITHMETIC EVALUA‐ + TION. If the value of the expression is non-zero, the return status is 0; otherwise the re‐ + turn status is 1. This is exactly equivalent to let "expression". + + [[ expression ]] + Return a status of 0 or 1 depending on the evaluation of the conditional expression expres‐ + sion. Expressions are composed of the primaries described below under CONDITIONAL EXPRES‐ + SIONS. Word splitting and pathname expansion are not performed on the words between the [[ + and ]]; tilde expansion, parameter and variable expansion, arithmetic expansion, command sub‐ + stitution, process substitution, and quote removal are performed. 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. + + See the description of the test builtin command (section SHELL BUILTIN COMMANDS below) for the han‐ + dling of parameters (i.e. missing parameters). + + When the == and != operators are used, the string to the right of the operator is considered a pat‐ + tern and matched according to the rules described below under Pattern Matching, as if the extglob + shell option were enabled. The = operator is equivalent to ==. If the nocasematch shell option 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. Any part + of the pattern may be quoted to force the quoted portion to be matched as a string. + + An additional binary operator, =~, is available, with the same precedence as == and !=. When it is + used, the string to the right of the operator is considered a POSIX extended regular expression and + matched accordingly (as in regex(3)). The return value is 0 if the string matches the pattern, and + 1 otherwise. If the regular expression is syntactically incorrect, the conditional expression's re‐ + turn value is 2. If the nocasematch shell option is enabled, the match is performed without regard + to the case of alphabetic characters. Any part of the pattern may be quoted to force the quoted + portion to be matched as a string. Bracket expressions in regular expressions must be treated care‐ + fully, since normal quoting characters lose their meanings between brackets. If the pattern is + stored in a shell variable, quoting the variable expansion forces the entire pattern to be matched + as a string. Substrings matched by parenthesized subexpressions within the regular expression are + saved in the array variable BASH_REMATCH. The element of BASH_REMATCH with index 0 is the portion + of the string matching the entire regular expression. The element of BASH_REMATCH with index n is + the portion of the string matching the nth parenthesized subexpression. + + 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. + + for name [ [ in [ word ... ] ] ; ] do list ; done + The list of words following in is expanded, generating a list of items. The variable name is + set to each element of this list in turn, and list is executed each time. If the in word is + omitted, the for command executes list once for each positional parameter that is set (see + PARAMETERS below). The return status is the exit status of the last command that executes. + If the expansion of the items following in results in an empty list, no commands are exe‐ + cuted, and the return status is 0. + + for (( expr1 ; expr2 ; expr3 )) ; do list ; done + First, the arithmetic expression expr1 is evaluated according to the rules described below + under ARITHMETIC EVALUATION. The arithmetic expression expr2 is then evaluated repeatedly + until it evaluates to zero. Each time expr2 evaluates to a non-zero value, list is executed + and the arithmetic expression expr3 is evaluated. If any expression is omitted, it behaves + as if it evaluates to 1. The return value is the exit status of the last command in list + that is executed, or false if any of the expressions is invalid. + + select name [ in word ] ; do list ; done + The list of words following in is expanded, generating a list of items. The set of expanded + words is printed on the standard error, each preceded by a number. If the in word is omit‐ + ted, the positional parameters are printed (see PARAMETERS below). The PS3 prompt is then + displayed and a line read from the standard input. If the line consists of a number corre‐ + sponding to one of the displayed words, then the value of name is set to that word. If the + line is empty, the words and prompt are displayed again. If EOF is read, the command com‐ + pletes. Any other value read causes name to be set to null. The line read is saved in the + variable REPLY. The list is executed after each selection until a break command is executed. + The exit status of select is the exit status of the last command executed in list, or zero if + no commands were executed. + + case word in [ [(] pattern [ | pattern ] ... ) list ;; ] ... esac + A case command first expands word, and tries to match it against each pattern in turn, using + the matching rules described under Pattern Matching below. The word is expanded using tilde + expansion, parameter and variable expansion, arithmetic expansion, command substitution, + process substitution and quote removal. Each pattern examined is expanded using tilde expan‐ + sion, parameter and variable expansion, arithmetic expansion, command substitution, and + process substitution. If the nocasematch shell option is enabled, the match is performed + without regard to the case of alphabetic characters. When a match is found, the correspond‐ + ing list is executed. If the ;; operator is used, no subsequent matches are attempted after + the first pattern match. Using ;& in place of ;; causes execution to continue with the list + associated with the next set of patterns. Using ;;& in place of ;; causes the shell to test + the next pattern list in the statement, if any, and execute any associated list on a success‐ + ful match. The exit status is zero if no pattern matches. Otherwise, it is the exit status + of the last command executed in list. + + if list; then list; [ elif list; then list; ] ... [ else list; ] fi + The if list is executed. If its exit status is zero, the then list is executed. Otherwise, + each elif list is executed in turn, and if its exit status is zero, the corresponding then + list is executed and the command completes. Otherwise, the else list is executed, if + present. The exit status is the exit status of the last command executed, or zero if no con‐ + dition tested true. + + while list-1; do list-2; done + until list-1; do list-2; done + The while command continuously executes the list list-2 as long as the last command in the + list list-1 returns an exit status of zero. The until command is identical to the while com‐ + mand, except that the test is negated: list-2 is executed as long as the last command in + list-1 returns a non-zero exit status. The exit status of the while and until commands is + the exit status of the last command executed in list-2, or zero if none was executed. + + Coprocesses + A coprocess is a shell command preceded by the coproc reserved word. A coprocess is executed asyn‐ + chronously 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 format for a coprocess is: + + coproc [NAME] command [redirections] + + This creates a coprocess named NAME. If NAME is not supplied, the default name is COPROC. NAME + must not be supplied if command is a simple command (see above); otherwise, it is interpreted as the + first word of the simple command. When the coprocess is executed, the shell creates an array vari‐ + able (see Arrays below) 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 descrip‐ + tor is assigned to NAME[0]. The standard input of command is connected via a pipe to a file de‐ + scriptor in the executing shell, and that file descriptor is assigned to NAME[1]. This pipe is es‐ + tablished before any redirections specified by the command (see REDIRECTION below). The file de‐ + scriptors can be utilized as arguments to shell commands and redirections using standard word expan‐ + sions. 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 command may be used to wait for + the coprocess to terminate. + + Since the coprocess is created as an asynchronous command, the coproc command always returns suc‐ + cess. The return status of a coprocess is the exit status of command. + + Shell Function Definitions + A shell function is an object that is called like a simple command and executes a compound command + with a new set of positional parameters. Shell functions are declared as follows: + + name () compound-command [redirection] + function name [()] compound-command [redirection] + This defines a function named name. The reserved word function is optional. If the function + reserved word is supplied, the parentheses are optional. The body of the function is the + compound command compound-command (see Compound Commands above). That command is usually a + list of commands between { and }, but may be any command listed under Compound Commands + above, with one exception: If the function reserved word is used, but the parentheses are not + supplied, the braces are required. compound-command is executed whenever name is specified + as the name of a simple command. When in posix mode, name may not be the name of one of the + POSIX special builtins. Any redirections (see REDIRECTION below) specified when a function + is defined are performed when the function is executed. The exit status of a function defi‐ + nition is zero unless a syntax error occurs or a readonly function with the same name already + exists. When executed, the exit status of a function is the exit status of the last command + executed in the body. (See FUNCTIONS below.) + +COMMENTS + In a non-interactive shell, or an interactive shell in which the interactive_comments option to the + shopt builtin is enabled (see SHELL BUILTIN COMMANDS below), a word beginning with # causes that + word and all remaining characters on that line to be ignored. An interactive shell without the in‐ + teractive_comments option enabled does not allow comments. The interactive_comments option is on by + default in interactive shells. + +QUOTING + Quoting is used to remove the special meaning of certain characters or words to the shell. Quoting + can be used to disable special treatment for special characters, to prevent reserved words from be‐ + ing recognized as such, and to prevent parameter expansion. + + Each of the metacharacters listed above under DEFINITIONS has special meaning to the shell and must + be quoted if it is to represent itself. + + When the command history expansion facilities are being used (see HISTORY EXPANSION below), the his‐ + tory expansion character, usually !, must be quoted to prevent history expansion. + + There are three quoting mechanisms: the escape character, single quotes, and double quotes. + + A non-quoted backslash (\) is the escape character. It preserves the literal value of the next + character that follows, with the exception of . If a \ pair appears, and the + backslash is not itself quoted, the \ is treated as a line continuation (that is, it is re‐ + moved from the input stream and effectively ignored). + + Enclosing characters in single quotes preserves the literal value of each character within the + quotes. A single quote may not occur between single quotes, even when preceded by a backslash. + + Enclosing characters in double quotes 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 en‐ + abled. The characters $ and ` retain their special meaning within double quotes. The backslash re‐ + tains its special meaning only when followed by one of the following characters: $, `, ", \, or + . A double quote may be quoted within double quotes by preceding it with a backslash. If + enabled, history expansion will be performed unless an ! appearing in double quotes is escaped us‐ + ing a backslash. The backslash preceding the ! is not removed. + + The special parameters * and @ have special meaning when in double quotes (see PARAMETERS below). + + Words of the form $'string' are treated specially. The word expands to string, with backslash-es‐ + caped characters replaced as specified by the ANSI C standard. Backslash escape sequences, if + present, are decoded as follows: + \a alert (bell) + \b backspace + \e + \E an escape character + \f form feed + \n new line + \r carriage return + \t horizontal tab + \v vertical tab + \\ backslash + \' single quote + \" double quote + \? question mark + \nnn the eight-bit character whose value is the octal value nnn (one to three octal digits) + \xHH the eight-bit character whose value is the hexadecimal value HH (one or two hex dig‐ + its) + \uHHHH the Unicode (ISO/IEC 10646) character whose value is the hexadecimal value HHHH (one + to four hex digits) + \UHHHHHHHH + the Unicode (ISO/IEC 10646) character whose value is the hexadecimal value HHHHHHHH + (one to eight hex digits) + \cx a control-x character + + The expanded result is single-quoted, as if the dollar sign had not been present. + + A double-quoted string preceded by a dollar sign ($"string") will cause the string to be translated + according to the current locale. If the current locale is C or POSIX, the dollar sign is ignored. + If the string is translated and replaced, the replacement is double-quoted. + +PARAMETERS + A parameter is an entity that stores values. It can be a name, a number, or one of the special + characters listed below under Special Parameters. 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 declare below in SHELL BUILTIN COMMANDS). + + A parameter is set if it has been assigned a value. The null string is a valid value. Once a vari‐ + able is set, it may be unset only by using the unset builtin command (see SHELL BUILTIN COMMANDS be‐ + low). + + A variable may be assigned to by a statement of the form + + name=[value] + + If value is not given, the variable is assigned the null string. All values undergo tilde expan‐ + sion, parameter and variable expansion, command substitution, arithmetic expansion, and quote re‐ + moval (see EXPANSION below). If the variable has its integer attribute set, then value is evaluated + as an arithmetic expression even if the $((...)) expansion is not used (see Arithmetic Expansion be‐ + low). Word splitting is not performed, with the exception of "$@" as explained below under Special + Parameters. Pathname expansion is not performed. Assignment statements may also appear as argu‐ + ments to the alias, declare, typeset, export, readonly, and local builtin commands (declaration com‐ + mands). 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. + + In the context where an assignment statement is assigning a value to a shell variable or array in‐ + dex, the += operator can be used to append to or add to the variable's previous value. This in‐ + cludes arguments to builtin commands such as declare that accept assignment statements (declaration + commands). When += is applied to a variable for which the integer attribute has been set, value is + evaluated as an arithmetic expression and added to the variable's current value, which is also eval‐ + uated. When += is applied to an array variable using compound assignment (see Arrays below), the + variable's value is not unset (as it is when using =), and new values are appended to the array be‐ + ginning 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 ex‐ + panded 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 (see the descriptions of declare and local below) to create a nameref, or a reference to + another variable. This allows variables to be manipulated indirectly. Whenever the nameref vari‐ + able 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 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 will be 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 us‐ + ing 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 will be unset. + + Positional Parameters + A positional parameter is a parameter denoted by one or more digits, other than the single digit 0. + Positional parameters are assigned from the shell's arguments when it is invoked, and may be reas‐ + signed using the set builtin command. Positional parameters may not be assigned to with assignment + statements. The positional parameters are temporarily replaced when a shell function is executed + (see FUNCTIONS below). + + When a positional parameter consisting of more than a single digit is expanded, it must be enclosed + in braces (see EXPANSION below). + + Special Parameters + The shell treats several parameters specially. These parameters may only be referenced; assignment + to them is not allowed. + * 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 it is + performed, those words are subject to further word splitting and pathname 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 special variable. That is, "$*" is + equivalent to "$1c$2c...", 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. + @ 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, this expands to a single word with each positional parameter separated by a space. + When the expansion occurs within double quotes, each parameter expands to a separate word. + That is, "$@" is equivalent to "$1" "$2" ... If the double-quoted expansion occurs within a + word, the expansion of the first parameter is joined with the beginning part of the original + word, and the expansion of the last parameter is joined with the last part of the original + word. When there are no positional parameters, "$@" and $@ expand to nothing (i.e., they are + removed). + # Expands to the number of positional parameters in decimal. + ? Expands to the exit status of the most recently executed foreground pipeline. + - 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). + $ Expands to the process ID of the shell. In a () subshell, it expands to the process ID of + the current shell, not the subshell. + ! Expands to the process ID of the job most recently placed into the background, whether exe‐ + cuted as an asynchronous command or using the bg builtin (see JOB CONTROL below). + 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 exe‐ + cuted, if one is present. Otherwise, it is set to the filename used to invoke bash, as given + by argument zero. + _ At shell startup, set to the absolute pathname used to invoke the shell or shell script being + executed as passed in the environment or argument list. Subsequently, expands to the last + argument to the previous simple command executed in the foreground, after expansion. Also + set to the full pathname used to invoke each command executed and placed in the environment + exported to that command. When checking mail, this parameter holds the name of the mail file + currently being checked. + + Shell Variables + The following variables are set by the shell: + + BASH Expands to the full filename used to invoke this instance of bash. + BASHOPTS + A colon-separated list of enabled shell options. Each word in the list is a valid argument + for the -s option to the shopt builtin command (see SHELL BUILTIN COMMANDS below). The op‐ + tions appearing in BASHOPTS are those reported as on by shopt. If this variable is in the + environment when bash starts up, each shell option in the list will be enabled before reading + any startup files. This variable is read-only. + BASHPID + Expands to the process ID of the current bash process. This differs from $$ under certain + circumstances, such as subshells that do not require bash to be re-initialized. Assignments + to BASHPID have no effect. If BASHPID is unset, it loses its special properties, even if it + is subsequently reset. + BASH_ALIASES + An associative array variable whose members correspond to the internal list of aliases as + maintained by the alias builtin. Elements added to this array appear in the alias list; how‐ + ever, unsetting array elements currently does not cause aliases to be removed from the alias + list. If BASH_ALIASES is unset, it loses its special properties, even if it is subsequently + reset. + BASH_ARGC + An array variable whose values are the number of parameters in each frame of the current bash + execution call stack. The number of parameters to the current subroutine (shell function or + script executed with . or source) is at the top of the stack. When a subroutine is executed, + the number of parameters passed is pushed onto BASH_ARGC. The shell sets BASH_ARGC only when + in extended debugging mode (see the description of the extdebug option to the shopt builtin + below). Setting extdebug after the shell has started to execute a script, or referencing + this variable when extdebug is not set, may result in inconsistent values. + BASH_ARGV + An array variable containing all of the parameters in the current bash execution call stack. + The final parameter of the last subroutine call is at the top of the stack; the first parame‐ + ter of the initial call is at the bottom. When a subroutine is executed, the parameters sup‐ + plied are pushed onto BASH_ARGV. The shell sets BASH_ARGV only when in extended debugging + mode (see the description of the extdebug option to the shopt builtin below). Setting extde‐ + bug after the shell has started to execute a script, or referencing this variable when extde‐ + bug is not set, may result in inconsistent values. + BASH_ARGV0 + When referenced, this variable expands to the name of the shell or shell script (identical to + $0; see the description of special parameter 0 above). Assignment to BASH_ARGV0 causes the + value assigned to also be assigned to $0. If BASH_ARGV0 is unset, it loses its special prop‐ + erties, even if it is subsequently reset. + BASH_CMDS + An associative array variable whose members correspond to the internal hash table of commands + as maintained by the hash builtin. Elements added to this array appear in the hash table; + however, unsetting array elements currently does not cause command names to be removed from + the hash table. If BASH_CMDS is unset, it loses its special properties, even if it is subse‐ + quently reset. + BASH_COMMAND + The command currently being executed or about to be executed, unless the shell is executing a + command as the result of a trap, in which case it is the command executing at the time of the + trap. + BASH_EXECUTION_STRING + The command argument to the -c invocation option. + BASH_LINENO + An array variable whose members are the line numbers in source files where each corresponding + member of FUNCNAME was invoked. ${BASH_LINENO[$i]} is the line number in the source file + (${BASH_SOURCE[$i+1]}) where ${FUNCNAME[$i]} was called (or ${BASH_LINENO[$i-1]} if refer‐ + enced within another shell function). Use LINENO to obtain the current line number. + BASH_LOADABLES_PATH + A colon-separated list of directories in which the shell looks for dynamically loadable + builtins specified by the enable command. + BASH_REMATCH + An array variable whose members are assigned by the =~ binary operator to the [[ conditional + command. The element with index 0 is the portion of the string matching the entire regular + expression. The element with index n is the portion of the string matching the nth parenthe‐ + sized subexpression. This variable is read-only. + BASH_SOURCE + An array variable whose members are the source filenames where the corresponding shell func‐ + tion names in the FUNCNAME array variable are defined. The shell function ${FUNCNAME[$i]} is + defined in the file ${BASH_SOURCE[$i]} and called from ${BASH_SOURCE[$i+1]}. + BASH_SUBSHELL + Incremented by one within each subshell or subshell environment when the shell begins execut‐ + ing in that environment. The initial value is 0. + BASH_VERSINFO + A readonly array variable whose members hold version information for this instance of bash. + The values assigned to the array members are as follows: + BASH_VERSINFO[0] The major version number (the release). + BASH_VERSINFO[1] The minor version number (the version). + BASH_VERSINFO[2] The patch level. + BASH_VERSINFO[3] The build version. + BASH_VERSINFO[4] The release status (e.g., beta1). + BASH_VERSINFO[5] The value of MACHTYPE. + BASH_VERSION + Expands to a string describing the version of this instance of bash. + COMP_CWORD + An index into ${COMP_WORDS} of the word containing the current cursor position. This vari‐ + able is available only in shell functions invoked by the programmable completion facilities + (see Programmable Completion below). + COMP_KEY + The key (or final key of a key sequence) used to invoke the current completion function. + COMP_LINE + The current command line. This variable is available only in shell functions and external + commands invoked by the programmable completion facilities (see Programmable Completion be‐ + low). + COMP_POINT + The index of the current cursor position relative to the beginning of the current command. + If the current cursor position is at the end of the current command, the value of this vari‐ + able is equal to ${#COMP_LINE}. This variable is available only in shell functions and ex‐ + ternal commands invoked by the programmable completion facilities (see Programmable Comple‐ + tion below). + COMP_TYPE + Set to an integer value corresponding to the type of completion attempted that caused a com‐ + pletion function to be called: TAB, for normal completion, ?, for listing completions after + successive tabs, !, for listing alternatives on partial word completion, @, to list comple‐ + tions if the word is not unmodified, or %, for menu completion. This variable is available + only in shell functions and external commands invoked by the programmable completion facili‐ + ties (see Programmable Completion below). + COMP_WORDBREAKS + The set of characters that the readline library treats as word separators when performing + word completion. If COMP_WORDBREAKS is unset, it loses its special properties, even if it is + subsequently reset. + COMP_WORDS + An array variable (see Arrays below) consisting of the individual words in the current com‐ + mand line. The line is split into words as readline would split it, using COMP_WORDBREAKS as + described above. This variable is available only in shell functions invoked by the program‐ + mable completion facilities (see Programmable Completion below). + COPROC An array variable (see Arrays below) created to hold the file descriptors for output from and + input to an unnamed coprocess (see Coprocesses above). + DIRSTACK + An array variable (see Arrays below) containing the current contents of the directory stack. + Directories appear in the stack in the order they are displayed by the dirs builtin. Assign‐ + ing to members of this array variable may be used to modify directories already in the stack, + but the pushd and popd builtins must be used to add and remove directories. Assignment to + this variable will not change the current directory. If DIRSTACK is unset, it loses its spe‐ + cial properties, even if it is subsequently reset. + EPOCHREALTIME + Each time this parameter is referenced, it expands to the number of seconds since the Unix + Epoch (see time(3)) as a floating point value with micro-second granularity. Assignments to + EPOCHREALTIME are ignored. If EPOCHREALTIME is unset, it loses its special properties, even + if it is subsequently reset. + EPOCHSECONDS + Each time this parameter is referenced, it expands to the number of seconds since the Unix + Epoch (see time(3)). Assignments to EPOCHSECONDS are ignored. If EPOCHSECONDS is unset, it + loses its special properties, even if it is subsequently reset. + EUID Expands to the effective user ID of the current user, initialized at shell startup. This + variable is readonly. + FUNCNAME + An array variable containing the names of all shell functions currently in the execution call + stack. The element with index 0 is the name of any currently-executing shell function. The + bottom-most element (the one with the highest index) is "main". This variable exists only + when a shell function is executing. Assignments to FUNCNAME have no effect. If FUNCNAME is + unset, it loses its special properties, even if it is subsequently reset. + + This variable can be used with BASH_LINENO and BASH_SOURCE. Each element of FUNCNAME has + corresponding elements in BASH_LINENO and BASH_SOURCE to describe the call stack. For in‐ + stance, ${FUNCNAME[$i]} was called from the file ${BASH_SOURCE[$i+1]} at line number + ${BASH_LINENO[$i]}. The caller builtin displays the current call stack using this informa‐ + tion. + GROUPS An array variable containing the list of groups of which the current user is a member. As‐ + signments to GROUPS have no effect. If GROUPS is unset, it loses its special properties, + even if it is subsequently reset. + HISTCMD + The history number, or index in the history list, of the current command. If HISTCMD is un‐ + set, it loses its special properties, even if it is subsequently reset. + HOSTNAME + Automatically set to the name of the current host. + HOSTTYPE + Automatically set to a string that uniquely describes the type of machine on which bash is + executing. The default is system-dependent. + LINENO Each time this parameter is referenced, the shell substitutes a decimal number representing + the current sequential line number (starting with 1) within a script or function. When not + in a script or function, the value substituted is not guaranteed to be meaningful. If LINENO + is unset, it loses its special properties, even if it is subsequently reset. + MACHTYPE + Automatically set to a string that fully describes the system type on which bash is execut‐ + ing, in the standard GNU cpu-company-system format. The default is system-dependent. + MAPFILE + An array variable (see Arrays below) created to hold the text read by the mapfile builtin + when no variable name is supplied. + OLDPWD The previous working directory as set by the cd command. + OPTARG The value of the last option argument processed by the getopts builtin command (see SHELL + BUILTIN COMMANDS below). + OPTIND The index of the next argument to be processed by the getopts builtin command (see SHELL + BUILTIN COMMANDS below). + OSTYPE Automatically set to a string that describes the operating system on which bash is executing. + The default is system-dependent. + PIPESTATUS + An array variable (see Arrays below) containing a list of exit status values from the pro‐ + cesses in the most-recently-executed foreground pipeline (which may contain only a single + command). + PPID The process ID of the shell's parent. This variable is readonly. + PWD The current working directory as set by the cd command. + RANDOM Each time this parameter is referenced, a random integer between 0 and 32767 is generated. + The sequence of random numbers may be initialized by assigning a value to RANDOM. If RANDOM + is unset, it loses its special properties, even if it is subsequently reset. + READLINE_LINE + The contents of the readline line buffer, for use with "bind -x" (see SHELL BUILTIN COMMANDS + below). + READLINE_POINT + The position of the insertion point in the readline line buffer, for use with "bind -x" (see + SHELL BUILTIN COMMANDS below). + REPLY Set to the line of input read by the read builtin command when no arguments are supplied. + SECONDS + Each time this parameter is referenced, the number of seconds since shell invocation is re‐ + turned. If a value is assigned to SECONDS, the value returned upon subsequent references is + the number of seconds since the assignment plus the value assigned. If SECONDS is unset, it + loses its special properties, even if it is subsequently reset. + SHELLOPTS + A colon-separated list of enabled shell options. Each word in the list is a valid argument + for the -o option to the set builtin command (see SHELL BUILTIN COMMANDS below). The options + appearing in SHELLOPTS are those reported as on by set -o. If this variable is in the envi‐ + ronment when bash starts up, each shell option in the list will be enabled before reading any + startup files. This variable is read-only. + SHLVL Incremented by one each time an instance of bash is started. + UID Expands to the user ID of the current user, initialized at shell startup. This variable is + readonly. + + The following variables are used by the shell. In some cases, bash assigns a default value to a + variable; these cases are noted below. + + BASH_COMPAT + The value is used to set the shell's compatibility level. See the description of the shopt + builtin below under SHELL BUILTIN COMMANDS for a description of the various compatibility + levels and their effects. The value may be a decimal number (e.g., 4.2) or an integer (e.g., + 42) corresponding to the desired compatibility level. If BASH_COMPAT is unset or set to the + empty string, the compatibility level is set to the default for the current version. If + BASH_COMPAT is set to a value that is not one of the valid compatibility levels, the shell + prints an error message and sets the compatibility level to the default for the current ver‐ + sion. The valid compatibility levels correspond to the compatibility options accepted by the + shopt builtin described below (for example, compat42 means that 4.2 and 42 are valid values). + The current version is also a valid value. + BASH_ENV + If this parameter is set when bash is executing a shell script, its value is interpreted as a + filename containing commands to initialize the shell, as in ~/.bashrc. The value of BASH_ENV + is subjected to parameter expansion, command substitution, and arithmetic expansion before + being interpreted as a filename. PATH is not used to search for the resultant filename. + BASH_XTRACEFD + If set to an integer corresponding to a valid file descriptor, bash will write the trace out‐ + put generated when set -x is enabled to that file descriptor. The file descriptor is closed + when BASH_XTRACEFD is unset or assigned a new value. Unsetting BASH_XTRACEFD or assigning it + the empty string causes the trace output to be sent to the standard error. Note that setting + BASH_XTRACEFD to 2 (the standard error file descriptor) and then unsetting it will result in + the standard error being closed. + CDPATH The search path for the cd command. This is a colon-separated list of directories in which + the shell looks for destination directories specified by the cd command. A sample value is + ".:~:/usr". + CHILD_MAX + Set the number of exited child status values for the shell to remember. Bash will not allow + this value to be decreased below a POSIX-mandated minimum, and there is a maximum value (cur‐ + rently 8192) that this may not exceed. The minimum value is system-dependent. + COLUMNS + Used by the select compound command to determine the terminal width when printing selection + lists. Automatically set if the checkwinsize option is enabled or in an interactive shell + upon receipt of a SIGWINCH. + COMPREPLY + An array variable from which bash reads the possible completions generated by a shell func‐ + tion invoked by the programmable completion facility (see Programmable Completion below). + Each array element contains one possible completion. + EMACS If bash finds this variable in the environment when the shell starts with value "t", it as‐ + sumes that the shell is running in an Emacs shell buffer and disables line editing. + ENV Similar to BASH_ENV; used when the shell is invoked in posix mode. + EXECIGNORE + A colon-separated list of shell patterns (see Pattern Matching) defining the list of file‐ + names to be ignored by command search using PATH. Files whose full pathnames match one of + these patterns are not considered executable files for the purposes of completion and command + execution via PATH lookup. This does not affect the behavior of the [, test, and [[ com‐ + mands. Full pathnames in the command hash table are not subject to EXECIGNORE. Use this + variable to ignore shared library files that have the executable bit set, but are not exe‐ + cutable files. The pattern matching honors the setting of the extglob shell option. + FCEDIT The default editor for the fc builtin command. + FIGNORE + A colon-separated list of suffixes to ignore when performing filename completion (see READ‐ + LINE below). A filename whose suffix matches one of the entries in FIGNORE is excluded from + the list of matched filenames. A sample value is ".o:~" (Quoting is needed when assigning a + value to this variable, which contains tildes). + FUNCNEST + If set to a numeric value greater than 0, defines a maximum function nesting level. Function + invocations that exceed this nesting level will cause the current command to abort. + GLOBIGNORE + A colon-separated list of patterns defining the set of file names to be ignored by pathname + expansion. If a file name matched by a pathname expansion pattern also matches one of the + patterns in GLOBIGNORE, it is removed from the list of matches. + HISTCONTROL + A colon-separated list of values controlling how commands are saved on the history list. If + the list of values includes ignorespace, lines which begin with a space character are not + saved in the history list. A value of ignoredups causes lines matching the previous history + entry to not be saved. A value of ignoreboth is shorthand for ignorespace and ignoredups. A + value of erasedups causes all previous lines matching the current line to be removed from the + history list before that line is saved. Any value not in the above list is ignored. If + HISTCONTROL is unset, or does not include a valid value, all lines read by the shell parser + are saved on the history list, subject to the value of HISTIGNORE. The second and subsequent + lines of a multi-line compound command are not tested, and are added to the history regard‐ + less of the value of HISTCONTROL. + HISTFILE + The name of the file in which command history is saved (see HISTORY below). The default + value is ~/.bash_history. If unset, the command history is not saved when a shell exits. + HISTFILESIZE + The maximum number of lines contained in the history file. When this variable is assigned a + value, the history file is truncated, if necessary, to contain no more than that number of + lines by removing the oldest entries. The history file is also truncated to this size after + writing it when a shell exits. If the value is 0, the history file is truncated to zero + size. Non-numeric values and numeric values less than zero inhibit truncation. The shell + sets the default value to the value of HISTSIZE after reading any startup files. + HISTIGNORE + A colon-separated list of patterns used to decide which command lines should be saved on the + history list. Each pattern is anchored at the beginning of the line and must match the com‐ + plete line (no implicit `*' is appended). Each pattern is tested against the line after the + checks specified by HISTCONTROL are applied. In addition to the normal shell pattern match‐ + ing characters, `&' matches the previous history line. `&' may be escaped using a backslash; + the backslash is removed before attempting a match. The second and subsequent lines of a + multi-line compound command are not tested, and are added to the history regardless of the + value of HISTIGNORE. The pattern matching honors the setting of the extglob shell option. + HISTSIZE + The number of commands to remember in the command history (see HISTORY below). If the value + is 0, commands are not saved in the history list. Numeric values less than zero result in + every command being saved on the history list (there is no limit). The shell sets the de‐ + fault value to 500 after reading any startup files. + HISTTIMEFORMAT + If this variable is set and not null, its value is used as a format string for strftime(3) to + print the time stamp associated with each history entry displayed by the history builtin. If + this variable is set, time stamps are written to the history file so they may be preserved + across shell sessions. This uses the history comment character to distinguish timestamps + from other history lines. + HOME The home directory of the current user; the default argument for the cd builtin command. The + value of this variable is also used when performing tilde expansion. + HOSTFILE + Contains the name of a file in the same format as /etc/hosts that should be read when the + shell needs to complete a hostname. The list of possible hostname completions may be changed + while the shell is running; the next time hostname completion is attempted after the value is + changed, bash adds the contents of the new file to the existing list. If HOSTFILE is set, + but has no value, or does not name a readable file, bash attempts to read /etc/hosts to ob‐ + tain the list of possible hostname completions. When HOSTFILE is unset, the hostname list is + cleared. + IFS The Internal Field Separator that is used for word splitting after expansion and to split + lines into words with the read builtin command. The default value is ``''. + IGNOREEOF + Controls the action of an interactive shell on receipt of an EOF character as the sole input. + If set, the value is the number of consecutive EOF characters which must be typed as the + first characters on an input line before bash exits. If the variable exists but does not + have a numeric value, or has no value, the default value is 10. If it does not exist, EOF + signifies the end of input to the shell. + INPUTRC + The filename for the readline startup file, overriding the default of ~/.inputrc (see READ‐ + LINE below). + INSIDE_EMACS + If this variable appears in the environment when the shell starts, bash assumes that it is + running inside an Emacs shell buffer and may disable line editing, depending on the value of + TERM. + LANG Used to determine the locale category for any category not specifically selected with a vari‐ + able starting with LC_. + LC_ALL This variable overrides the value of LANG and any other LC_ variable specifying a locale cat‐ + egory. + LC_COLLATE + This variable determines the collation order used when sorting the results of pathname expan‐ + sion, and determines the behavior of range expressions, equivalence classes, and collating + sequences within pathname expansion and pattern matching. + LC_CTYPE + This variable determines the interpretation of characters and the behavior of character + classes within pathname expansion and pattern matching. + LC_MESSAGES + This variable determines the locale used to translate double-quoted strings preceded by a $. + LC_NUMERIC + This variable determines the locale category used for number formatting. + LC_TIME + This variable determines the locale category used for data and time formatting. + LINES Used by the select compound command to determine the column length for printing selection + lists. Automatically set if the checkwinsize option is enabled or in an interactive shell + upon receipt of a SIGWINCH. + MAIL If this parameter is set to a file or directory name and the MAILPATH variable is not set, + bash informs the user of the arrival of mail in the specified file or Maildir-format direc‐ + tory. + MAILCHECK + Specifies how often (in seconds) bash checks for mail. The default is 60 seconds. When it + is time to check for mail, the shell does so before displaying the primary prompt. If this + variable is unset, or set to a value that is not a number greater than or equal to zero, the + shell disables mail checking. + MAILPATH + A colon-separated list of filenames to be checked for mail. The message to be printed when + mail arrives in a particular file may be specified by separating the filename from the mes‐ + sage with a `?'. When used in the text of the message, $_ expands to the name of the current + mailfile. Example: + MAILPATH='/var/mail/bfox?"You have mail":~/shell-mail?"$_ has mail!"' + Bash can be configured to supply a default value for this variable (there is no value by de‐ + fault), but the location of the user mail files that it uses is system dependent (e.g., + /var/mail/$USER). + OPTERR If set to the value 1, bash displays error messages generated by the getopts builtin command + (see SHELL BUILTIN COMMANDS below). OPTERR is initialized to 1 each time the shell is in‐ + voked or a shell script is executed. + PATH The search path for commands. It is a colon-separated list of directories in which the shell + looks for commands (see COMMAND EXECUTION below). A zero-length (null) directory name in the + value of PATH indicates the current directory. A null directory name may appear as two adja‐ + cent colons, or as an initial or trailing colon. The default path is system-dependent, and + is set by the administrator who installs bash. A common value is ``/usr/local/bin:/usr/lo‐ + cal/sbin:/usr/bin:/usr/sbin:/bin:/sbin''. + POSIXLY_CORRECT + If this variable is in the environment when bash starts, the shell enters posix mode before + reading the startup files, as if the --posix invocation option had been supplied. If it is + set while the shell is running, bash enables posix mode, as if the command set -o posix had + been executed. When the shell enters posix mode, it sets this variable if it was not already + set. + PROMPT_COMMAND + If set, the value is executed as a command prior to issuing each primary prompt. + PROMPT_DIRTRIM + If set to a number greater than zero, the value is used as the number of trailing directory + components to retain when expanding the \w and \W prompt string escapes (see PROMPTING be‐ + low). Characters removed are replaced with an ellipsis. + PS0 The value of this parameter is expanded (see PROMPTING below) and displayed by interactive + shells after reading a command and before the command is executed. + PS1 The value of this parameter is expanded (see PROMPTING below) and used as the primary prompt + string. The default value is ``\s-\v\$ ''. + PS2 The value of this parameter is expanded as with PS1 and used as the secondary prompt string. + The default is ``> ''. + PS3 The value of this parameter is used as the prompt for the select command (see SHELL GRAMMAR + above). + PS4 The value of this parameter is expanded as with PS1 and the value is printed before each com‐ + mand bash displays during an execution trace. The first character of the expanded value of + PS4 is replicated multiple times, as necessary, to indicate multiple levels of indirection. + The default is ``+ ''. + SHELL The full pathname to the shell is kept in this environment variable. If it is not set when + the shell starts, bash assigns to it the full pathname of the current user's login shell. + TIMEFORMAT + The value of this parameter is used as a format string specifying how the timing information + for pipelines prefixed with the time reserved word should be displayed. The % character in‐ + troduces an escape sequence that is expanded to a time value or other information. The es‐ + cape sequences and their meanings are as follows; the braces denote optional portions. + %% A literal %. + %[p][l]R The elapsed time in seconds. + %[p][l]U The number of CPU seconds spent in user mode. + %[p][l]S The number of CPU seconds spent in system mode. + %P The CPU percentage, computed as (%U + %S) / %R. + + The optional p is a digit specifying the precision, the number of fractional digits after a + decimal point. A value of 0 causes no decimal point or fraction to be output. At most three + places after the decimal point may be specified; values of p greater than 3 are changed to 3. + If p is not specified, the value 3 is used. + + The optional l specifies a longer format, including minutes, of the form MMmSS.FFs. The + value of p determines whether or not the fraction is included. + + If this variable is not set, bash acts as if it had the value + $'\nreal\t%3lR\nuser\t%3lU\nsys\t%3lS'. If the value is null, no timing information is dis‐ + played. A trailing newline is added when the format string is displayed. + TMOUT If set to a value greater than zero, TMOUT is treated as the default timeout for the read + builtin. The select command terminates if input does not arrive after TMOUT seconds when in‐ + put is coming from a terminal. In an interactive shell, the value is interpreted as the num‐ + ber of seconds to wait for a line of input after issuing the primary prompt. Bash terminates + after waiting for that number of seconds if a complete line of input does not arrive. + TMPDIR If set, bash uses its value as the name of a directory in which bash creates temporary files + for the shell's use. + auto_resume + This variable controls how the shell interacts with the user and job control. If this vari‐ + able is set, single word simple commands without redirections are treated as candidates for + resumption of an existing stopped job. There is no ambiguity allowed; if there is more than + one job beginning with the string typed, the job most recently accessed is selected. The + name of a stopped job, in this context, is the command line used to start it. If set to the + value exact, the string supplied must match the name of a stopped job exactly; if set to sub‐ + string, the string supplied needs to match a substring of the name of a stopped job. The + substring value provides functionality analogous to the %? job identifier (see JOB CONTROL + below). If set to any other value, the supplied string must be a prefix of a stopped job's + name; this provides functionality analogous to the %string job identifier. + histchars + The two or three characters which control history expansion and tokenization (see HISTORY EX‐ + PANSION below). The first character is the history expansion character, the character which + signals the start of a history expansion, normally `!'. The second character is the quick + substitution character, which is used as shorthand for re-running the previous command en‐ + tered, substituting one string for another in the command. The default is `^'. The optional + third character is the character which indicates that the remainder of the line is a comment + when found as the first character of a word, normally `#'. The history comment character + causes history substitution to be skipped for the remaining words on the line. It does not + necessarily cause the shell parser to treat the rest of the line as a comment. + + Arrays + Bash provides one-dimensional indexed and associative array variables. Any variable may be used as + an indexed array; the declare builtin will explicitly declare an array. There is no maximum limit + on the size of an array, nor any requirement that members be indexed or assigned contiguously. In‐ + dexed arrays are referenced using integers (including arithmetic expressions) and are zero-based; + associative arrays are referenced using arbitrary strings. Unless otherwise noted, indexed array + indices must be non-negative integers. + + An indexed array is created automatically if any variable is assigned to using the syntax name[sub‐ + script]=value. The subscript is treated as an arithmetic expression that must evaluate to a number. + To explicitly declare an indexed array, use declare -a name (see SHELL BUILTIN COMMANDS below). de‐ + clare -a name[subscript] is also accepted; the subscript is ignored. + + Associative arrays are created using declare -A name. + + Attributes may be specified for an array variable using the declare and readonly builtins. Each at‐ + tribute applies to all members of an array. + + Arrays are assigned to using compound assignments of the form name=(value1 ... valuen), where each + value is of the form [subscript]=string. Indexed array assignments do not require anything but + string. When assigning to indexed arrays, if the optional brackets and subscript are supplied, that + index is assigned to; otherwise the index of the element assigned is the last index assigned to by + the statement plus one. Indexing starts at zero. + + When assigning to an associative array, the subscript is required. + + This syntax is also accepted by the declare builtin. Individual array elements may be assigned to + using the name[subscript]=value syntax introduced above. When assigning to an indexed array, if + name is subscripted by a negative number, that number is interpreted as relative to one greater than + the maximum index of name, so negative indices count back from the end of the array, and an index of + -1 references the last element. + + Any element of an array may be referenced using ${name[subscript]}. The braces are required to + avoid conflicts with pathname expansion. If subscript is @ or *, the word expands to all members of + name. These subscripts differ only when the word appears within double quotes. If the word is dou‐ + ble-quoted, ${name[*]} expands to a single word with the value of each array member separated by the + first character of the IFS special variable, and ${name[@]} expands each element of name to a sepa‐ + rate word. When there are no array members, ${name[@]} expands to nothing. If the double-quoted + expansion occurs within a word, the expansion of the first parameter is joined with the beginning + part of the original word, and the expansion of the last parameter is joined with the last part of + the original word. This is analogous to the expansion of the special parameters * and @ (see Spe‐ + cial Parameters above). ${#name[subscript]} expands to the length of ${name[subscript]}. If sub‐ + script is * or @, the expansion is the number of elements in the array. If the subscript used to + reference an element of an indexed array evaluates to a number less than zero, it is interpreted as + relative to one greater than the maximum index of the array, so negative indices count back from the + end of the array, and an index of -1 references the last element. + + Referencing an array variable without a subscript is equivalent to referencing the array with a sub‐ + script of 0. Any reference to a variable using a valid subscript is legal, and bash will create an + array if necessary. + + An array variable is considered set if a subscript has been assigned a value. The null string is a + valid value. + + It is possible to obtain the keys (indices) of an array as well as the values. ${!name[@]} and + ${!name[*]} expand to the indices assigned in array variable name. The treatment when in double + quotes is similar to the expansion of the special parameters @ and * within double quotes. + + The unset builtin is used to destroy arrays. unset name[subscript] destroys the array element at + index subscript, for both indexed and associative arrays. Negative subscripts to indexed arrays are + interpreted as described above. Unsetting the last element of an array variable does not unset the + variable. unset name, where name is an array, or unset name[subscript], where subscript is * or @, + removes the entire array. + + When using a variable name with a subscript as an argument to a command, such as with unset, without + using the word expansion syntax described above, the argument is subject to pathname expansion. If + pathname expansion is not desired, the argument should be quoted. + + The declare, local, and readonly builtins each accept a -a option to specify an indexed array and a + -A option to specify an associative array. If both options are supplied, -A takes precedence. The + read builtin accepts a -a option to assign a list of words read from the standard input to an array. + The set and declare builtins display array values in a way that allows them to be reused as assign‐ + ments. + +EXPANSION + Expansion is performed on the command line after it has been split into words. There are seven + kinds of expansion performed: brace expansion, tilde expansion, parameter and variable expansion, + command substitution, arithmetic expansion, word splitting, and pathname expansion. + + The 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; + and pathname expansion. + + 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 com‐ + mand substitution. + + After these expansions are performed, quote characters present in the original word are removed un‐ + less they have been quoted themselves (quote removal). + + Only brace expansion, word splitting, and pathname 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 "${name[@]}", and, in most cases, $* and ${name[*]} as explained above + (see PARAMETERS). + + Brace Expansion + Brace expansion is a mechanism by which arbitrary strings may be generated. This mechanism is simi‐ + lar to pathname expansion, but the filenames generated need not exist. Patterns to be brace ex‐ + panded take the form of 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; left to right + order is preserved. For example, a{d,c,b}e expands into `ade ace abe'. + + A sequence expression takes the form {x..y[..incr]}, where x and y are either integers or single + characters, and incr, an optional increment, is an integer. When integers are supplied, the expres‐ + sion expands to each number between x and y, inclusive. Supplied integers may be prefixed with 0 to + force each term to have the same width. When either x or y begins with a zero, the shell attempts + to force all generated terms to contain the same number of digits, zero-padding where necessary. + When characters are supplied, the expression expands to each character lexicographically between x + and y, inclusive, using the default C locale. Note that both x and y must be of the same type. + When the increment is supplied, it is used as the difference between each term. The default incre‐ + ment is 1 or -1 as appropriate. + + Brace expansion is performed before any other expansions, and any characters special to other expan‐ + sions are preserved in the result. It is strictly textual. Bash does not apply any syntactic in‐ + terpretation 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. The same word is output as file1 + file2 after expansion by bash. If strict compatibility with sh is desired, start bash with the +B + option or disable brace expansion with the +B option to the set command (see SHELL BUILTIN COMMANDS + below). + + Tilde Expansion + If a word begins with an unquoted tilde character (`~'), all of the characters preceding the first + unquoted slash (or all characters, if there is no unquoted slash) are considered a tilde-prefix. If + none of the characters in the tilde-prefix are quoted, the 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 shell parameter HOME. If HOME is unset, the home directory of the + user executing the shell is substituted instead. Otherwise, the tilde-prefix is replaced with the + home directory associated with the specified login name. + + If the tilde-prefix is a `~+', the value of the shell variable PWD replaces the tilde-prefix. If + the tilde-prefix is a `~-', the value of the shell variable OLDPWD, if it is set, is substituted. + 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 tilde-prefix as an argument. + If the characters following the tilde in the tilde-prefix consist of a number without a leading `+' + or `-', `+' is assumed. + + If the login name is invalid, or the tilde expansion fails, the word is unchanged. + + Each variable assignment is checked for unquoted tilde-prefixes immediately following a : or the + first =. In these cases, tilde expansion is also performed. Consequently, one may use filenames + with tildes in assignments to PATH, MAILPATH, and CDPATH, and the shell assigns the expanded value. + + Bash also performs tilde expansion on words satisfying the conditions of variable assignments (as + described above under PARAMETERS) when they appear as arguments to simple commands. Bash does not + do this, except for the declaration commands listed above, when in posix mode. + + Parameter Expansion + The `$' 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 in‐ + terpreted as part of the name. + + When braces are used, the matching ending brace is the first `}' not escaped by a backslash or + within a quoted string, and not within an embedded arithmetic expansion, command substitution, or + parameter expansion. + + ${parameter} + The value of parameter is substituted. The braces are required when parameter is a posi‐ + tional parameter with more than one digit, or when parameter is followed by a character which + is not to be interpreted as part of its name. The parameter is a shell parameter as de‐ + scribed above PARAMETERS) or an array reference (Arrays). + + If the first character of parameter is an exclamation point (!), and parameter is not a nameref, it + introduces a level of indirection. Bash uses the value formed by expanding the rest of parameter as + the new parameter; this 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 parameter referenced by parameter instead of + performing the complete indirect expansion. The exceptions to this are the expansions of ${!pre‐ + fix*} and ${!name[@]} described below. The exclamation point must immediately follow the left brace + in order to introduce indirection. + + In each of the cases below, word is subject to tilde expansion, parameter expansion, command substi‐ + tution, and arithmetic expansion. + + When not performing substring expansion, using the forms documented below (e.g., :-), bash tests for + a parameter that is unset or null. Omitting the colon results in a test only for a parameter that + is unset. + + ${parameter:-word} + Use Default Values. If parameter is unset or null, the expansion of word is substituted. + Otherwise, the value of parameter is substituted. + ${parameter:=word} + Assign Default Values. If parameter is unset or null, the expansion of word is assigned to + parameter. The value of parameter is then substituted. Positional parameters and special + parameters may not be assigned to in this way. + ${parameter:?word} + Display Error if Null or Unset. If parameter is null or unset, the expansion of word (or a + message to that effect if word is not present) is written to the standard error and the + shell, if it is not interactive, exits. Otherwise, the value of parameter is substituted. + ${parameter:+word} + Use Alternate Value. If parameter is null or unset, nothing is substituted, otherwise the + expansion of word is substituted. + ${parameter:offset} + ${parameter:offset:length} + Substring Expansion. Expands to up to length characters of the value of parameter starting + at the character specified by offset. If parameter is @, an indexed array subscripted by @ + or *, or an associative array name, the results differ as described below. If length is + omitted, expands to the substring of the value of parameter starting at the character speci‐ + fied by offset and extending to the end of the value. length and offset are arithmetic ex‐ + pressions (see ARITHMETIC EVALUATION below). + + If offset evaluates to a number less than zero, the value is used as an offset in characters + from the end of the value 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. + + If parameter is @, the result is length positional parameters beginning at offset. A nega‐ + tive offset is taken relative to one greater than the greatest positional parameter, so an + offset of -1 evaluates to the last positional parameter. It is an expansion error if length + evaluates to a number less than zero. + + If parameter is an indexed array name subscripted by @ or *, the result is the length members + of the array beginning with ${parameter[offset]}. A negative offset is taken relative to one + greater than the maximum index of the specified array. It is an expansion error if length + evaluates to a number less than zero. + + Substring expansion applied to an associative array produces undefined results. + + Substring indexing is zero-based unless the positional parameters are used, in which case the + indexing starts at 1 by default. If offset is 0, and the positional parameters are used, $0 + is prefixed to the list. + + ${!prefix*} + ${!prefix@} + Names matching prefix. Expands to the names of variables whose names begin with prefix, sep‐ + arated 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[*]} + List of array keys. 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 oth‐ + erwise. When @ is used and the expansion appears within double quotes, each key expands to a + separate word. + + ${#parameter} + Parameter length. The length in characters of the value of parameter is substituted. If pa‐ + rameter is * or @, the value substituted is the number of positional parameters. If parame‐ + ter 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 neg‐ + ative indices count back from the end of the array, and an index of -1 references the last + element. + + ${parameter#word} + ${parameter##word} + Remove matching prefix pattern. The word is expanded to produce a pattern just as in path‐ + name expansion, and matched against the expanded value of parameter using the rules described + under Pattern Matching below. If the pattern matches the beginning of the value of parame‐ + ter, 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 sub‐ + scripted 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} + Remove matching suffix pattern. The word is expanded to produce a pattern just as in path‐ + name expansion, and matched against the expanded value of parameter using the rules described + under Pattern Matching below. If the pattern matches a trailing portion of the expanded + 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 po‐ + sitional parameter in turn, and the expansion is the resultant list. If parameter is an ar‐ + ray 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} + Pattern substitution. The pattern is expanded to produce a pattern just as in pathname ex‐ + pansion, Parameter is expanded and the longest match of pattern against its value is replaced + with string. The match is performed using the rules described under Pattern Matching below. + If pattern begins with /, all matches of pattern are replaced with string. Normally only the + first match is replaced. If pattern begins with #, it must match at the beginning of the ex‐ + panded value of parameter. If pattern begins with %, it must match at the end of the ex‐ + panded value of parameter. If string is null, matches of pattern are deleted and the / fol‐ + lowing pattern may be omitted. If the nocasematch shell option is enabled, the match is per‐ + formed without regard to the case of alphabetic characters. If parameter is @ or *, the sub‐ + stitution 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. + + ${parameter^pattern} + ${parameter^^pattern} + ${parameter,pattern} + ${parameter,,pattern} + Case modification. This expansion modifies the case of alphabetic characters in parameter. + The pattern is expanded to produce a pattern just as in pathname expansion. Each character + in the expanded value of parameter is tested against pattern, and, if it matches the pattern, + its case is converted. The pattern should not attempt to match more than one character. The + ^ operator converts lowercase letters matching pattern to uppercase; the , operator converts + matching uppercase letters to lowercase. The ^^ and ,, expansions convert each matched char‐ + acter in the expanded value; the ^ and , expansions match and convert only the first charac‐ + ter in the expanded value. If pattern is omitted, it is treated like a ?, which matches ev‐ + ery 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} + Parameter transformation. 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: + + Q The expansion is a string that is the value of parameter quoted in a format that can + be reused as input. + E The expansion is a string that is the value of parameter with backslash escape se‐ + quences expanded as with the $'...' quoting mechanism. + P The expansion is a string that is the result of expanding the value of parameter as if + it were a prompt string (see PROMPTING below). + A The expansion is a string in the form of an assignment statement or declare command + that, if evaluated, will recreate parameter with its attributes and value. + a The expansion is a string consisting of flag values representing parameter's at‐ + tributes. + + If 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 re‐ + sultant list. + + The result of the expansion is subject to word splitting and pathname expansion as described + below. + + Command Substitution + Command substitution allows the output of a command to replace the command name. There are two + forms: + + $(command) + or + `command` + + Bash performs the expansion by executing command in a subshell environment and replacing the command + substitution with the 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). + + When the old-style backquote form of substitution is used, backslash retains its literal meaning ex‐ + cept 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. + + Command substitutions may be nested. To nest when using the backquoted form, escape the inner back‐ + quotes with backslashes. + + If the substitution appears within double quotes, word splitting and pathname expansion are not per‐ + formed on the results. + + Arithmetic Expansion + Arithmetic expansion allows the evaluation of an arithmetic expression and the substitution of the + result. The format for arithmetic expansion is: + + $((expression)) + + The old format $[expression] is deprecated and will be removed in upcoming versions of bash. + + The expression is treated as if it were within double quotes, but a double quote inside the paren‐ + theses is not treated specially. All tokens in the expression undergo parameter and variable expan‐ + sion, command substitution, and quote removal. The result is treated as the arithmetic expression + to be evaluated. Arithmetic expansions may be nested. + + The evaluation is performed according to the rules listed below under ARITHMETIC EVALUATION. If ex‐ + pression is invalid, bash prints a message indicating failure and no substitution occurs. + + Process Substitution + Process substitution allows a process's input or output to be referred to using a filename. It + takes the form of <(list) or >(list). The process list is run asynchronously, and its input or out‐ + put appears as a filename. This filename is passed as an argument to the current command as the re‐ + sult of the expansion. If the >(list) form is used, writing to the file will provide input for + list. If the <(list) form is used, the file passed as an argument should be read to obtain the out‐ + put of list. 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 expan‐ + sion, command substitution, and arithmetic expansion. + + Word Splitting + The shell scans the results of parameter expansion, command substitution, and arithmetic expansion + that did not occur within double quotes for word splitting. + + The shell treats each character of IFS as a delimiter, and splits the results of the other expan‐ + sions into words using these characters as field terminators. If IFS is unset, or its value is ex‐ + actly , the default, then sequences of , , and at the be‐ + ginning and end of the results of the previous expansions are ignored, and any sequence of IFS char‐ + acters not at the beginning or end serves to delimit words. If IFS has a value other than the de‐ + fault, then sequences of the whitespace characters space, tab, and newline are ignored at the begin‐ + ning and end of the word, as long as the whitespace character is in the value of IFS (an IFS white‐ + space character). Any character in IFS that is not IFS whitespace, along with any adjacent IFS + whitespace characters, delimits a field. A sequence of IFS whitespace characters is also treated as + a delimiter. If the value of IFS is null, no word splitting occurs. + + Explicit null arguments ("" or '') are retained and passed to commands as empty strings. Unquoted + implicit null arguments, resulting from the expansion of parameters that have no values, are re‐ + moved. If a parameter with no value is expanded within double quotes, a null argument results and + 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, the null argument is removed. That is, the word -d'' becomes + -d after word splitting and null argument removal. + + Note that if no expansion occurs, no splitting is performed. + + Pathname Expansion + After word splitting, unless the -f option has been set, bash scans each word for the characters *, + ?, and [. If one of these characters appears, then the word is regarded as a pattern, and replaced + with an alphabetically sorted list of filenames matching the pattern (see Pattern Matching below). + If no matching filenames are found, and the shell option nullglob is not enabled, 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, an error message is printed and the command + is not executed. If the shell option nocaseglob is enabled, the match is performed without regard + to the case of alphabetic characters. Note that when using range expressions like [a-z] (see be‐ + low), letters of the other case may be included, depending on the setting of LC_COLLATE. When a + pattern is used for pathname expansion, the character ``.'' at the start of a name or immediately + following a slash must be matched explicitly, unless the shell option dotglob is set. The filenames + ``.'' and ``..'' must always be matched explicitly, even if dotglob is set. In other cases, the + ``.'' character is not treated specially. When matching a pathname, the slash character must al‐ + ways 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 under Pattern Matching. See the descrip‐ + tion of shopt below under SHELL BUILTIN COMMANDS for a description of the nocaseglob, nullglob, + failglob, and dotglob shell options. + + The GLOBIGNORE shell variable may be used to restrict the set of file names matching a pattern. If + GLOBIGNORE is set, each matching 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 pat‐ + terns in GLOBIGNORE is performed without regard to case. The filenames ``.'' and ``..'' are al‐ + ways 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 ``.'' + will 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 pat‐ + tern matching honors the setting of the extglob shell option. + + Pattern Matching + + Any 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: + + * Matches any string, including the null string. When the globstar shell option is en‐ + abled, and * is used in a pathname expansion context, two adjacent *s used as a single + pattern will match all files and zero or more directories and subdirectories. If fol‐ + lowed by a /, two adjacent *s will match only directories and subdirectories. + ? Matches any single character. + [...] Matches any one of the enclosed characters. A pair of characters separated by a hy‐ + phen denotes a range expression; any character that falls between those two charac‐ + ters, inclusive, using the current locale's collating sequence and character set, is + matched. If the first character following the [ is a ! or a ^ then any character not + enclosed is matched. The sorting order of characters in range expressions is deter‐ + mined by the current locale and the values of the LC_COLLATE or LC_ALL shell vari‐ + ables, if set. To obtain the traditional interpretation of range expressions, where + [a-d] is equivalent to [abcd], set value of the LC_ALL shell variable to C, or enable + the globasciiranges shell option. A - may be matched by including it as the first or + last character in the set. A ] may be matched by including it as the first character + in the set. + + Within [ and ], 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 _. + + Within [ and ], an equivalence class can be specified using the syntax [=c=], which + matches all characters with the same collation weight (as defined by the current lo‐ + cale) as the character c. + + Within [ and ], the syntax [.symbol.] matches the collating symbol symbol. + + If the extglob shell option is enabled using the shopt builtin, several extended pattern matching + operators are recognized. In the following description, a pattern-list is a list of one or more + patterns separated by a |. 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 + *(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 + + 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. + + Quote Removal + After the preceding expansions, all unquoted occurrences of the characters \, ', and " that did not + result from one of the above expansions are removed. + +REDIRECTION + Before a command is executed, its input and output may be redirected using a special notation inter‐ + preted by the shell. Redirection allows commands' file handles to be duplicated, opened, closed, + made to refer to different files, and can change the files the command reads from and writes to. + Redirection may also be used to modify file handles in the current shell execution environment. The + following redirection operators may precede or appear anywhere within a simple command or may follow + a command. Redirections are processed in the order they appear, from left to right. + + Each redirection that may be preceded by a file descriptor number may instead be preceded by a word + of the form {varname}. In this case, for each redirection operator except >&- and <&-, the shell + will allocate a file descriptor greater than or equal to 10 and assign it to varname. If >&- or <&- + is preceded by {varname}, the value of varname defines the file descriptor to close. If {varname} + is supplied, the redirection persists beyond the scope of the command, allowing the shell programmer + to manage the file descriptor himself. + + In the following descriptions, if the file descriptor number is omitted, and the first character of + the redirection operator is <, the redirection refers to the standard input (file descriptor 0). If + the first character of the redirection operator is >, the redirection refers to the standard output + (file descriptor 1). + + The word following the redirection operator in the following descriptions, unless otherwise noted, + is subjected to brace expansion, tilde expansion, parameter and variable expansion, command substi‐ + tution, arithmetic expansion, quote removal, pathname expansion, and word splitting. If it expands + to more than one word, bash reports an error. + + Note that the order of redirections is significant. For example, the command + + ls > dirlist 2>&1 + + directs both standard output and standard error to the file dirlist, while the command + + ls 2>&1 > dirlist + + directs only the standard output to file dirlist, because the standard error was duplicated from the + standard output before the standard output was redirected to dirlist. + + Bash handles several filenames specially when they are used in redirections, as described in the + following table. If the operating system on which bash is running provides these special files, + bash will use them; otherwise it will emulate them internally with the behavior described below. + + /dev/fd/fd + If fd is a valid integer, file descriptor fd is duplicated. + /dev/stdin + File descriptor 0 is duplicated. + /dev/stdout + File descriptor 1 is duplicated. + /dev/stderr + File descriptor 2 is duplicated. + /dev/tcp/host/port + If host is a valid hostname or Internet address, and port is an integer port number or + service name, bash attempts to open the corresponding TCP socket. + /dev/udp/host/port + If host is a valid hostname or Internet address, and port is an integer port number or + service name, bash attempts to open the corresponding UDP socket. + + A failure to open or create a file causes the redirection to fail. + + Redirections using file descriptors greater than 9 should be used with care, as they may conflict + with file descriptors the shell uses internally. + + Note that the exec builtin command can make redirections take effect in the current shell. + + Redirecting Input + Redirection of input causes the file whose name results from the expansion of word to be opened for + reading on file descriptor n, or the standard input (file descriptor 0) if n is not specified. + + The general format for redirecting input is: + + [n]word + + If the redirection operator is >, and the noclobber option to the set builtin has been enabled, the + redirection will fail if the file whose name results from the expansion of word exists and is a reg‐ + ular file. If the redirection operator is >|, or the redirection operator is > and the noclobber + option to the set builtin command is not enabled, the redirection is attempted even if the file + named by word exists. + + Appending Redirected Output + Redirection of output in this fashion causes the file whose name results from the expansion of word + to be opened for appending on file descriptor n, or the standard output (file descriptor 1) if n is + not specified. If the file does not exist it is created. + + The general format for appending output is: + + [n]>>word + + Redirecting Standard Output and Standard Error + This construct allows both the standard output (file descriptor 1) and the standard error output + (file descriptor 2) to be redirected to the file whose name is the expansion of word. + + There are two formats for redirecting standard output and standard error: + + &>word + and + >&word + + Of the two forms, the first is preferred. This is semantically equivalent to + + >word 2>&1 + + When using the second form, word may not expand to a number or -. If it does, other redirection op‐ + erators apply (see Duplicating File Descriptors below) for compatibility reasons. + + Appending Standard Output and Standard Error + This construct allows both the standard output (file descriptor 1) and the standard error output + (file descriptor 2) to be appended to the file whose name is the expansion of word. + + The format for appending standard output and standard error is: + + &>>word + + This is semantically equivalent to + + >>word 2>&1 + + (see Duplicating File Descriptors below). + + Here Documents + This type of redirection instructs the shell to read input from the current source until a line con‐ + taining only delimiter (with no trailing blanks) is seen. All of the lines read up to that point + are then used as the standard input (or file descriptor n if n is specified) for a command. + + The format of here-documents is: + + [n]<<[-]word + here-document + delimiter + + No parameter and variable expansion, command substitution, arithmetic expansion, or pathname expan‐ + sion is performed on word. If any part of word is quoted, the delimiter is the result of quote re‐ + moval on word, and the lines in the here-document are not expanded. If word is unquoted, all lines + of the here-document are subjected to parameter expansion, command substitution, and arithmetic ex‐ + pansion, the character sequence \ is ignored, and \ must be used to quote the characters \, + $, and `. + + If the redirection operator is <<-, then all leading tab characters are stripped from input lines + and the line containing delimiter. This allows here-documents within shell scripts to be indented + in a natural fashion. + + Here Strings + A variant of here documents, the format is: + + [n]<<&word + + is used similarly to duplicate output file descriptors. If n is not specified, the standard output + (file descriptor 1) is used. If the digits in word do not specify a file descriptor open for out‐ + put, a redirection error occurs. If word evaluates to -, file descriptor n is closed. As a special + case, if n is omitted, and word does not expand to one or more digits or -, the standard output and + standard error are redirected as described previously. + + Moving File Descriptors + The redirection operator + + [n]<&digit- + + moves the file descriptor digit to file descriptor n, or the standard input (file descriptor 0) if n + is not specified. digit is closed after being duplicated to n. + + Similarly, the redirection operator + + [n]>&digit- + + moves the file descriptor digit to file descriptor n, or the standard output (file descriptor 1) if + n is not specified. + + Opening File Descriptors for Reading and Writing + The redirection operator + + [n]<>word + + causes the file whose name is the expansion of word to be opened for both reading and writing on + file descriptor n, or on file descriptor 0 if n is not specified. If the file does not exist, it is + created. + +ALIASES + Aliases allow a string to be substituted for a word when it is used as the first word of a simple + command. The shell maintains a list of aliases that may be set and unset with the alias and unalias + builtin commands (see SHELL BUILTIN COMMANDS below). The first word of each simple command, if un‐ + quoted, is checked to see if it has an alias. If so, that word is replaced by the text of the + alias. The characters /, $, `, and = and any of the shell metacharacters or quoting characters + listed above may not appear in an alias name. The replacement text may contain any valid shell in‐ + put, including shell metacharacters. The first word of the replacement text is tested for aliases, + but a word that is identical to an alias being expanded is not expanded a second time. This means + that one may alias ls to ls -F, for instance, and bash does not try to recursively expand the re‐ + placement text. If the last character of the alias value is a blank, then the next command word + following the alias is also checked for alias expansion. + + Aliases are created and listed with the alias command, and removed with the unalias command. + + There is no mechanism for using arguments in the replacement text. If arguments are needed, a shell + function should be used (see FUNCTIONS below). + + Aliases are not expanded when the shell is not interactive, unless the expand_aliases shell option + is set using shopt (see the description of shopt under SHELL BUILTIN COMMANDS below). + + The rules concerning the definition and use of aliases are somewhat confusing. Bash always reads at + least one complete line of input, and all lines that make up a compound command, before executing + any of the commands on that line or the compound command. Aliases are expanded when a command is + read, not when it is executed. Therefore, an alias definition appearing on the same line as another + command does not take effect until the next line of input is read. The commands following the alias + definition on that line are not affected by the new alias. This behavior is also an issue when + functions are executed. Aliases are expanded when a function definition is read, not when the func‐ + tion is executed, because a function definition is itself a command. As a consequence, aliases de‐ + fined in a function are not available until after that function is executed. To be safe, always put + alias definitions on a separate line, and do not use alias in compound commands. + + For almost every purpose, aliases are superseded by shell functions. + +FUNCTIONS + A shell function, defined as described above under SHELL GRAMMAR, stores a series of commands for + later execution. When the name of a shell function is used as a simple command name, the list of + commands associated with that function name is executed. Functions are executed in the context of + the current shell; no new process is 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 # is updated to reflect the change. 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 (see the description of the trap builtin under + SHELL BUILTIN COMMANDS below) are not inherited unless the function has been given the trace attri‐ + bute (see the description of the declare builtin below) or the -o functrace shell option 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. + + Variables local to the function may be declared with the local builtin command. Ordinarily, vari‐ + ables and their values are shared between the function and its caller. If a variable is declared + local, the variable's visible scope is restricted to that function and its children (including the + functions it calls). Local variables "shadow" variables with the same name declared at previous + scopes. For instance, a local variable declared in a function hides a global variable of the same + name: references and assignments refer to the local variable, leaving the global variable unmodi‐ + fied. 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 function sees de‐ + pends on its value within its caller, if any, whether that caller is the "global" scope 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 func‐ + tion func2, references to var made from within func2 will resolve to the local variable var from + func1, shadowing any global variable named var. + + The unset builtin also acts using the same dynamic scope: if a variable is local to the current + scope, unset will unset 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 will remain so un‐ + til it is reset in that scope or until the function returns. Once the function returns, any in‐ + stance of the variable at a previous scope will become visible. If the unset acts on a variable at + a previous scope, any instance of a variable with that name that had been shadowed will become visi‐ + ble. + + The FUNCNEST variable, if set to a numeric value greater than 0, defines a maximum function nesting + level. Function invocations that exceed the limit cause the entire command to abort. + + If the builtin command return is executed in a function, the function completes and execution re‐ + sumes 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 parame‐ + ters and the special parameter # are restored to the values they had prior to the function's execu‐ + tion. + + Function names and definitions may be listed with the -f option to the declare or typeset builtin + commands. The -F option to declare or typeset will list the function names only (and optionally the + source file and line number, if the extdebug shell option is enabled). Functions may be exported so + that subshells automatically have them defined with the -f option to the export builtin. A function + definition may be deleted using the -f option to the unset builtin. + + 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, no limit is imposed on the + number of recursive calls. + +ARITHMETIC EVALUATION + The shell allows arithmetic expressions to be evaluated, under certain circumstances (see the let + and declare builtin commands, the (( compound command, and Arithmetic Expansion). Evaluation is + done in fixed-width integers with no check for overflow, though division by 0 is trapped and flagged + as an error. The operators and their precedence, associativity, and values are the same as in the C + language. The following list of operators is grouped into levels of equal-precedence operators. + The levels are listed in order of decreasing precedence. + + id++ id-- + variable post-increment and post-decrement + - + unary minus and plus + ++id --id + variable pre-increment and pre-decrement + ! ~ logical and bitwise negation + ** exponentiation + * / % multiplication, division, remainder + + - addition, subtraction + << >> left and right bitwise shifts + <= >= < > + comparison + == != equality and inequality + & bitwise AND + ^ bitwise exclusive OR + | bitwise OR + && logical AND + || logical OR + expr?expr:expr + conditional operator + = *= /= %= += -= <<= >>= &= ^= |= + assignment + expr1 , expr2 + comma + + Shell variables are allowed as operands; parameter expansion is performed before the expression is + evaluated. Within an expression, shell variables may also be referenced by name without using the + parameter expansion syntax. A shell variable that is null or unset evaluates to 0 when referenced + by name without using the parameter expansion syntax. The value of a variable is evaluated as an + arithmetic expression when it is referenced, or when a variable which has been given the integer at‐ + tribute using declare -i is assigned a value. A null value evaluates to 0. A shell variable need + not have its integer attribute turned on to be used in an expression. + + Constants with a leading 0 are interpreted as octal numbers. A leading 0x or 0X denotes hexadeci‐ + mal. Otherwise, numbers take the form [base#]n, where the optional base is a decimal number between + 2 and 64 representing the arithmetic base, and n is a number in that base. If base# is omitted, + then base 10 is used. When specifying n, the digits greater than 9 are represented by the lowercase + letters, the uppercase letters, @, and _, in that order. If base is less than or equal to 36, low‐ + ercase and uppercase letters may be used interchangeably to represent numbers between 10 and 35. + + Operators are evaluated in order of precedence. Sub-expressions in parentheses are evaluated first + and may override the precedence rules above. + +CONDITIONAL EXPRESSIONS + Conditional expressions are used by the [[ compound command and the test and [ builtin commands to + test file attributes and perform string and arithmetic comparisons. The test abd [ commands deter‐ + mine their behavior based on the number of arguments; see the descriptions of those commands for any + other command-specific actions. + + Expressions are formed from the following unary or binary primaries. Bash handles several filenames + specially when they are used in expressions. If the operating system on which bash is running pro‐ + vides these special files, bash will use them; otherwise it will emulate them internally with this + behavior: If any file argument to one of the primaries is of the form /dev/fd/n, then file descrip‐ + tor n is checked. If the file argument to one of the primaries is one of /dev/stdin, /dev/stdout, + or /dev/stderr, file descriptor 0, 1, or 2, respectively, is checked. + + Unless otherwise specified, primaries that operate on files follow symbolic links and operate on the + target of the link, rather than the link itself. + + When used with [[, the < and > operators sort lexicographically using the current locale. The test + command sorts using ASCII ordering. + + -a file + True if file exists. + -b file + True if file exists and is a block special file. + -c file + True if file exists and is a character special file. + -d file + True if file exists and is a directory. + -e file + True if file exists. + -f file + True if file exists and is a regular file. + -g file + True if file exists and is set-group-id. + -h file + True if file exists and is a symbolic link. + -k file + True if file exists and its ``sticky'' bit is set. + -p file + True if file exists and is a named pipe (FIFO). + -r file + True if file exists and is readable. + -s file + True if file exists and has a size greater than zero. + -t fd True if file descriptor fd is open and refers to a terminal. + -u file + True if file exists and its set-user-id bit is set. + -w file + True if file exists and is writable. + -x file + True if file exists and is executable. + -G file + True if file exists and is owned by the effective group id. + -L file + True if file exists and is a symbolic link. + -N file + True if file exists and has been modified since it was last read. + -O file + True if file exists and is owned by the effective user id. + -S file + True if file exists and is a socket. + file1 -ef file2 + True if file1 and file2 refer to the same device and inode numbers. + file1 -nt file2 + True if file1 is newer (according to modification date) than file2, or if file1 exists and + file2 does not. + file1 -ot file2 + True if file1 is older than file2, or if file2 exists and file1 does not. + -o optname + True if the shell option optname is enabled. See the list of options under the description + of the -o option to the set builtin below. + -v varname + True if the shell variable varname is set (has been assigned a value). + -R varname + True if the shell variable varname is set and is a name reference. + -z string + True if the length of string is zero. + string + -n string + True if the length of string is non-zero. + + string1 == string2 + string1 = string2 + True if the strings are equal. = should be used with the test command for POSIX conformance. + When used with the [[ command, this performs pattern matching as described above (Compound + Commands). + + string1 != string2 + True if the strings are not equal. + + string1 < string2 + True if string1 sorts before string2 lexicographically. + + string1 > string2 + True if string1 sorts after string2 lexicographically. + + arg1 OP arg2 + OP is one of -eq, -ne, -lt, -le, -gt, or -ge. These arithmetic binary operators return true + if arg1 is equal to, not equal to, less than, less than or equal to, greater than, or greater + than or equal to arg2, respectively. Arg1 and arg2 may be positive or negative integers. + When used with the [[ command, Arg1 and Arg2 are evaluated as arithmetic expressions (see + ARITHMETIC EVALUATION above). + +SIMPLE COMMAND EXPANSION + When a simple command is executed, the shell performs the following expansions, assignments, and + redirections, from left to right. + + 1. The words that the parser has marked as variable assignments (those preceding the command + name) and redirections are saved for later processing. + + 2. The words that are not variable assignments or redirections are expanded. If any words re‐ + main after expansion, the first word is taken to be the name of the command and the remaining + words are the arguments. + + 3. Redirections are performed as described above under REDIRECTION. + + 4. The text after the = in each variable assignment undergoes tilde expansion, parameter expan‐ + sion, command substitution, arithmetic expansion, and quote removal before being assigned to + the variable. + + If no command name results, the variable assignments affect the current shell environment. Other‐ + wise, the variables are added to the environment of the executed command and do not affect the cur‐ + rent shell environment. If any of the assignments attempts to assign a value to a readonly vari‐ + able, an error occurs, and the command exits with a non-zero status. + + If no command name results, redirections are performed, but do not affect the current shell environ‐ + ment. A redirection error causes the command to exit with a non-zero status. + + If there is a command name left after expansion, execution proceeds as described below. Otherwise, + the command exits. If one of the expansions contained a command substitution, the exit status of + the command is the exit status of the last command substitution performed. If there were no command + substitutions, the command exits with a status of zero. + +COMMAND EXECUTION + After a command has been split into words, if it results in a simple command and an optional list of + arguments, the following actions are taken. + + If the command name contains no slashes, the shell attempts to locate it. If there exists a shell + function by that name, that function is invoked as described above in FUNCTIONS. If the name does + not match a function, the shell searches for it in the list of shell builtins. If a match is found, + that builtin is invoked. + + If the name is neither a shell function nor a builtin, and contains no slashes, bash searches each + element of the PATH for a directory containing an executable file by that name. Bash uses a hash + table to remember the full pathnames of executable files (see hash under SHELL BUILTIN COMMANDS be‐ + low). A full search of the directories in PATH is performed only if the command is not found in the + hash table. If the search is unsuccessful, the shell searches for a defined shell function named + command_not_found_handle. If that function exists, it is invoked in a separate execution environ‐ + ment with the original command and the original command's arguments as its arguments, and the func‐ + tion's exit status becomes the exit status of that subshell. If that function is not defined, the + shell prints an error message and returns an exit status of 127. + + If the search is successful, or if the command name contains one or more slashes, the shell executes + the named program in a separate execution environment. Argument 0 is set to the name given, and the + remaining arguments to the command are set to the arguments given, if any. + + If this execution fails because the file is not in executable format, and the file is not a direc‐ + tory, it is assumed to be a shell script, a file containing shell commands. A subshell is spawned + to execute it. This subshell reinitializes itself, so that the effect is as if a new shell had been + invoked to handle the script, with the exception that the locations of commands remembered by the + parent (see hash below under SHELL BUILTIN COMMANDS) are retained by the child. + + If the program is a file beginning with #!, the remainder of the first line specifies an interpreter + for the program. The shell executes the specified interpreter on operating systems that do not han‐ + dle this executable format themselves. The arguments to the interpreter consist of a single op‐ + tional argument following the interpreter name on the first line of the program, followed by the + name of the program, followed by the command arguments, if any. + +COMMAND EXECUTION ENVIRONMENT + The shell has an execution environment, which consists of the following: + + • open files inherited by the shell at invocation, as modified by redirections supplied to the + exec builtin + + • the current working directory as set by cd, pushd, or popd, or inherited by the shell at in‐ + vocation + + • the file creation mode mask as set by umask or inherited from the shell's parent + + • current traps set by trap + + • shell parameters that are set by variable assignment or with set or inherited from the + shell's parent in the environment + + • shell functions defined during execution or inherited from the shell's parent in the environ‐ + ment + + • options enabled at invocation (either by default or with command-line arguments) or by set + + • options enabled by shopt + + • shell aliases defined with alias + + • various process IDs, including those of background jobs, the value of $$, and the value of + PPID + + When a simple command other than a builtin or shell function is to be executed, it is invoked in a + separate execution environment that consists of the following. Unless otherwise noted, the values + are inherited from the shell. + + • the shell's open files, plus any modifications and additions specified by redirections to the + command + + • the current working directory + + • the file creation mode mask + + • shell variables and functions marked for export, along with variables exported for the com‐ + mand, passed in the environment + + • traps caught by the shell are reset to the values inherited from the shell's parent, and + traps ignored by the shell are ignored + + A command invoked in this separate environment cannot affect the shell's execution environment. + + Command substitution, commands grouped with parentheses, and asynchronous commands are invoked in a + subshell environment that is a duplicate of the shell environment, except that traps caught by the + shell are reset to the values that the shell inherited from its parent at invocation. Builtin com‐ + mands that are invoked as part of a pipeline are also executed in a subshell environment. Changes + made to the subshell environment cannot affect the shell's execution environment. + + Subshells spawned to execute command substitutions inherit the value of the -e option from the par‐ + ent shell. When not in posix mode, bash clears the -e option in such subshells. + + If a command is followed by a & and job control is not active, the default standard input for the + command is the empty file /dev/null. Otherwise, the invoked command inherits the file descriptors + of the calling shell as modified by redirections. + +ENVIRONMENT + When a program is invoked it is given an array of strings called the environment. This is a list of + name-value pairs, of the form name=value. + + The shell provides several ways to manipulate the environment. On invocation, the shell scans its + own environment and creates a parameter for each name found, automatically marking it for export to + child processes. Executed commands inherit the environment. The export and declare -x commands al‐ + low parameters and functions to be added to and deleted from the environment. If the value of a pa‐ + rameter in the environment is modified, the new value becomes part of the environment, replacing the + old. The environment inherited by any executed command consists of the shell's initial environment, + whose values may be modified in the shell, less any pairs removed by the unset command, plus any ad‐ + ditions via the export and declare -x commands. + + The environment for any simple command or function may be augmented temporarily by prefixing it with + parameter assignments, as described above in PARAMETERS. These assignment statements affect only + the environment seen by that command. + + If the -k option is set (see the set builtin command below), then all parameter assignments are + placed in the environment for a command, not just those that precede the command name. + + When bash invokes an external command, the variable _ is set to the full filename of the command and + passed to that command in its environment. + +EXIT STATUS + The exit status of an executed command is the value returned by the waitpid system call or equiva‐ + lent function. Exit statuses fall between 0 and 255, though, as explained below, the shell may use + values above 125 specially. Exit statuses from shell builtins and compound commands are also lim‐ + ited to this range. Under certain circumstances, the shell will use special values to indicate spe‐ + cific failure modes. + + For the shell's purposes, a command which exits with a zero exit status has succeeded. An exit sta‐ + tus of zero indicates success. A non-zero exit status indicates failure. When a command terminates + on a fatal signal N, bash uses the value of 128+N as the exit status. + + If a command is not found, the child process created to execute it returns a status of 127. If a + command is found but is not executable, the return status is 126. + + If a command fails because of an error during expansion or redirection, the exit status is greater + than zero. + + Shell builtin commands return a status of 0 (true) if successful, and non-zero (false) if an error + occurs while they execute. All builtins return an exit status of 2 to indicate incorrect usage, + generally invalid options or missing arguments. + + Bash itself returns the exit status of the last command executed, unless a syntax error occurs, in + which case it exits with a non-zero value. See also the exit builtin command below. + +SIGNALS + When bash is interactive, in the absence of any traps, it ignores SIGTERM (so that kill 0 does not + kill an interactive shell), and SIGINT is caught and handled (so that the wait builtin is interrupt‐ + ible). In all cases, bash ignores SIGQUIT. If job control is in effect, bash ignores SIGTTIN, + SIGTTOU, and SIGTSTP. + + Non-builtin commands run by bash have signal handlers set to the values inherited by the shell from + its parent. When job control is not in effect, asynchronous commands ignore SIGINT and SIGQUIT in + addition to these inherited handlers. Commands run as a result of command substitution ignore the + keyboard-generated job control signals SIGTTIN, SIGTTOU, and SIGTSTP. + + The shell exits by default upon receipt of a SIGHUP. Before exiting, an interactive shell resends + the SIGHUP to all jobs, running or stopped. Stopped jobs are sent SIGCONT to ensure that they re‐ + ceive the SIGHUP. To prevent the shell from sending the signal to a particular job, it should be + removed from the jobs table with the disown builtin (see SHELL BUILTIN COMMANDS below) or marked to + not receive SIGHUP using disown -h. + + If the huponexit shell option has been set with shopt, bash sends a SIGHUP to all jobs when an in‐ + teractive login shell exits. + + If bash is waiting for a command to complete and receives a signal for which a trap has been set, + the trap will not be executed until the command completes. When bash is waiting for an asynchronous + command via the wait builtin, the reception of a signal for which a trap has been set will cause the + wait builtin to return immediately with an exit status greater than 128, immediately after which the + trap is executed. + +JOB CONTROL + Job control refers to the ability to selectively stop (suspend) the execution of processes and con‐ + tinue (resume) their execution at a later point. A user typically employs this facility via an in‐ + teractive 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 + may be listed with the jobs command. When bash starts a job asynchronously (in the background), 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, the operating system main‐ + tains the notion of a current terminal process group ID. Members of this process group (processes + whose process group ID is equal to the current terminal process group ID) receive keyboard-generated + signals such as SIGINT. These processes are said to be in the foreground. Background processes are + those whose process group ID differs from the terminal's; such processes are immune to keyboard-gen‐ + erated signals. Only foreground processes are allowed to read from or, if the user so specifies + with stty tostop, write to the terminal. Background processes which attempt to read from (write to + when stty tostop is in effect) the terminal are sent a SIGTTIN (SIGTTOU) signal by the kernel's ter‐ + minal driver, which, unless caught, suspends the process. + + If the operating system on which bash is running supports job control, bash contains facilities to + use it. Typing the suspend character (typically ^Z, Control-Z) while a process is running causes + that process to be stopped and returns control to bash. Typing the delayed suspend character (typi‐ + cally ^Y, Control-Y) causes the process to be stopped when it attempts to read input from the termi‐ + nal, and control to be returned to bash. The user may then manipulate the state of this job, using + the bg command to continue it in the background, the fg command to continue it in the foreground, or + the kill command to kill it. A ^Z takes effect immediately, and has the additional side effect of + causing pending output and typeahead to be discarded. + + There are a number of ways to refer to a job in the shell. The character % introduces a job speci‐ + fication (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 ex‐ + ample, %ce refers to a stopped ce job. If a prefix matches more than one job, bash reports an er‐ + ror. Using %?ce, on the other hand, refers to any job containing the string ce in its command line. + If the substring matches more than one job, bash reports an error. The symbols %% and %+ refer to + the shell's notion of the current job, which is the last job stopped while it was in the foreground + or started in the background. The previous job may be referenced using %-. If there is only a sin‐ + gle job, %+ and %- can both be used to refer to that job. In output pertaining to jobs (e.g., the + output of the jobs command), the current job is always flagged with a +, and the previous job with a + -. A single % (with no accompanying job specification) also refers to the current job. + + Simply naming a job can be used to bring it into the foreground: %1 is a synonym for ``fg %1'', + bringing job 1 from the 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 reporting changes in a job's status so as to not interrupt any other out‐ + put. If the -b option to the set builtin command is enabled, bash reports such changes immediately. + Any trap on SIGCHLD is executed for each child that exits. + + If an attempt to exit bash is made while jobs are stopped (or, if the checkjobs shell option has + been enabled using the shopt builtin, running), the shell prints a warning message, and, if the + checkjobs option is enabled, lists the jobs and their statuses. The jobs command may then be used + to inspect their status. If a second attempt to exit is made without an intervening command, the + shell does not print another warning, and any stopped jobs are terminated. + + 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 will force wait to wait until the job or + process terminates before returning. + +PROMPTING + When executing interactively, bash displays the primary prompt PS1 when it is ready to read a com‐ + mand, and the secondary prompt PS2 when it needs more input to complete a command. Bash displays + PS0 after it reads a command but before executing it. Bash displays PS4 as described above before + tracing each command when the -x option is enabled. Bash allows these prompt strings to be custom‐ + ized by inserting a number of backslash-escaped special characters that are decoded as follows: + \a an ASCII bell character (07) + \d the date in "Weekday Month Date" format (e.g., "Tue May 26") + \D{format} + the format is passed to strftime(3) and the result is inserted into the prompt string; + an empty format results in a locale-specific time representation. The braces are re‐ + quired + \e an ASCII escape character (033) + \h the hostname up to the first `.' + \H the hostname + \j the number of jobs currently managed by the shell + \l the basename of the shell's terminal device name + \n newline + \r carriage return + \s the name of the shell, the basename of $0 (the portion following the final slash) + \t the current time in 24-hour HH:MM:SS format + \T the current time in 12-hour HH:MM:SS format + \@ the current time in 12-hour am/pm format + \A the current time in 24-hour HH:MM format + \u the username of the current user + \v the version of bash (e.g., 2.00) + \V the release of bash, version + patch level (e.g., 2.00.0) + \w the current working directory, with $HOME abbreviated with a tilde (uses the value of + the PROMPT_DIRTRIM variable) + \W the basename of the current working directory, with $HOME abbreviated with a tilde + \! the history number of this command + \# the command number of this command + \$ if the effective UID is 0, a #, otherwise a $ + \nnn the character corresponding to the octal number nnn + \\ a backslash + \[ begin a sequence of non-printing characters, which could be used to embed a terminal + control sequence into the prompt + \] end a sequence of non-printing characters + + The command number and the history number are usually different: the history number of a command is + its position in the history list, which may include commands restored from the history file (see + HISTORY below), while the command number is the position in the sequence of commands executed during + the current shell session. After the string is decoded, it is expanded via parameter expansion, + command substitution, arithmetic expansion, and quote removal, subject to the value of the prompt‐ + vars shell option (see the description of the shopt command under SHELL BUILTIN COMMANDS below). + +READLINE + This is the library that handles reading input when using an interactive shell, unless the --noedit‐ + ing option is given at shell invocation. Line editing is also used when using the -e option to the + read builtin. By default, the line editing commands are similar to those of Emacs. 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 (see SHELL BUILTIN COMMANDS below). To turn off line editing after + the shell is running, use the +o emacs or +o vi options to the set builtin. + + Readline Notation + In this section, the Emacs-style notation is used to denote keystrokes. Control keys are denoted by + C-key, e.g., C-n means Control-N. Similarly, meta keys are denoted by M-key, so M-x means Meta-X. + (On keyboards without a meta key, M-x means ESC x, i.e., press the Escape key then the x key. This + makes ESC the meta prefix. The combination M-C-x means ESC-Control-x, or press the Escape key then + hold the Control key while pressing the x key.) + + Readline commands may be given numeric arguments, which normally act as a repeat count. Sometimes, + however, it is the sign of the argument that is significant. Passing a negative argument to a com‐ + mand that acts in the forward direction (e.g., kill-line) causes that command to act in a backward + direction. Commands whose behavior with arguments deviates from this are noted below. + + When a command is described as killing text, the text deleted is saved for possible future retrieval + (yanking). The killed text is saved in a kill ring. Consecutive kills cause the text to be accumu‐ + lated into one unit, which can be yanked all at once. Commands which do not kill text separate the + chunks of text on the kill ring. + + Readline Initialization + Readline is customized by putting commands in an initialization file (the inputrc file). The name + of this file is taken from the value of the INPUTRC variable. If that variable is unset, the de‐ + fault is ~/.inputrc. When a program which uses the readline library starts up, the initialization + file is read, and the key bindings and variables are set. There are only a few basic constructs al‐ + lowed in the readline initialization file. Blank lines are ignored. Lines beginning with a # are + comments. Lines beginning with a $ indicate conditional constructs. Other lines denote key bind‐ + ings and variable settings. + + The default key-bindings may be changed with an inputrc file. Other programs that use this library + may add their own commands and bindings. + + For example, placing + + M-Control-u: universal-argument + or + C-Meta-u: universal-argument + into the inputrc would make M-C-u execute the readline command universal-argument. + + The following symbolic character names are recognized: RUBOUT, DEL, ESC, LFD, NEWLINE, RET, RETURN, + SPC, SPACE, and TAB. + + In addition to command names, readline allows keys to be bound to a string that is inserted when the + key is pressed (a macro). + + Readline Key Bindings + The syntax for controlling key bindings in the inputrc file is simple. All that is required is the + name of the command or the text of a macro and a key sequence to which it should be bound. The name + may be specified in one of two ways: as a symbolic key name, possibly with Meta- or Control- pre‐ + fixes, or as a key sequence. + + When using the form keyname:function-name or macro, keyname is the name of a key spelled out in Eng‐ + lish. For example: + + Control-u: universal-argument + Meta-Rubout: backward-kill-word + Control-o: "> output" + + In the above example, C-u is bound to the function universal-argument, M-DEL is bound to the func‐ + tion 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). + + In the second form, "keyseq":function-name or macro, keyseq differs from keyname above in that + strings denoting an entire key sequence may be specified by placing the sequence within double + quotes. Some GNU Emacs style key escapes can be used, as in the following example, but the symbolic + character names are not recognized. + + "\C-u": universal-argument + "\C-x\C-r": re-read-init-file + "\e[11~": "Function Key 1" + + In this example, C-u is again bound to the function universal-argument. C-x C-r is bound to the + function re-read-init-file, and ESC [ 1 1 ~ is bound to insert the text ``Function Key 1''. + + The full set of GNU Emacs style escape sequences is + \C- control prefix + \M- meta prefix + \e an escape character + \\ backslash + \" literal " + \' literal ' + + In addition to the GNU Emacs style escape sequences, a second set of backslash escapes is available: + \a alert (bell) + \b backspace + \d delete + \f form feed + \n newline + \r carriage return + \t horizontal tab + \v vertical tab + \nnn the eight-bit character whose value is the octal value nnn (one to three digits) + \xHH the eight-bit character whose value is the hexadecimal value HH (one or two hex dig‐ + its) + + When entering the text of a macro, single or double quotes must be used to indicate a macro defini‐ + tion. Unquoted text is assumed to be a function name. In the macro body, the backslash escapes de‐ + scribed above are expanded. Backslash will quote any other character in the macro text, including " + and '. + + Bash allows the current readline key bindings to be displayed or modified with the bind builtin com‐ + mand. The editing mode may be switched during interactive use by using the -o option to the set + builtin command (see SHELL BUILTIN COMMANDS below). + + Readline Variables + Readline has variables that can be used to further customize its behavior. A variable may be set in + the inputrc file with a statement of the form + + set variable-name value + + Except where noted, readline variables can take the values On or Off (without regard to case). Un‐ + recognized variable names are ignored. When a variable value is read, empty or null values, "on" + (case-insensitive), and "1" are equivalent to On. All other values are equivalent to Off. The + variables and their default values are: + + bell-style (audible) + Controls what happens when readline wants to ring the terminal bell. If set to none, read‐ + line never rings the bell. If set to visible, readline uses a visible bell if one is avail‐ + able. If set to audible, readline attempts to ring the terminal's bell. + bind-tty-special-chars (On) + If set to On, readline attempts to bind the control characters treated specially by the ker‐ + nel's terminal driver to their readline equivalents. + blink-matching-paren (Off) + If set to On, readline attempts to briefly move the cursor to an opening parenthesis when a + closing parenthesis is inserted. + colored-completion-prefix (Off) + If set to On, when listing completions, readline displays the common prefix of the set of + possible completions using a different color. The color definitions are taken from the value + of the LS_COLORS environment variable. + colored-stats (Off) + If set to On, readline displays possible completions using different colors to indicate their + file type. The color definitions are taken from the value of the LS_COLORS environment vari‐ + able. + comment-begin (``#'') + The string that is inserted when the readline insert-comment command is executed. This com‐ + mand is bound to M-# in emacs mode and to # in vi command mode. + completion-display-width (-1) + The number of screen columns used to display possible matches when performing completion. + The value is ignored if it is less than 0 or greater than the terminal screen width. A value + of 0 will cause matches to be displayed one per line. The default value is -1. + completion-ignore-case (Off) + If set to On, readline performs filename matching and completion in a case-insensitive fash‐ + ion. + completion-map-case (Off) + If set to On, and completion-ignore-case is enabled, readline treats hyphens (-) and under‐ + scores (_) as equivalent when performing case-insensitive filename matching and completion. + completion-prefix-display-length (0) + The length in characters of the common prefix of a list of possible completions that is dis‐ + played without modification. When set to a value greater than zero, common prefixes longer + than this value are replaced with an ellipsis when displaying possible completions. + completion-query-items (100) + This determines when the user is queried about viewing the number of possible completions + generated by the possible-completions command. It may be set to any integer value greater + than or equal to zero. If the number of possible completions is greater than or equal to the + value of this variable, the user is asked whether or not he wishes to view them; otherwise + they are simply listed on the terminal. + convert-meta (On) + If set to On, readline will convert characters with the eighth bit set to an ASCII key se‐ + quence by stripping the eighth bit and prefixing an escape character (in effect, using escape + as the meta prefix). The default is On, but readline will set it to Off if the locale con‐ + tains eight-bit characters. + disable-completion (Off) + If set to On, readline will inhibit word completion. Completion characters will be inserted + into the line as if they had been mapped to self-insert. + echo-control-characters (On) + When set to On, on operating systems that indicate they support it, readline echoes a charac‐ + ter corresponding to a signal generated from the keyboard. + editing-mode (emacs) + Controls whether readline begins with a set of key bindings similar to Emacs or vi. edit‐ + ing-mode 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. Use the \1 and \2 escapes to begin and end sequences of non-printing + characters, which can be used to embed a terminal control sequence into the mode string. + enable-bracketed-paste (Off) + When set to On, readline will configure the terminal in a way that will enable it to insert + each paste into the editing buffer as a single string of characters, instead of treating each + character as if it had been read from the keyboard. This can prevent pasted characters from + being interpreted as editing commands. + enable-keypad (Off) + When set to On, readline will try to enable the application keypad when it is called. Some + systems need this to enable the arrow keys. + enable-meta-key (On) + When set to On, readline will try to enable any meta modifier key the terminal claims to sup‐ + port when it is called. On many terminals, the meta key is used to send eight-bit charac‐ + ters. + expand-tilde (Off) + If set to On, tilde expansion is performed when readline attempts word completion. + history-preserve-point (Off) + If set to On, the history code attempts to place point at the same location on each history + line retrieved with previous-history or next-history. + history-size (unset) + Set the maximum number of history entries saved in the history list. If set to zero, any ex‐ + isting 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, the number of history en‐ + tries is set to the value of the HISTSIZE shell variable. If an attempt is made to set his‐ + tory-size to a non-numeric value, the maximum number of history entries will be set to 500. + horizontal-scroll-mode (Off) + When set to On, makes readline use a single line for display, scrolling the input horizon‐ + tally on a single screen line when it becomes longer than the screen width rather than wrap‐ + ping to a new line. + input-meta (Off) + If set to On, readline will enable eight-bit input (that is, it will not strip the eighth bit + from the characters it reads), regardless of what the terminal claims it can support. The + name meta-flag is a synonym for this variable. The default is Off, but readline will set it + to On if the locale contains eight-bit characters. + isearch-terminators (``C-[C-J'') + The string of characters that should terminate an incremental search without subsequently ex‐ + ecuting the character as a command. If this variable has not been given a value, the charac‐ + ters ESC and C-J will terminate an incremental search. + keymap (emacs) + Set the current readline keymap. The set of valid keymap names is emacs, emacs-standard, + emacs-meta, emacs-ctlx, vi, vi-command, and vi-insert. vi is equivalent to vi-command; emacs + is equivalent to emacs-standard. The default value is emacs; the value of editing-mode also + affects the default keymap. + keyseq-timeout (500) + Specifies the duration readline will wait for a character when reading an ambiguous key se‐ + quence (one that can form a complete key sequence using the input read so far, or can take + additional input to complete a longer key sequence). If no input is received within the + timeout, readline will use the shorter but complete key sequence. The value is specified in + milliseconds, so a value of 1000 means that readline will wait one second for additional in‐ + put. If this variable is set to a value less than or equal to zero, or to a non-numeric + value, readline will wait until another key is pressed to decide which key sequence to com‐ + plete. + mark-directories (On) + If set to On, completed directory names have a slash appended. + mark-modified-lines (Off) + If set to On, history lines that have been modified are displayed with a preceding asterisk + (*). + mark-symlinked-directories (Off) + If set to On, completed names which are symbolic links to directories have a slash appended + (subject to the value of mark-directories). + match-hidden-files (On) + This variable, when set to On, causes readline to match files whose names begin with a `.' + (hidden files) when performing filename completion. If set to Off, the leading `.' must be + supplied by the user in the filename to be completed. + menu-complete-display-prefix (Off) + If set to On, menu completion displays the common prefix of the list of possible completions + (which may be empty) before cycling through the list. + output-meta (Off) + If set to On, readline will display characters with the eighth bit set directly rather than + as a meta-prefixed escape sequence. The default is Off, but readline will set it to On if + the locale contains eight-bit characters. + page-completions (On) + If set to On, readline uses an internal more-like pager to display a screenful of possible + completions at a time. + print-completions-horizontally (Off) + If set to On, readline will display completions with matches sorted horizontally in alphabet‐ + ical order, rather than down the screen. + revert-all-at-newline (Off) + If set to On, readline will undo all changes to history lines before returning when ac‐ + cept-line is executed. By default, history lines may be modified and retain individual undo + lists across calls to readline. + show-all-if-ambiguous (Off) + This alters the default behavior of the completion functions. If set to On, words which have + more than one possible completion cause the matches to be listed immediately instead of ring‐ + ing the bell. + show-all-if-unmodified (Off) + This alters the default behavior of the completion functions in a fashion similar to + show-all-if-ambiguous. If set to On, words which have more than one possible completion + without any possible partial completion (the possible completions don't share a common pre‐ + fix) cause the matches to be listed immediately instead of ringing the bell. + show-mode-in-prompt (Off) + 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). + skip-completed-text (Off) + If set to On, this alters the default completion behavior when inserting a single match into + the line. It's only active 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. + vi-cmd-mode-string ((cmd)) + 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 command mode. The + value is expanded like a key binding, so the standard set of meta- and control prefixes and + backslash escape sequences is available. Use the \1 and \2 escapes to begin and end se‐ + quences of non-printing characters, which can be used to embed a terminal control sequence + into the mode string. + vi-ins-mode-string ((ins)) + 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 control prefixes + and backslash escape sequences is available. Use the \1 and \2 escapes to begin and end se‐ + quences of non-printing characters, which can be used to embed a terminal control sequence + into the mode string. + visible-stats (Off) + If set to On, a character denoting a file's type as reported by stat(2) is appended to the + filename when listing possible completions. + + Readline Conditional Constructs + Readline implements a facility similar in spirit to the conditional compilation features of the C + preprocessor which allows key bindings and variable settings to be performed as the result of tests. + There are four parser directives used. + + $if The $if construct allows bindings to be made based on the editing mode, the terminal being + used, or the application using readline. The text of the test, after any comparison opera‐ + tor, + extends to the end of the line; unless otherwise noted, no characters are required to iso‐ + late it. + + mode The mode= form of the $if directive is used to test whether readline is in emacs or vi + mode. This may be used in conjunction with the set keymap command, for instance, to + set bindings in the emacs-standard and emacs-ctlx keymaps only if readline is starting + out in emacs mode. + + term The term= form may be used to include terminal-specific key bindings, perhaps to bind + the key sequences output by the terminal's function keys. The word on the right side + of the = is tested against both the full name of the terminal and the portion of the + terminal name before the first -. This allows sun to match both sun and sun-cmd, for + instance. + + version + The version test may be used to perform comparisons against specific readline ver‐ + sions. The version expands to the current readline version. The set of comparison + operators includes =, (and ==), !=, <=, >=, <, and >. The version number supplied on + the right side of the operator consists of a major version number, an optional decimal + point, and an optional minor version (e.g., 7.1). If the minor version is omitted, it + is assumed to be 0. The operator may be separated from the string version and from + the version number argument by whitespace. + + application + The application construct is used to include application-specific settings. Each pro‐ + gram using the readline library sets the application name, and an initialization file + can test for a particular value. This could be used to bind key sequences to func‐ + tions useful for a specific program. For instance, the following command adds a key + sequence that quotes the current or previous word in bash: + + $if Bash + # Quote the current or previous word + "\C-xq": "\eb\"\ef\"" + $endif + + variable + The variable construct provides simple equality tests for readline variables and val‐ + ues. The permitted comparison operators are =, ==, and !=. The variable name must be + separated from the comparison operator by whitespace; the operator may be separated + from the value on the right hand side by whitespace. Both string and boolean vari‐ + ables may be tested. Boolean variables must be tested against the values on and off. + + $endif This command, as seen in the previous example, terminates an $if command. + + $else Commands in this branch of the $if directive are executed if the test fails. + + $include + This directive takes a single filename as an argument and reads commands and bindings from + that file. For example, the following directive would read /etc/inputrc: + + $include /etc/inputrc + + Searching + Readline provides commands for searching through the command history (see HISTORY below) for lines + containing a specified string. There 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. 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 Escape and Con‐ + trol-J characters will terminate an incremental search. Control-G will abort an incremental search + and restore 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 Control-S or Control-R as appropriate. + This will search 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 will terminate the search and exe‐ + cute that command. For instance, a newline will terminate the search and accept the line, thereby + executing the command from the history list. + + Readline remembers the last incremental search string. If two Control-Rs are typed without any in‐ + tervening characters defining a new search string, any remembered search string is used. + + Non-incremental searches read the entire search string before starting to search for matching his‐ + tory lines. The search string may be typed by the user or be part of the contents of the current + line. + + Readline Command Names + The following is a list of the names of the commands and the default key sequences to which they are + bound. 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. + + Commands for Moving + beginning-of-line (C-a) + Move to the start of the current line. + end-of-line (C-e) + Move to the end of the line. + forward-char (C-f) + Move forward a character. + backward-char (C-b) + Move back a character. + forward-word (M-f) + Move forward to the end of the next word. Words are composed of alphanumeric characters + (letters and digits). + backward-word (M-b) + Move back to the start of the current or previous word. Words are composed of alphanumeric + characters (letters and digits). + shell-forward-word + Move forward to the end of the next word. Words are delimited by non-quoted shell metachar‐ + acters. + shell-backward-word + Move back to the start of the current or previous word. Words are delimited by non-quoted + shell metacharacters. + previous-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-screen (C-l) + Clear the screen leaving the current line at the top of the screen. With an argument, re‐ + fresh the current line without clearing the screen. + redraw-current-line + Refresh the current line. + + Commands for Manipulating the History + accept-line (Newline, Return) + Accept the line regardless of where the cursor is. If this line is non-empty, add it to the + history list according to the state of the HISTCONTROL variable. If the line is a modified + history line, then restore the history line to its original state. + previous-history (C-p) + Fetch the previous command from the history list, moving back in the list. + next-history (C-n) + Fetch the next command from the history list, moving forward in the list. + beginning-of-history (M-<) + Move to the first line in the history. + end-of-history (M->) + Move to the end of the input history, i.e., the line currently being entered. + reverse-search-history (C-r) + Search backward starting at the current line and moving `up' through the history as neces‐ + sary. This is an incremental search. + forward-search-history (C-s) + Search forward starting at the current line and moving `down' through the history as neces‐ + sary. This is an incremental search. + non-incremental-reverse-search-history (M-p) + Search backward through the history starting at the current line using a non-incremental + search for a string supplied by the user. + non-incremental-forward-search-history (M-n) + Search forward through the history using a non-incremental search for a string supplied by + the user. + history-search-forward + Search forward through the history for the string of characters between the start of the cur‐ + rent line and the point. This is a non-incremental search. + history-search-backward + Search backward through the history for the string of characters between the start of the + current line and the point. This is a non-incremental search. + history-substring-search-backward + Search backward through the history for the string of characters between the start of the + current line and the current cursor position (the point). The search string may match any‐ + where in a history line. This is a non-incremental search. + history-substring-search-forward + Search forward through the history for the string of characters between the start of the cur‐ + rent line and the point. The search string may match anywhere in a history line. This is a + non-incremental search. + yank-nth-arg (M-C-y) + Insert the first argument to the previous command (usually the second word on the previous + line) at point. With an 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, the argument is extracted + as if the "!n" history expansion had been specified. + yank-last-arg (M-., M-_) + Insert the last argument to the previous command (the last word of the previous history en‐ + try). With a numeric argument, behave exactly like yank-nth-arg. Successive calls to + yank-last-arg move back through the history list, inserting the last word (or the word speci‐ + fied 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). The history expansion + facilities are used to extract the last word, as if the "!$" history expansion had been spec‐ + ified. + shell-expand-line (M-C-e) + Expand the line as the shell does. This performs alias and history expansion as well as all + of the shell word expansions. See HISTORY EXPANSION below for a description of history ex‐ + pansion. + history-expand-line (M-^) + Perform history expansion on the current line. See HISTORY EXPANSION below for a description + of history expansion. + magic-space + Perform history expansion on the current line and insert a space. See HISTORY EXPANSION be‐ + low for a description of history expansion. + alias-expand-line + Perform alias expansion on the current line. See ALIASES above for a description of alias + expansion. + history-and-alias-expand-line + Perform history and alias expansion on the current line. + insert-last-argument (M-., M-_) + A synonym for yank-last-arg. + operate-and-get-next (C-o) + Accept the current line for execution and fetch the next line relative to the current line + from the history for editing. A numeric argument, if supplied, specifies the history entry + to use instead of the current line. + 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. + + Commands for Changing Text + end-of-file (usually C-d) + The character indicating end-of-file as set, for example, by ``stty''. If this character is + read when there are no 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. + backward-delete-char (Rubout) + Delete the character behind the cursor. When given a numeric argument, save the deleted text + on the kill ring. + forward-backward-delete-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. + quoted-insert (C-q, C-v) + Add the next character typed to the line verbatim. This is how to insert characters like + C-q, for example. + tab-insert (C-v TAB) + Insert a tab character. + self-insert (a, b, A, 1, !, ...) + Insert the character typed. + transpose-chars (C-t) + Drag the character before point forward over the character at point, moving point forward as + well. If point is at the end of the line, then this transposes the two characters before + point. Negative arguments have no effect. + transpose-words (M-t) + Drag the word before point past the word after point, moving point over that word as well. + If point is at the end of the line, this transposes the last two words on the line. + upcase-word (M-u) + Uppercase the current (or following) word. With a negative argument, uppercase the previous + word, but do not move point. + downcase-word (M-l) + Lowercase the current (or following) word. With a negative argument, lowercase the previous + word, but do not move point. + capitalize-word (M-c) + Capitalize the current (or following) word. With a negative argument, capitalize the previ‐ + ous word, but do not move point. + 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. + + Killing and Yanking + kill-line (C-k) + Kill the text from point to the end of the line. + backward-kill-line (C-x Rubout) + Kill backward to the beginning of the line. + unix-line-discard (C-u) + Kill backward from point to the beginning of the line. The killed text is saved on the kill- + ring. + kill-whole-line + Kill all characters on the current line, no matter where point is. + kill-word (M-d) + Kill from point to the end of the current word, or if between words, to the end of the next + word. Word boundaries are the same as those used by forward-word. + backward-kill-word (M-Rubout) + Kill the word behind point. Word boundaries are the same as those used by backward-word. + shell-kill-word + 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 those used by shell-forward-word. + shell-backward-kill-word + Kill the word behind point. Word boundaries are the same as those used by shell-back‐ + ward-word. + unix-word-rubout (C-w) + Kill the word behind point, using white space as a word boundary. The killed text is saved + on the kill-ring. + unix-filename-rubout + Kill the word behind point, using white space and the slash character as the word boundaries. + The killed text is saved on the kill-ring. + delete-horizontal-space (M-\) + Delete all spaces and tabs around point. + kill-region + Kill the text in the current region. + copy-region-as-kill + Copy the text in the region to the kill buffer. + copy-backward-word + Copy the word before point to the kill buffer. The word boundaries are the same as back‐ + ward-word. + copy-forward-word + Copy the word following point to the kill buffer. The word boundaries are the same as for‐ + ward-word. + yank (C-y) + Yank the top of the kill ring into the buffer at point. + yank-pop (M-y) + Rotate the kill ring, and yank the new top. Only works following yank or yank-pop. + + Numeric Arguments + digit-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 dig‐ + its, 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, if this command is immediately followed by a character + that is neither a digit nor 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. + + Completing + complete (TAB) + Attempt to perform completion on the text before point. Bash attempts completion treating + the text as a variable (if the text begins with $), username (if the text begins with ~), + hostname (if the text begins with @), or command (including aliases and functions) in turn. + If none of these produces a match, filename completion is attempted. + possible-completions (M-?) + List the possible completions of the text before point. + insert-completions (M-*) + Insert all completions of the text before point that would have been generated by possi‐ + ble-completions. + menu-complete + Similar to complete, but replaces the word to be completed with a single match from the list + of possible completions. Repeated execution of menu-complete steps through the list of pos‐ + sible completions, inserting each match in turn. At the end of the list of completions, the + bell is rung (subject to the setting of bell-style) and the original text is restored. An + argument of n moves n positions forward in the list of matches; a negative argument may be + used to move backward through the list. This command is intended to be bound to TAB, but is + unbound by default. + menu-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. + delete-char-or-list + Deletes the character under the cursor if not at the beginning or end of the line (like + delete-char). If at the end of the line, behaves identically to possible-completions. This + command is unbound by default. + complete-filename (M-/) + Attempt filename completion on the text before point. + possible-filename-completions (C-x /) + List the possible completions of the text before point, treating it as a filename. + complete-username (M-~) + Attempt completion on the text before point, treating it as a username. + possible-username-completions (C-x ~) + List the possible completions of the text before point, treating it as a username. + complete-variable (M-$) + Attempt completion on the text before point, treating it as a shell variable. + possible-variable-completions (C-x $) + List the possible completions of the text before point, treating it as a shell variable. + complete-hostname (M-@) + Attempt completion on the text before point, treating it as a hostname. + possible-hostname-completions (C-x @) + List the possible completions of the text before point, treating it as a hostname. + complete-command (M-!) + Attempt completion on the text before point, treating it as a command name. Command comple‐ + tion 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 lines from the his‐ + tory list 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 (see Brace Expansion above). + + Keyboard Macros + start-kbd-macro (C-x () + Begin saving the characters typed into the current keyboard macro. + end-kbd-macro (C-x )) + Stop saving the characters typed into the current keyboard macro and store the definition. + call-last-kbd-macro (C-x e) + Re-execute the last keyboard macro defined, by making the characters in the macro appear as + if typed at the keyboard. + print-last-kbd-macro () + Print the last keyboard macro defined in a format suitable for the inputrc file. + + Miscellaneous + re-read-init-file (C-x C-r) + Read in the contents of the inputrc file, and incorporate any bindings or variable assign‐ + ments found there. + abort (C-g) + Abort the current editing command and ring the terminal's bell (subject to the setting of + bell-style). + do-lowercase-version (M-A, M-B, M-x, ...) + If the metafied character x is uppercase, run the command that is bound to the corresponding + metafied lowercase character. The behavior is undefined if x is already lowercase. + prefix-meta (ESC) + Metafy the next character typed. ESC f is equivalent to Meta-f. + undo (C-_, C-x C-u) + Incremental undo, separately remembered for each line. + revert-line (M-r) + Undo all changes made to this line. This is like executing the undo command enough times to + return the line to its initial state. + tilde-expand (M-&) + Perform tilde expansion on the current word. + set-mark (C-@, M-) + Set the mark to the point. If a numeric argument is supplied, the mark is set to that posi‐ + tion. + exchange-point-and-mark (C-x C-x) + Swap the point with the mark. The current cursor position is set to the saved position, and + the old cursor position is saved as the mark. + character-search (C-]) + A character is read and point is moved to the next occurrence of that character. A negative + count searches for previous occurrences. + character-search-backward (M-C-]) + A character is read and point is moved to the previous occurrence of that character. A nega‐ + tive count searches for subsequent occurrences. + skip-csi-sequence + Read enough characters to consume a multi-key sequence such as those defined for keys like + Home and End. Such sequences begin with a Control Sequence Indicator (CSI), usually ESC-[. + If this sequence is bound to "\[", keys producing such sequences will have no effect unless + explicitly bound to a readline command, instead of inserting stray characters into the edit‐ + ing buffer. This is unbound by default, but usually bound to ESC-[. + insert-comment (M-#) + Without a numeric argument, the value of the readline comment-begin variable is inserted at + the beginning of the current line. If a numeric argument is supplied, this command acts as a + toggle: if the characters at the beginning of the line do not match the value of comment-be‐ + gin, the value is inserted, otherwise the characters in comment-begin are deleted 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 com‐ + ment. If a numeric argument causes the comment character to be removed, the line will be ex‐ + ecuted by the shell. + glob-complete-word (M-g) + The word before point is treated as a pattern for pathname expansion, with an asterisk im‐ + plicitly appended. This pattern is used to generate a list of matching filenames for possi‐ + ble completions. + glob-expand-word (C-x *) + The word before point is treated as a pattern for pathname expansion, and the list of match‐ + ing filenames is inserted, replacing the word. If a numeric argument is supplied, an aster‐ + isk is appended before pathname expansion. + glob-list-expansions (C-x g) + The list of expansions that would have been generated by glob-expand-word is displayed, and + the line is redrawn. If a numeric argument is supplied, an asterisk is appended before path‐ + name expansion. + dump-functions + Print all of the functions and their key bindings to the readline output stream. If a nu‐ + meric argument is supplied, the output is formatted in such a way that it can be made part of + an inputrc file. + dump-variables + Print all of the settable readline 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. + dump-macros + Print all of the readline key sequences bound to macros and the strings they output. If a + numeric argument is supplied, the output is formatted in such a way that it can be made part + of an inputrc file. + display-shell-version (C-x C-v) + Display version information about the current instance of bash. + + Programmable Completion + When word completion is attempted for an argument to a command for which a completion specification + (a compspec) has been defined using the complete builtin (see SHELL BUILTIN COMMANDS below), the + programmable completion facilities are invoked. + + First, the command name is identified. If the command word is the empty string (completion at‐ + tempted at the beginning of an empty line), any compspec defined with the -E option to complete is + used. 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 a full pathname, a compspec for the full + pathname is searched for first. If no compspec is found for the full pathname, an attempt is made + to find a compspec for the portion following the final slash. If those searches do not result in a + compspec, any compspec defined with the -D option to complete is used as the default. If there is + no default compspec, bash attempts alias expansion on the command word as a final resort, and at‐ + tempts to find a compspec for the command word from any successful expansion. + + Once a compspec has been found, it is used to generate the list of matching words. If a compspec is + not found, the default bash completion as described above under Completing is performed. + + First, the actions specified by the compspec are used. Only matches which are prefixed by the word + being completed are returned. When the -f or -d option is used for filename or directory name com‐ + pletion, the shell variable FIGNORE is used to filter the matches. + + Any completions specified by a pathname expansion pattern to the -G option are generated next. The + words generated by the pattern need not match the word being completed. The GLOBIGNORE shell vari‐ + able is not used to filter the matches, but the FIGNORE variable is used. + + Next, the string specified as the argument to the -W option is considered. The string is first + split using the characters in the IFS special variable as delimiters. Shell quoting is honored. + Each word is then expanded using brace expansion, tilde expansion, parameter and variable expansion, + command substitution, and arithmetic expansion, as described above under EXPANSION. The results are + split using the rules described above under Word Splitting. The results of the expansion are pre‐ + fix-matched against the word being completed, and the matching words become the possible comple‐ + tions. + + After these matches have been generated, any shell function or command specified with the -F and -C + options is invoked. When the command or function is invoked, the COMP_LINE, COMP_POINT, COMP_KEY, + and COMP_TYPE variables are assigned values as described above under Shell Variables. If a shell + function is being invoked, the COMP_WORDS and COMP_CWORD variables are also set. 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. No filtering of the generated + completions against the word being completed is performed; the function or command has complete + freedom in generating the matches. + + Any function specified with -F is invoked first. The function may use any of the shell facilities, + including the compgen builtin 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. Back‐ + slash may be used to escape a newline, if necessary. + + After all of the possible completions are generated, any filter specified with the -X option is ap‐ + plied to 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 will be + removed from the list. A leading ! negates the pattern; in this case any completion not matching + the pattern will be removed. If the nocasematch shell option is enabled, the match is performed + without regard to the case of alphabetic characters. + + Finally, any prefix and suffix specified with the -P and -S options are added to each member of the + completion list, and the result is returned to the readline completion code as the list of possible + completions. + + If the previously-applied actions do not generate any matches, and the -o dirnames option was sup‐ + plied to complete when the compspec was defined, directory name completion is attempted. + + If the -o plusdirs option was supplied to complete when the compspec was defined, directory name + completion is attempted and any matches are added to the results of the other actions. + + By default, if a compspec is found, whatever it generates is returned to the completion code as the + full set of possible completions. The default bash completions are not attempted, and the readline + default of filename completion is disabled. If the -o bashdefault option was supplied to complete + when the compspec was defined, the bash default completions are attempted if the compspec generates + no matches. If the -o default option was supplied to complete when the compspec was defined, read‐ + line's default completion will be performed if the compspec (and, if attempted, the default bash + completions) generate no matches. + + When a compspec indicates that directory name completion is desired, the programmable completion + functions force readline to append a slash to completed names which are symbolic links to directo‐ + ries, 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 com‐ + bination with a default completion specified with complete -D. It's possible for shell functions + executed as completion handlers 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 com‐ + mand on which completion is being attempted (supplied as the first argument when the function is ex‐ + ecuted), programmable completion restarts from the beginning, with an attempt to find a new compspec + for that command. This allows a set of completions to be built dynamically as completion is at‐ + tempted, rather than being loaded all at once. + + For instance, assuming that there is a library of compspecs, each kept in a file corresponding to + the name of the command, the following default completion function would load completions dynami‐ + cally: + + _completion_loader() + { + . "/etc/bash_completion.d/$1.sh" >/dev/null 2>&1 && return 124 + } + complete -D -F _completion_loader -o bashdefault -o default + +HISTORY + When the -o history option to the set builtin is enabled, the shell provides access to the command + history, the list of commands previously typed. The value of the HISTSIZE variable is used as the + number of commands to save in a history list. The text of the last HISTSIZE commands (default 500) + is saved. The shell stores each command in the history list prior to parameter and variable expan‐ + sion (see EXPANSION above) but after history expansion is performed, subject to the values of the + shell variables HISTIGNORE and HISTCONTROL. + + On startup, the history is initialized from the file named by the variable HISTFILE (default + ~/.bash_history). The file named by the value of HISTFILE is truncated, if necessary, to contain no + more than the number of lines specified by the value of HISTFILESIZE. If HISTFILESIZE is unset, or + set to null, a non-numeric value, or a numeric value less than zero, the history file is not trun‐ + cated. 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 line. These time‐ + stamps are optionally displayed depending on the value of the HISTTIMEFORMAT variable. When a shell + with history enabled exits, the last $HISTSIZE lines are copied from the history list to $HISTFILE. + If the histappend shell option is enabled (see the description of shopt under SHELL BUILTIN COMMANDS + below), the lines are appended to the history file, otherwise the history file is overwritten. If + HISTFILE is unset, or if the history file is unwritable, the history is not saved. If the HISTTIME‐ + FORMAT variable is set, time stamps are written to the history file, marked with the history comment + character, so they may be preserved across shell sessions. This uses the history comment character + to distinguish timestamps from other history lines. After saving the history, the history file is + truncated to contain no more than HISTFILESIZE lines. 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. + + The builtin command fc (see SHELL BUILTIN COMMANDS below) may be used to list or edit and re-execute + a portion of the history list. The history builtin may be used to display or modify the history + list and manipulate the history file. When using command-line editing, search commands are avail‐ + able in each editing mode that provide access to the history list. + + The shell allows control over which commands are saved on the history list. The HISTCONTROL and + HISTIGNORE variables may be set to cause the shell to save only a subset of the commands entered. + The cmdhist shell option, if enabled, causes the shell to attempt to save each line of a multi-line + command in the same history entry, adding semicolons where necessary to preserve syntactic correct‐ + ness. The lithist shell option causes the shell to save the command with embedded newlines instead + of semicolons. See the description of the shopt builtin below under SHELL BUILTIN COMMANDS for in‐ + formation on setting and unsetting shell options. + +HISTORY EXPANSION + The shell supports a history expansion feature that is similar to the history expansion in csh. + This section describes what syntax features are available. This feature is enabled by default for + interactive shells, and can be disabled using the +H option to the set builtin command (see SHELL + BUILTIN COMMANDS below). Non-interactive shells do not perform history expansion by default. + + History expansions introduce words from the history list into the input stream, making it easy to + repeat commands, insert the arguments to a previous command into the current input line, or fix er‐ + rors 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 without taking quoting on previous lines into + account. It takes place in two parts. The first is to determine which line from the history list + to use during substitution. The second is to select portions of that line for inclusion into the + current one. The line selected from the history is the event, and the portions of that line that + are acted upon are words. Various modifiers are available to manipulate the selected words. The + line is broken into words in the same fashion as when reading input, so that several metacharacter- + separated words surrounded by quotes are considered one word. History expansions are introduced by + the appearance of the history expansion character, which is ! by default. Only backslash (\) and + single quotes can quote 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. + + Several characters inhibit history expansion if found immediately following the history expansion + character, even if it is unquoted: space, tab, newline, carriage return, and =. If the extglob + shell option is enabled, ( will also inhibit expansion. + + Several shell options settable with the shopt builtin may be used to tailor the behavior of history + expansion. If the histverify shell option is enabled (see the description of the shopt builtin be‐ + low), 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 modifi‐ + cation. If readline is being used, and the histreedit shell option is enabled, a failed history + substitution will be reloaded into the readline editing buffer for correction. The -p option to the + history builtin command may be used to see 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 ac‐ + tually executing them, so that they are available for subsequent recall. + + The shell allows control of the various characters used by the history expansion mechanism (see the + description of histchars above under Shell Variables). The shell uses the history comment character + to mark history timestamps when writing the history file. + + Event Designators + An event designator is a reference to a command line entry in the history list. Unless the refer‐ + ence is absolute, events are relative to the current position in the history list. + + ! Start a history substitution, except when followed by a blank, newline, carriage return, = or + ( (when the extglob shell option is enabled using the shopt builtin). + !n Refer to command line n. + !-n Refer to the current command minus n. + !! Refer to the previous command. This is a synonym for `!-1'. + !string + Refer to the most recent command preceding the current position in the history list starting + with string. + !?string[?] + Refer to the most recent command preceding the current position in the history list contain‐ + ing string. The trailing ? may be omitted if string is followed immediately by a newline. + ^string1^string2^ + Quick substitution. Repeat the previous command, replacing string1 with string2. Equivalent + to ``!!:s/string1/string2/'' (see Modifiers below). + !# The entire command line typed so far. + + Word Designators + Word designators are used to select desired words from the event. A : separates the event specifi‐ + cation 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). Words are inserted into the current line separated by single spaces. + + 0 (zero) + The zeroth word. For the shell, this is the command word. + n The nth word. + ^ The first argument. That is, word 1. + $ The last word. This is usually the last argument, but will expand to the zeroth word if + there is only one word in the line. + % The word matched by the most recent `?string?' search. + x-y A range of words; `-y' abbreviates `0-y'. + * All of the words but the zeroth. This is a synonym for `1-$'. It is not an error to use * + if there is just one word in the event; the empty string is returned in that case. + x* Abbreviates x-$. + x- Abbreviates x-$ like x*, but omits the last word. + + If a word designator is supplied without an event specification, the previous command is used as the + event. + + Modifiers + After the optional word designator, there may appear a sequence of one or more of the following mod‐ + ifiers, each preceded by a `:'. + + h Remove a trailing filename component, leaving only the head. + t Remove all leading filename components, leaving the tail. + r Remove a trailing suffix of the form .xxx, leaving the basename. + e Remove all but the trailing suffix. + p Print the new command but do not execute it. + q Quote the substituted words, escaping further substitutions. + x Quote the substituted words as with q, but break into words at blanks and newlines. + s/old/new/ + Substitute new for the first occurrence of old in the event line. Any delimiter can be used + in place of /. The final delimiter is optional if it is the last character of the event + line. The delimiter may be quoted in old and new with a single backslash. If & appears in + new, it is replaced by old. A single backslash will quote the &. 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. + & Repeat the previous substitution. + g Cause changes to be applied over the entire event line. This is used in conjunction with + `:s' (e.g., `:gs/old/new/') or `:&'. If used with `:s', any delimiter can be used in place + of /, and the final delimiter is optional if it is the last character of the event line. An + a may be used as a synonym for g. + G Apply the following `s' modifier once to each word in the event line. + +SHELL BUILTIN COMMANDS + Unless otherwise noted, each builtin command documented in this section as accepting options pre‐ + ceded by - accepts -- to signify the end of the options. The :, true, false, and test/[ builtins do + not accept options and do not treat -- specially. The exit, logout, return, break, continue, let, + and shift builtins accept and process arguments beginning with - without requiring --. Other + builtins that accept arguments but are not specified as accepting options interpret arguments begin‐ + ning with - as invalid options and require -- to prevent this interpretation. + : [arguments] + No effect; the command does nothing beyond expanding arguments and performing any specified + redirections. The return status is zero. + + . filename [arguments] + source filename [arguments] + Read and execute commands from filename in the current shell environment and return the exit + status of the last command executed from filename. If filename does not contain a slash, + filenames in PATH are used to find the directory containing filename. The file searched for + in PATH need not be executable. When bash is not in posix mode, the current directory is + searched if no file is found in PATH. If the sourcepath option to the shopt builtin command + is turned off, the PATH is not searched. If any arguments are supplied, they become the po‐ + sitional parameters when filename is executed. Otherwise the positional parameters are un‐ + changed. If the -T option is enabled, source inherits any trap on DEBUG; if it is not, any + DEBUG trap string is saved and restored around the call to source, and source unsets the DE‐ + BUG trap while it executes. If -T is not set, and the sourced file changes the DEBUG trap, + the new value is retained when source completes. The return status is the status of the last + command exited within the script (0 if no commands are executed), and false if filename is + not found or cannot be read. + + alias [-p] [name[=value] ...] + Alias with no arguments or with the -p option prints the list of aliases in the form alias + name=value on standard output. When arguments are supplied, an alias is defined for each + name whose value is given. A trailing space in value causes the next word to be checked for + alias substitution when the alias is expanded. For each name in the argument list for which + no value is supplied, the name and value of the alias is printed. Alias returns true unless + a name is given for which no alias has been defined. + + bg [jobspec ...] + Resume each suspended job jobspec in the background, as if it had been started with &. If + jobspec is not present, the shell's notion of the current job is used. bg jobspec returns 0 + unless run when job control is disabled or, when run with job control enabled, any specified + jobspec was not found or was started without job control. + + bind [-m keymap] [-lpsvPSVX] + bind [-m keymap] [-q function] [-u function] [-r keyseq] + bind [-m keymap] -f filename + bind [-m keymap] -x keyseq:shell-command + bind [-m keymap] keyseq:function-name + bind [-m keymap] keyseq:readline-command + Display current readline key and function bindings, bind a key sequence to a readline func‐ + tion or macro, or set a readline variable. Each non-option argument is a command as it would + appear in .inputrc, but each binding or command must be passed as a separate argument; e.g., + '"\C-x\C-r": re-read-init-file'. Options, if supplied, have the following meanings: + -m keymap + Use keymap as the keymap to be affected by the subsequent bindings. Acceptable keymap + names are 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. + -l List the names of all readline functions. + -p Display readline function names and bindings in such a way that they can be re-read. + -P List current readline function names and bindings. + -s Display readline key sequences bound to macros and the strings they output in such a + way that they can be re-read. + -S Display readline key sequences bound to macros and the strings they output. + -v Display readline variable names and values in such a way that they can be re-read. + -V List current readline variable names and values. + -f filename + Read key bindings from filename. + -q function + Query about which keys invoke the named function. + -u function + Unbind all keys bound to the named function. + -r keyseq + Remove any current binding for keyseq. + -x keyseq:shell-command + Cause shell-command to be executed whenever keyseq is entered. When shell-command is + executed, the shell sets the READLINE_LINE variable to the contents of the readline + line buffer and the READLINE_POINT variable to the current location of the insertion + point. If the executed command changes the value of READLINE_LINE or READLINE_POINT, + those new values will be reflected in the editing state. + -X List all key sequences bound to shell commands and the associated commands in a format + that can be reused as input. + + The return value is 0 unless an unrecognized option is given or an error occurred. + + break [n] + Exit from within a for, while, until, or select loop. If n is specified, break n levels. n + must be ≥ 1. If n is greater than the number of enclosing loops, all enclosing loops are ex‐ + ited. The return value is 0 unless n is not greater than or equal to 1. + + builtin shell-builtin [arguments] + Execute the specified shell builtin, passing it arguments, and return its exit status. This + is useful when defining a function whose name is the same as a shell builtin, retaining the + functionality of the builtin within the function. The cd builtin is commonly redefined this + way. The return status is false if shell-builtin is not a shell builtin command. + + caller [expr] + Returns the context of any active subroutine call (a shell function or a script executed with + the . or source builtins). Without expr, caller displays the line number and source filename + of the current subroutine call. If a non-negative integer is supplied as expr, caller dis‐ + plays the line number, subroutine name, and source file corresponding to that position in the + current execution call stack. This extra information may be used, for example, to print a + stack trace. The current frame is frame 0. The return value is 0 unless the shell is not + executing a subroutine call or expr does not correspond to a valid position in the call + stack. + + cd [-L|[-P [-e]] [-@]] [dir] + Change the current directory to dir. if dir is not supplied, the value of the HOME shell + variable is the default. Any additional arguments following dir are ignored. The variable + CDPATH defines the search path for the directory containing dir: each directory name in CD‐ + PATH is searched for dir. Alternative directory names in CDPATH are separated by a colon + (:). A null directory name in CDPATH is the same as the current directory, i.e., ``.''. If + dir begins with a slash (/), then CDPATH is not used. The -P option causes cd to use the + physical directory structure by resolving symbolic links while traversing dir and before pro‐ + cessing instances of .. in dir (see also the -P option to the set builtin command); the -L + option forces symbolic links to be followed by resolving the link after processing instances + of .. in dir. If .. appears in dir, it is processed by removing the immediately previous + pathname component from dir, back to a slash or the beginning of dir. If the -e option is + supplied with -P, and the current working directory cannot be successfully determined after a + successful directory change, cd will return an unsuccessful status. On systems that support + it, the -@ option presents the extended attributes associated with a file as a directory. An + argument of - is converted to $OLDPWD before the directory change is attempted. If a non- + empty directory name from CDPATH is used, or if - is the first argument, and the directory + change is successful, the absolute pathname of the new working directory is written to the + standard output. The return value is true if the directory was successfully changed; false + otherwise. + + command [-pVv] command [arg ...] + Run command with args suppressing the normal shell function lookup. Only builtin commands or + commands found in the PATH are executed. If the -p option is given, the search for command + is performed using a default value for PATH that is guaranteed to find all of the standard + utilities. If either the -V or -v option is supplied, a description of command is printed. + The -v option causes a single word indicating the command or filename used to invoke command + to be displayed; the -V option produces a more verbose description. If the -V or -v option + is supplied, the exit status is 0 if command was found, and 1 if not. If neither option is + supplied and an error occurred or command cannot be found, the exit status is 127. Other‐ + wise, the exit status of the command builtin is the exit status of command. + + compgen [option] [word] + Generate possible completion matches for word according to the options, which may be any op‐ + tion accepted by the complete builtin with the exception of -p and -r, and write the matches + 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 gen‐ + erated them directly from a completion specification with the same flags. If word is speci‐ + fied, only those completions matching word will be displayed. + + The return value is true unless an invalid option is supplied, or no matches were generated. + + complete [-abcdefgjksuv] [-o comp-option] [-DEI] [-A action] [-G globpat] [-W wordlist] [-F func‐ + tion] [-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 are supplied, existing completion specifications are printed 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 indicates + that other supplied options and actions should apply to completion on the inital non-assign‐ + ment 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 argu‐ + ments 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 under Programmable Completion. + + 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 Use readline's default filename completion if the compspec generates no + matches. + dirnames + Perform directory name completion if the compspec generates no matches. + filenames + Tell readline that the compspec generates filenames, so it can perform any + filename-specific processing (like adding a slash to directory names, quoting + special characters, or suppressing trailing spaces). Intended to be used + with shell functions. + noquote Tell readline not to quote the completed words if they are filenames (quoting + filenames is the default). + nosort Tell readline not to sort the list of possible completions alphabetically. + nospace Tell readline not to append a space (the default) to words completed at the + end of the line. + plusdirs + After any matches defined by the compspec are generated, directory name com‐ + pletion is attempted and any matches are added to the results of the other + actions. + -A action + The action may be one of the following to generate a list of possible completions: + alias Alias names. May also be specified as -a. + arrayvar + Array variable names. + binding Readline key binding names. + builtin Names of shell builtin commands. May also be specified as -b. + command Command names. May also be specified as -c. + directory + Directory names. May also be specified as -d. + disabled + Names of disabled shell builtins. + enabled Names of enabled shell builtins. + export Names of exported shell variables. May also be specified as -e. + file File names. May also be specified as -f. + function + Names of shell functions. + group Group names. May also be specified as -g. + helptopic + Help topics as accepted by the help builtin. + hostname + Hostnames, as taken from the file specified by the HOSTFILE shell variable. + job Job names, if job control is active. May also be specified as -j. + keyword Shell reserved words. May also be specified as -k. + running Names of running jobs, if job control is active. + service Service names. May also be specified as -s. + setopt Valid arguments for the -o option to the set builtin. + shopt Shell option names as accepted by the shopt builtin. + signal Signal names. + stopped Names of stopped jobs, if job control is active. + user User names. May also be specified as -u. + variable + Names of all shell variables. May also be specified as -v. + -C command + command is executed in a subshell environment, and its output is used as the possible + completions. + -F function + The shell function function is executed in the current shell environment. When the + function is executed, the first argument ($1) is the name of the command whose argu‐ + ments 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. When it finishes, the possible completions are retrieved from the + value of the COMPREPLY array variable. + -G globpat + The pathname expansion pattern globpat is expanded to generate the possible comple‐ + tions. + -P prefix + prefix is added at the beginning of each possible completion after all other options + have been applied. + -S suffix + suffix is appended to each possible completion after all other options have been ap‐ + plied. + -W wordlist + The wordlist is split using the characters in the IFS special variable as delimiters, + and each resultant word is expanded. Shell quoting is honored within wordlist, in + order to provide a mechanism for the words to contain shell metacharacters or charac‐ + ters in the value of IFS. The possible completions are the members of the resultant + list which match the word being completed. + -X filterpat + filterpat is a pattern as used for pathname expansion. It is applied to the list of + possible completions generated by the preceding options and arguments, and each com‐ + pletion matching filterpat is removed from the list. A leading ! in filterpat + negates the pattern; in this case, any completion not matching filterpat is removed. + + The return value is true unless an invalid option is supplied, an option other than -p or -r + is supplied without a name 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 specifi‐ + cation. + + compopt [-o option] [-DEI] [+o option] [name] + Modify completion options for each name according to the options, or for the currently-exe‐ + cuting 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; that is, completion attempted on + a command for which no completion has previously been defined. The -E option indicates that + other supplied options should apply to ``empty'' command completion; that is, completion at‐ + tempted on a blank line. The -I option indicates that other supplied options should apply to + completion on the inital non-assignment word on the line, or after a command delimiter such + as ; or |, which is usually command name completion. + + 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 oc‐ + curs. + + continue [n] + Resume the next iteration of the enclosing for, while, until, or select loop. If n is speci‐ + fied, resume at the nth enclosing loop. n must be ≥ 1. If n is greater than the number of + enclosing loops, the last enclosing loop (the ``top-level'' loop) is resumed. The return + value is 0 unless n is not greater than or equal to 1. + + declare [-aAfFgilnrtux] [-p] [name[=value] ...] + typeset [-aAfFgilnrtux] [-p] [name[=value] ...] + Declare variables and/or give them attributes. If no names are given then display the values + of variables. The -p option will display the attributes and values of each name. When -p is + used with name arguments, additional options, other than -f and -F, are ignored. When -p is + supplied without name arguments, it will display the attributes and values of all variables + having the attributes specified by the additional options. If no other options are supplied + with -p, declare will display the attributes and values of all shell variables. The -f op‐ + tion will restrict the display to shell functions. The -F option inhibits the display of + function definitions; only the function name and attributes are printed. If the extdebug + shell option is enabled using shopt, the source file name and line number where each name is + defined are displayed as well. The -F option implies -f. The -g option forces variables to + be created or modified at the global scope, even when declare is executed in a shell func‐ + tion. It is ignored in all other cases. The following options can be used to restrict out‐ + put to variables with the specified attribute or to give variables attributes: + -a Each name is an indexed array variable (see Arrays above). + -A Each name is an associative array variable (see Arrays above). + -f Use function names only. + -i The variable is treated as an integer; arithmetic evaluation (see ARITHMETIC EVALUA‐ + TION above) is performed when the variable is assigned a value. + -l When the variable is assigned a value, all upper-case characters are converted to + lower-case. The upper-case attribute is disabled. + -n Give each name the nameref attribute, making it a name reference to another variable. + That other variable is defined by the value of name. All references, assignments, and + attribute modifications to name, except those using or changing the -n attribute it‐ + self, are performed on the variable referenced by name's value. The nameref attribute + cannot be applied to array variables. + -r Make names readonly. These names cannot then be assigned values by subsequent assign‐ + ment statements or unset. + -t Give each name the trace attribute. Traced functions inherit the DEBUG and RETURN + traps from the calling shell. The trace attribute has no special meaning for vari‐ + ables. + -u When the variable is assigned a value, all lower-case characters are converted to up‐ + per-case. The lower-case attribute is disabled. + -x Mark names for export to subsequent commands via the environment. + + Using `+' instead of `-' turns off the attribute instead, with the exceptions that +a and +A + may not be used to destroy array variables and +r will not remove the readonly attribute. + When used in a function, declare and typeset make each name local, as with the local command, + unless the -g option is supplied. If a variable name is followed by =value, the value of the + variable is set to value. When using -a or -A and the compound assignment syntax to create + array variables, additional attributes do not take effect until subsequent assignments. The + return value is 0 unless an invalid option is encountered, an attempt is made to define a + function using ``-f foo=bar'', an attempt is made to assign a value to a readonly variable, + an attempt is made to assign a value to an array variable without using the compound assign‐ + ment syntax (see Arrays above), one of the names is not a valid shell variable name, an at‐ + tempt is made to turn off readonly status for a readonly variable, an attempt is made to turn + off array status for an array variable, or an attempt is made to display a non-existent func‐ + tion with -f. + + dirs [-clpv] [+n] [-n] + Without options, displays the list of currently remembered directories. The default display + is on a single line with directory names separated by spaces. Directories are added to the + list with the pushd command; the popd command removes entries from the list. The current di‐ + rectory is always the first directory in the stack. + -c Clears the directory stack by deleting all of the entries. + -l Produces a listing using full pathnames; the default listing format uses a tilde to + denote the home directory. + -p Print the directory stack with one entry per line. + -v Print the directory stack with one entry per line, prefixing each entry with its index + in the stack. + +n Displays the nth entry counting from the left of the list shown by dirs when invoked + without options, starting with zero. + -n Displays the nth entry counting from the right of the list shown by dirs when invoked + without options, starting with zero. + + The return value is 0 unless an invalid option is supplied or n indexes beyond the end of the + directory stack. + + disown [-ar] [-h] [jobspec ... | pid ... ] + Without options, remove each jobspec from the table of active jobs. If jobspec is not + present, and neither the -a nor the -r option is supplied, the current job is used. If the + -h option is given, each jobspec is not removed from the table, but is marked so that SIGHUP + is not sent to the job if the shell receives a SIGHUP. If no jobspec is supplied, the -a op‐ + tion means to remove or mark all jobs; the -r option without a jobspec argument restricts op‐ + eration to running jobs. The return value is 0 unless a jobspec does not specify a valid + job. + + echo [-neE] [arg ...] + Output the args, separated by spaces, followed by a newline. The return status is 0 unless a + write error occurs. If -n is specified, the trailing newline is suppressed. If the -e op‐ + tion is given, interpretation of the following backslash-escaped characters is enabled. The + -E option disables the interpretation of these escape characters, even on systems where they + are interpreted by default. The xpg_echo shell option may be used to dynamically determine + whether or not echo expands these escape characters by default. echo does not interpret -- + to mean the end of options. echo interprets the following escape sequences: + \a alert (bell) + \b backspace + \c suppress further output + \e + \E an escape character + \f form feed + \n new line + \r carriage return + \t horizontal tab + \v vertical tab + \\ backslash + \0nnn the eight-bit character whose value is the octal value nnn (zero to three octal dig‐ + its) + \xHH the eight-bit character whose value is the hexadecimal value HH (one or two hex dig‐ + its) + \uHHHH the Unicode (ISO/IEC 10646) character whose value is the hexadecimal value HHHH (one + to four hex digits) + \UHHHHHHHH + the Unicode (ISO/IEC 10646) character whose value is the hexadecimal value HHHHHHHH + (one to eight hex digits) + + enable [-a] [-dnps] [-f filename] [name ...] + Enable and disable builtin shell commands. Disabling a builtin allows a disk command which + has the same name as a shell builtin to be executed without specifying a full pathname, even + though the shell normally searches for builtins before disk commands. If -n is used, each + name is disabled; otherwise, names are enabled. For example, to use the test binary found + via the PATH instead of the shell builtin version, run ``enable -n test''. The -f option + means to load the new builtin command name from shared object filename, on systems that sup‐ + port dynamic loading. The -d option will delete a builtin previously loaded with -f. If no + name arguments are given, or if the -p option is supplied, a list of shell builtins is + printed. With no other option arguments, the list consists of all enabled shell builtins. + If -n is supplied, only disabled builtins are printed. If -a is supplied, the list printed + includes all builtins, with an indication of whether or not each is enabled. If -s is sup‐ + plied, the output is restricted to the POSIX special builtins. The return value is 0 unless + a name is not a shell builtin or there is an error loading a new builtin from a shared ob‐ + ject. + + eval [arg ...] + The args are read and concatenated together into a single command. This command is then read + and executed by the shell, and its exit status is returned as the value of eval. If there + are no args, or only null arguments, eval returns 0. + + exec [-cl] [-a name] [command [arguments]] + If command is specified, it replaces the shell. No new process is created. The arguments + become the arguments to command. If the -l option is supplied, the shell places a dash at + the beginning of the zeroth argument passed to command. This is what login(1) does. The -c + option causes command to be executed with an empty environment. If -a is supplied, the shell + passes name as the zeroth argument to the executed command. If command cannot be executed + for some reason, a non-interactive shell exits, unless the execfail shell option is enabled. + In that case, it returns failure. An interactive shell returns failure if the file cannot be + executed. A subshell exits unconditionally if exec fails. If command is not specified, any + redirections take effect in the current shell, and the return status is 0. If there is a re‐ + direction error, the return status is 1. + + exit [n] + Cause the shell to exit with a status of n. If n is omitted, the exit status is that of the + last command executed. A trap on EXIT is executed before the shell terminates. + + export [-fn] [name[=word]] ... + export -p + The supplied names are marked for automatic export to the environment of subsequently exe‐ + cuted commands. If the -f option is given, the names refer to functions. If no names are + given, or if the -p option is supplied, a list of names of all exported variables is printed. + The -n option causes the export property to be removed from each name. If a variable name is + followed by =word, the value of the variable is set to word. export returns an exit status + of 0 unless an invalid option is encountered, one of the names is not a valid shell variable + name, or -f is supplied with a name that is not a function. + + fc [-e ename] [-lnr] [first] [last] + fc -s [pat=rep] [cmd] + The first form selects a range of commands from first to last from the history list and dis‐ + plays or edits and re-executes them. First and last may be specified as a string (to locate + the last 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). If last is + not specified, it is set to the current command for listing (so that ``fc -l -10'' prints the + last 10 commands) and to first otherwise. If first is not specified, it is set to the previ‐ + ous command for editing and -16 for listing. + + The -n option suppresses the command numbers when listing. The -r option reverses the order + of the commands. If the -l option is given, the commands are listed on standard output. + Otherwise, the editor given by ename is invoked on a file containing those commands. If + ename is not given, the value of the FCEDIT variable is used, and the value of EDITOR if + FCEDIT is not set. If neither variable is set, vi is used. When editing is complete, the + edited commands are echoed and executed. + + In the second form, command is re-executed after each instance of pat is replaced by rep. + Command is interpreted the same as first above. A useful alias to use with this is ``r="fc + -s"'', so that typing ``r cc'' runs the last command beginning with ``cc'' and typing ``r'' + re-executes the last command. + + If the first form is used, the return value is 0 unless an invalid option is encountered or + first or last specify history lines out of range. If the -e option is supplied, the return + value is the value of the last command executed or failure if an error occurs with the tempo‐ + rary file of commands. If the second form is used, the return status is that of the command + re-executed, unless cmd does not specify a valid history line, in which case fc returns fail‐ + ure. + + fg [jobspec] + Resume jobspec in the foreground, and make it the current job. If jobspec is not present, + the shell's notion of the current job is used. The return value is that of the command + placed into the foreground, or failure if run when job control is disabled or, when run with + job control enabled, if jobspec does not specify a valid job or jobspec specifies a job that + was started without job control. + + getopts optstring name [args] + getopts is used by shell procedures to parse positional parameters. optstring contains the + option characters to be recognized; if a character is followed by a colon, the option is ex‐ + pected to have an argument, which should be separated from it by white space. The colon and + question mark characters may not be used as option characters. Each time it is invoked, + getopts places the next option in the shell variable name, initializing name if it does not + exist, and the index of the next argument to be processed into the variable OPTIND. OPTIND + is initialized to 1 each time the shell or a shell script is invoked. When an option re‐ + quires an argument, getopts places that argument into the variable OPTARG. The shell does + not reset OPTIND automatically; it must be manually reset between multiple calls to getopts + within the same shell invocation if a new set of parameters is to be used. + + When the end of options is encountered, getopts exits with a return value greater than zero. + OPTIND is set to the index of the first non-option argument, and name is set to ?. + + getopts normally parses the positional parameters, but if more arguments are given in args, + getopts parses those instead. + + getopts can report errors in two ways. If the first character of optstring is a colon, + silent error reporting is used. In normal operation, diagnostic messages are printed when + invalid options or missing option arguments are encountered. If the variable OPTERR is set + to 0, no error messages will be displayed, even if the first character of optstring is not a + colon. + + If an invalid option is seen, getopts places ? into name and, if not silent, prints an error + message and unsets OPTARG. If getopts is silent, the option character found is placed in OP‐ + TARG and no diagnostic message is printed. + + If a required argument is not found, and getopts is not silent, a question mark (?) is placed + in name, OPTARG is unset, and a diagnostic message is printed. If getopts is silent, then a + colon (:) is placed in name and OPTARG is set to the option character found. + + getopts returns true if an option, specified or unspecified, is found. It returns false if + the end of options is encountered or an error occurs. + + hash [-lr] [-p filename] [-dt] [name] + Each time hash is invoked, the full pathname of the command name is determined by searching + the directories in $PATH and remembered. Any previously-remembered pathname is discarded. + If the -p option is supplied, no path search is performed, and filename is used as the full + filename of the command. The -r option causes the shell to forget all remembered locations. + The -d option causes the shell to forget the remembered location of each name. If the -t op‐ + tion is supplied, the full pathname to which each name corresponds is printed. If multiple + name arguments are supplied with -t, the name is printed before the hashed full pathname. + The -l option causes output to be displayed in a format that may be reused as input. If no + arguments are given, or if only -l is supplied, information about remembered commands is + printed. The return status is true unless a name is not found or an invalid option is sup‐ + plied. + + help [-dms] [pattern] + Display helpful information about builtin commands. If pattern is specified, help gives de‐ + tailed help on all commands matching pattern; otherwise help for all the builtins and shell + control structures is printed. + -d Display a short description of each pattern + -m Display the description of each pattern in a manpage-like format + -s Display only a short usage synopsis for each pattern + + The return status is 0 unless no command matches pattern. + + history [n] + history -c + history -d offset + history -d start-end + history -anrw [filename] + history -p arg [arg ...] + history -s arg [arg ...] + With no options, display the command history list with line numbers. Lines listed with a * + have been modified. An argument of n lists only the last n lines. 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. No intervening blank is printed + between the formatted time stamp and the history line. If filename is supplied, it is used + as the name of the history file; if not, the value of HISTFILE is used. Options, if sup‐ + plied, have the following meanings: + -c Clear the history list by deleting all the entries. + -d offset + Delete the history entry at position offset. 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 history entries between positions start and end, inclusive. Positive and + negative values for start and end are interpreted as described above. + -a Append the ``new'' 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 his‐ + tory file. + -n Read the history lines not already read from the history file into the current history + list. These are lines appended to the history file since the beginning of the current + bash session. + -r Read the contents of the history file and append them to the current history list. + -w Write the current history list to the history file, overwriting the history file's + contents. + -p Perform history substitution on the following args and display the result on the stan‐ + dard output. Does not store the results in the history list. Each arg must be quoted + to disable normal history expansion. + -s Store the args in the history list as a single entry. The last command in the history + list is removed before the args are added. + + If the HISTTIMEFORMAT variable is set, the time stamp information associated with each his‐ + tory entry is written to the history file, marked with the history comment character. When + the history file is read, lines beginning with the history comment character followed immedi‐ + ately 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 while reading or writing + the history file, an invalid offset is supplied as an argument to -d, or the history expan‐ + sion supplied as an argument to -p fails. + + jobs [-lnprs] [ jobspec ... ] + jobs -x command [ args ... ] + The first form lists the active jobs. The options have the following meanings: + -l List process IDs in addition to the normal information. + -n Display information only about jobs that have changed status since the user was last + notified of their status. + -p List only the process ID of the job's process group leader. + -r Display only running jobs. + -s Display only stopped jobs. + + If jobspec is given, output is restricted to information about that job. The return status + is 0 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 args with the + corresponding process group ID, and executes command passing it args, returning its exit sta‐ + tus. + + kill [-s sigspec | -n signum | -sigspec] [pid | jobspec] ... + kill -l|-L [sigspec | exit_status] + Send the signal named by sigspec or signum to the processes named by pid or jobspec. sigspec + is either a case-insensitive signal name such as SIGKILL (with or without the SIG prefix) or + a signal number; signum is a signal number. If sigspec is not present, then SIGTERM is as‐ + sumed. An argument of -l lists the signal names. If any arguments are supplied when -l is + given, the names of the signals corresponding to the arguments are listed, and the return + status is 0. The exit_status argument to -l is a number specifying either a signal number or + the exit status of a process terminated by a signal. The -L option is equivalent to -l. + kill returns true if at least one signal was successfully sent, or false if an error occurs + or an invalid option is encountered. + + let arg [arg ...] + Each arg is an arithmetic expression to be evaluated (see ARITHMETIC EVALUATION above). If + the last arg evaluates to 0, let returns 1; 0 is returned otherwise. + + local [option] [name[=value] ... | - ] + For each argument, a local variable named name is created, and assigned value. The option + can be any of the options accepted by declare. When local is used within a function, it + causes the variable name to have a visible scope restricted to that function and its chil‐ + dren. If name is -, the set of shell options is made local to the function in which local is + invoked: shell options changed using the set builtin inside the function are restored to + their original values when the function returns. With no operands, local writes a list of + local variables to the standard output. It is an error to use local when not within a func‐ + tion. The return status is 0 unless local is used outside a function, an invalid name is + supplied, or name is a readonly variable. + + logout Exit a login shell. + + mapfile [-d delim] [-n count] [-O origin] [-s count] [-t] [-u fd] [-C callback] [-c quantum] [array] + readarray [-d delim] [-n count] [-O origin] [-s count] [-t] [-u fd] [-C callback] [-c quantum] [ar‐ + ray] + Read lines from the standard input into the indexed array variable array, or from file de‐ + scriptor fd if the -u option is supplied. The variable MAPFILE is the default array. Op‐ + tions, if supplied, have the following meanings: + -d The first character of delim is used to terminate each input line, rather than new‐ + line. If delim is the empty string, mapfile will terminate a line when it reads a NUL + character. + -n Copy at most count lines. If count is 0, all lines are copied. + -O Begin assigning to array at index origin. The default index is 0. + -s Discard the first count lines read. + -t Remove a trailing delim (default newline) from each line read. + -u Read lines from file descriptor fd instead of the standard input. + -C Evaluate callback each time quantum lines are read. The -c option specifies quantum. + -c Specify the number of lines read between each call to callback. + + If -C is specified without -c, the default quantum is 5000. When callback is evaluated, it + is supplied the index of the next array element to be assigned and the line to be assigned to + that element as additional arguments. callback is evaluated after the line is read but be‐ + fore the array element is assigned. + + If not supplied with an explicit origin, mapfile will clear array before assigning to it. + + mapfile returns successfully unless an invalid option or option argument is supplied, array + is invalid or unassignable, or if array is not an indexed array. + + popd [-n] [+n] [-n] + Removes entries from the directory stack. With no arguments, removes the top directory from + the stack, and performs a cd to the new top directory. Arguments, if supplied, have the fol‐ + lowing meanings: + -n Suppresses the normal change of directory when removing directories from the stack, so + that only the stack is manipulated. + +n Removes the nth entry counting from the left of the list shown by dirs, starting with + zero. For example: ``popd +0'' removes the first directory, ``popd +1'' the second. + -n Removes the nth entry counting from the right of the list shown by dirs, starting with + zero. For example: ``popd -0'' removes the last directory, ``popd -1'' the next to + last. + + If the popd command is successful, a dirs is performed as well, and the return status is 0. + popd returns false if an invalid option is encountered, the directory stack is empty, a non- + existent directory stack entry is specified, or the directory change fails. + + printf [-v var] format [arguments] + Write the formatted arguments to the standard output under the control of the format. The -v + option causes the output to be assigned to the variable var rather than being printed to the + standard output. + + The format is a character string which contains three types of objects: plain characters, + which are simply copied to standard output, character escape sequences, which are converted + and copied to the standard output, and format specifications, each of which causes printing + of the next successive argument. In addition to the standard printf(1) format specifica‐ + tions, printf interprets the following extensions: + %b causes printf to expand backslash escape sequences in the corresponding argument in + the same way as echo -e. + %q causes printf to output the corresponding argument in a format that can be reused as + shell input. + %(datefmt)T + causes printf to output the date-time string resulting from using datefmt as a format + string for strftime(3). The corresponding argument is an integer representing the + number of seconds since the epoch. Two special argument values may be used: -1 repre‐ + sents the current time, and -2 represents the time the shell was invoked. If no argu‐ + ment is specified, conversion behaves as if -1 had been given. This is an exception + to the usual printf behavior. + + Arguments to non-string format specifiers are treated as C constants, except that a leading + plus or minus sign is allowed, and if the leading character is a single or double quote, the + value is the ASCII value of the following character. + + The format is reused as necessary to consume all of the arguments. If the format requires + more arguments than are supplied, the extra format specifications behave as if a zero value + or null string, as appropriate, had been supplied. The return value is zero on success, non- + zero on failure. + + pushd [-n] [+n] [-n] + pushd [-n] [dir] + Adds a directory to the top of the directory stack, or rotates the stack, making the new top + of the stack the current working directory. With no arguments, pushd exchanges the top two + directories and returns 0, unless the directory stack is empty. Arguments, if supplied, have + the following meanings: + -n Suppresses the normal change of directory when rotating or adding directories to the + stack, so that only the stack is manipulated. + +n Rotates the stack so that the nth directory (counting from the left of the list shown + by dirs, starting with zero) is at the top. + -n Rotates the stack so that the nth directory (counting from the right of the list shown + by dirs, starting with zero) is at the top. + dir Adds dir to the directory stack at the top, making it the new current working direc‐ + tory as if it had been supplied as the argument to the cd builtin. + + If the pushd command is successful, a dirs is performed as well. If the first form is used, + pushd returns 0 unless the cd to dir fails. With the second form, pushd returns 0 unless the + directory stack is empty, a non-existent directory stack element is specified, or the direc‐ + tory change to the specified new current directory fails. + + pwd [-LP] + Print the absolute pathname of the current working directory. The pathname printed contains + no symbolic links if the -P option is supplied or the -o physical option to the set builtin + command is enabled. If the -L option is used, the pathname printed may contain symbolic + links. The return status is 0 unless an error occurs while reading the name of the current + directory or an invalid option is supplied. + + read [-ers] [-a aname] [-d delim] [-i text] [-n nchars] [-N nchars] [-p prompt] [-t timeout] [-u fd] + [name ...] + One line is read from the standard input, or from the file descriptor fd supplied as an argu‐ + ment to the -u option, split into words as described above under Word Splitting, and the + first word is assigned to the first name, the second word to the second name, and so on. If + there are more words than names, the remaining words and their intervening delimiters are as‐ + signed to the last name. If there are fewer words read from the input stream than names, the + remaining names are assigned empty values. The characters in IFS are used to split the line + into words using the same rules the shell uses for expansion (described above under Word + Splitting). The backslash character (\) may be used to remove any special meaning for the + next character read and for line continuation. Options, if supplied, have the following + meanings: + -a aname + The words are assigned to sequential indices of the array variable aname, starting at + 0. aname is unset before any new values are assigned. Other name arguments are ig‐ + nored. + -d delim + The first character of delim is used to terminate the input line, rather than newline. + If delim is the empty string, read will terminate a line when it reads a NUL charac‐ + ter. + -e If the standard input is coming from a terminal, readline (see READLINE above) is used + to obtain the line. Readline uses the current (or default, if line editing was not + previously active) editing settings, but uses Readline's default filename completion. + -i text + If readline is being used to read the line, text is placed into the editing buffer be‐ + fore editing begins. + -n nchars + read returns after reading nchars characters rather than waiting for a complete line + of input, but honors a delimiter if fewer than nchars characters are read before the + delimiter. + -N nchars + read returns after reading exactly nchars characters rather than waiting for a com‐ + plete line of input, unless EOF is encountered or read times out. Delimiter charac‐ + ters encountered in the input are not treated specially and do not cause read to re‐ + turn until nchars characters are read. The result is not split on the characters in + IFS; the intent is that the variable is assigned exactly the characters read (with the + exception of backslash; see the -r option below). + -p prompt + Display prompt on standard error, without a trailing newline, before attempting to + read any input. The prompt is displayed only if input is coming from a terminal. + -r Backslash does not act as an escape character. The backslash is considered to be part + of the line. In particular, a backslash-newline pair may not then be used as a line + continuation. + -s Silent mode. If input is coming from a terminal, characters are not echoed. + -t timeout + Cause read to time out and return failure if a complete line of input (or a specified + number of characters) is not read within timeout seconds. timeout may be a decimal + number with a fractional portion following the decimal point. This option is only ef‐ + fective if read is reading input from a terminal, pipe, or other special file; it has + no effect when reading from regular files. If read times out, read saves any partial + input read into the specified variable name. If timeout is 0, read returns immedi‐ + ately, without trying to read any data. The exit status is 0 if input is available on + the specified file descriptor, non-zero otherwise. The exit status is greater than + 128 if the timeout is exceeded. + -u fd Read input from file descriptor fd. + + If no names are supplied, the line read is assigned to the variable REPLY. The exit status + is zero, unless end-of-file is encountered, read times out (in which case the status is + greater than 128), a variable assignment error (such as assigning to a readonly variable) oc‐ + curs, or an invalid file descriptor is supplied as the argument to -u. + + readonly [-aAf] [-p] [name[=word] ...] + The given names are marked readonly; the values of these names may not be changed by subse‐ + quent assignment. If the -f option is supplied, the functions corresponding to the names are + so marked. The -a option restricts the variables to indexed arrays; the -A option restricts + the variables to associative arrays. If both options are supplied, -A takes precedence. If + no name arguments are given, or if the -p option is supplied, a list of all readonly names is + printed. The other options may be used to restrict the output to a subset of the set of + readonly names. The -p option causes output to be displayed in a format that may be reused + as input. If a variable name is followed by =word, the value of the variable is set to word. + The return status is 0 unless an invalid option is encountered, one of the names is not a + valid shell variable name, or -f is supplied with a name that is not a function. + + return [n] + Causes a function to stop executing and return the value specified by n to its caller. If n + is omitted, the return status is that of the last command executed in the function body. If + return is executed by a trap handler, the last command used to determine the status is the + last command executed before the trap handler. If return is executed during a DEBUG trap, + the last command used to determine the status is the last command executed by the trap han‐ + dler before return was invoked. If return is used outside a function, but during execution + of a script by the . (source) command, it causes the shell to stop executing that script and + return either n or the exit status of the last command executed within the script as the exit + status of the script. If n is supplied, the return value is its least significant 8 bits. + The return status is non-zero if return is supplied a non-numeric argument, or is used out‐ + side a function and not during execution of a script by . or source. Any command associated + with the RETURN trap is executed before execution resumes after the function or script. + + set [--abefhkmnptuvxBCEHPT] [-o option-name] [arg ...] + set [+abefhkmnptuvxBCEHPT] [+o option-name] [arg ...] + Without options, the name and value of each shell variable are displayed in a format that can + be reused as input for setting or resetting the currently-set variables. Read-only variables + cannot be reset. In posix mode, only shell variables are listed. The output is sorted ac‐ + cording to the current locale. When options are specified, they set or unset shell at‐ + tributes. Any arguments remaining after option processing are treated as values for the po‐ + sitional parameters and are assigned, in order, to $1, $2, ... $n. Options, if specified, + have the following meanings: + -a Each variable or function that is created or modified is given the export attribute + and marked for export to the environment of subsequent commands. + -b Report the status of terminated background jobs immediately, rather than before the + next primary prompt. This is effective only when job control is enabled. + -e Exit immediately if a pipeline (which may consist of a single simple command), a + list, or a compound command (see SHELL GRAMMAR above), exits with a non-zero status. + The shell does not exit if the command that fails is part of the command list immedi‐ + ately following a while or until keyword, part of the test following the if or elif + reserved words, part of any command executed in a && or || list except the command + following the final && or ||, any command in a pipeline but the last, or if the com‐ + mand's return value is being inverted with !. If a compound command other than a + subshell returns a non-zero status because a command failed while -e was being ig‐ + nored, the shell does not exit. A trap on ERR, if set, is executed before the shell + exits. This option applies to the shell environment and each subshell environment + separately (see COMMAND EXECUTION ENVIRONMENT above), and may cause subshells to exit + before executing all the commands in the subshell. + + If a compound command or shell function executes in a context where -e is being ig‐ + nored, none of the commands executed within the compound command or function body + will be affected by the -e setting, even if -e is set and a command returns a failure + status. If a compound command or shell function sets -e while executing in a context + where -e is ignored, that setting will not have any effect until the compound command + or the command containing the function call completes. + -f Disable pathname expansion. + -h Remember the location of commands as they are looked up for execution. This is en‐ + abled by default. + -k All arguments in the form of assignment statements are placed in the environment for + a command, not just those that precede the command name. + -m Monitor mode. Job control is enabled. This option is on by default for interactive + shells on systems that support it (see JOB CONTROL above). All processes run in a + separate process group. When a background job completes, the shell prints a line + containing its exit status. + -n Read commands but do not execute them. This may be used to check a shell script for + syntax errors. This is ignored by interactive shells. + -o option-name + The option-name can be one of the following: + allexport + Same as -a. + braceexpand + Same as -B. + emacs Use an emacs-style command line editing interface. This is enabled by de‐ + fault when the shell is interactive, unless the shell is started with the + --noediting option. This also affects the editing interface used for read + -e. + errexit Same as -e. + errtrace + Same as -E. + functrace + Same as -T. + hashall Same as -h. + histexpand + Same as -H. + history Enable command history, as described above under HISTORY. This option is on + by default in interactive shells. + ignoreeof + The effect is as if the shell command ``IGNOREEOF=10'' had been executed (see + Shell Variables above). + keyword Same as -k. + monitor Same as -m. + noclobber + Same as -C. + noexec Same as -n. + noglob Same as -f. + nolog Currently ignored. + notify Same as -b. + nounset Same as -u. + onecmd Same as -t. + physical + Same as -P. + pipefail + If set, the return value of a pipeline is the value of the last (rightmost) + command to exit with a non-zero status, or zero if all commands in the pipe‐ + line exit successfully. This option is disabled by default. + posix Change the behavior of bash where the default operation differs from the + POSIX standard to match the standard (posix mode). See SEE ALSO below for a + reference to a document that details how posix mode affects bash's behavior. + privileged + Same as -p. + verbose Same as -v. + vi Use a vi-style command line editing interface. This also affects the editing + interface used for read -e. + xtrace Same as -x. + If -o is supplied with no option-name, the values of the current options are printed. + If +o is supplied with no option-name, a series of set commands to recreate the cur‐ + rent option settings is displayed on the standard output. + -p Turn on privileged mode. In this mode, the $ENV and $BASH_ENV files are not pro‐ + cessed, shell functions are not inherited from the environment, and the SHELLOPTS, + BASHOPTS, CDPATH, and GLOBIGNORE variables, if they appear in the environment, are + ignored. If the shell is started with the effective user (group) id not equal to the + real user (group) id, and the -p option is not supplied, these actions are taken and + the effective user id is set to the real user id. If the -p option is supplied at + startup, the effective user id is not reset. Turning this option off causes the ef‐ + fective user and group ids to be set to the real user and group ids. + -t Exit after reading and executing one command. + -u Treat unset variables and parameters other than the special parameters "@" and "*" as + an error when performing parameter expansion. If expansion is attempted on an unset + variable or parameter, the shell prints an error message, and, if not interactive, + exits with a non-zero status. + -v Print shell input lines as they are read. + -x After expanding each simple command, for command, case command, select command, or + arithmetic for command, display the expanded value of PS4, followed by the command + and its expanded arguments or associated word list. + -B The shell performs brace expansion (see Brace Expansion above). This is on by de‐ + fault. + -C If set, bash does not overwrite an existing file with the >, >&, and <> redirection + operators. This may be overridden when creating output files by using the redirect‐ + ion operator >| instead of >. + -E If set, any trap on ERR is inherited by shell functions, command substitutions, and + commands executed in a subshell environment. The ERR trap is normally not inherited + in such cases. + -H Enable ! style history substitution. This option is on by default when the shell is + interactive. + -P If set, the shell does not resolve symbolic links when executing commands such as cd + that change the current working directory. It uses the physical directory structure + instead. By default, bash follows the logical chain of directories when performing + commands which change the current directory. + -T If set, any traps on DEBUG and RETURN are inherited by shell functions, command sub‐ + stitutions, and commands executed in a subshell environment. The DEBUG and RETURN + traps are normally not inherited in such cases. + -- If no arguments follow this option, then the positional parameters are unset. Other‐ + wise, the positional parameters are set to the args, even if some of them begin with + a -. + - Signal the end of options, cause all remaining args to be assigned to the positional + parameters. The -x and -v options are turned off. If there are no args, the posi‐ + tional parameters remain unchanged. + + The options are off by default unless otherwise noted. Using + rather than - causes these + options to be turned off. The options can also be specified as arguments to an invocation of + the shell. The current set of options may be found in $-. The return status is always true + unless an invalid option is encountered. + + shift [n] + The positional parameters from n+1 ... are renamed to $1 .... Parameters represented by the + numbers $# down to $#-n+1 are unset. n must be a non-negative number less than or equal to + $#. If n is 0, no parameters are changed. If n is not given, it is assumed to be 1. If n + is greater than $#, the positional parameters are not changed. The return status is greater + than zero if n is greater than $# or less than zero; otherwise 0. + + shopt [-pqsu] [-o] [optname ...] + Toggle the values of settings controlling optional shell behavior. The settings can be ei‐ + ther those listed below, or, if the -o option is used, those available with the -o option to + the set builtin command. With no options, or with the -p option, a list of all settable op‐ + tions is displayed, with an indication of whether or not each is set; if optnames are sup‐ + plied, the output is restricted to those options. The -p option causes output to be dis‐ + played in a form that may be reused as input. Other options have the following meanings: + -s Enable (set) each optname. + -u Disable (unset) each optname. + -q Suppresses normal output (quiet mode); the return status indicates whether the optname + is set or unset. If multiple optname arguments are given with -q, the return status + is zero if all optnames are enabled; non-zero otherwise. + -o Restricts the values of optname to be those defined for the -o option to the set + builtin. + + If either -s or -u is used with no optname arguments, shopt shows only those options which + are set or unset, respectively. Unless otherwise noted, the shopt options are disabled (un‐ + set) by default. + + The return status when listing options is zero if all optnames are enabled, non-zero other‐ + wise. When setting or unsetting options, the return status is zero unless an optname is not + a valid shell option. + + The list of shopt options is: + + assoc_expand_once + If set, the shell suppresses multiple evaluation of associative array subscripts dur‐ + ing arithmetic expression evaluation, while executing builtins that can perform vari‐ + able assignments, and while executing builtins that perform array dereferencing. + autocd If set, a command name that is the name of a directory is executed as if it were the + argument to the cd command. This option is only used by interactive shells. + cdable_vars + If set, an argument to the cd builtin command that is not a directory is assumed to + be the name of a variable whose value is the directory to change to. + cdspell If set, minor errors in the spelling of a directory component in a cd command will be + corrected. The errors checked for are transposed characters, a missing character, + and one character too many. If a correction is found, the corrected filename is + printed, and the command proceeds. This option is only used by interactive shells. + checkhash + If set, bash checks that a command found in the hash table exists before trying to + execute it. If a hashed command no longer exists, a normal path search is performed. + checkjobs + If set, bash lists the status of any stopped and running jobs before exiting an in‐ + teractive shell. If any jobs are running, this causes the exit to be deferred until + a second exit is attempted without an intervening command (see JOB CONTROL above). + The shell always postpones exiting if any jobs are stopped. + checkwinsize + If set, bash checks the window size after each external (non-builtin) command and, if + necessary, updates the values of LINES and COLUMNS. This option is enabled by de‐ + fault. + cmdhist If set, bash attempts to save all lines of a multiple-line command in the same his‐ + tory entry. This allows easy re-editing of multi-line commands. This option is en‐ + abled by default, but only has an effect if command history is enabled, as described + above under HISTORY. + compat31 + If set, bash changes its behavior to that of version 3.1 with respect to quoted argu‐ + ments to the [[ conditional command's =~ operator and locale-specific string compari‐ + son when using the [[ conditional command's < and > operators. Bash versions prior + to bash-4.1 use ASCII collation and strcmp(3); bash-4.1 and later use the current lo‐ + cale's collation sequence and strcoll(3). + compat32 + If set, bash changes its behavior to that of version 3.2 with respect to locale-spe‐ + cific string comparison when using the [[ conditional command's < and > operators + (see previous item) and the effect of interrupting a command list. Bash versions 3.2 + and earlier continue with the next command in the list after one terminates due to an + interrupt. + compat40 + If set, bash changes its behavior to that of version 4.0 with respect to locale-spe‐ + cific string comparison when using the [[ conditional command's < and > operators + (see description of compat31) and the effect of interrupting a command list. Bash + versions 4.0 and later interrupt the list as if the shell received the interrupt; + previous versions continue with the next command in the list. + compat41 + If set, bash, when in posix mode, treats a single quote in a double-quoted parameter + expansion as a special character. The single quotes must match (an even number) and + the characters between the single quotes are considered quoted. This is the behavior + of posix mode through version 4.1. The default bash behavior remains as in previous + versions. + compat42 + If set, bash does not process the replacement string in the pattern substitution word + expansion using quote removal. + compat43 + If set, bash does not print a warning message if an attempt is made to use a quoted + compound array assignment as an argument to declare, makes word expansion errors non- + fatal errors that cause the current command to fail (the default behavior is to make + them fatal errors that cause the shell to exit), and does not reset the loop state + when a shell function is executed (this allows break or continue in a shell function + to affect loops in the caller's context). + compat44 + If set, bash saves the positional parameters to BASH_ARGV and BASH_ARGC before they + are used, regardless of whether or not extended debugging mode is enabled. + complete_fullquote + If set, bash quotes all shell metacharacters in filenames and directory names when + performing completion. If not set, bash removes metacharacters such as the dollar + sign from the set of characters that will be quoted in completed filenames when these + metacharacters appear in shell variable references in words to be completed. This + means that dollar signs in variable names that expand to directories will not be + quoted; however, any dollar signs appearing in filenames will not be quoted, either. + This is active only when bash is using backslashes to quote completed filenames. + This variable is set by default, which is the default bash behavior in versions + through 4.2. + direxpand + If set, bash replaces directory names with the results of word expansion when per‐ + forming filename completion. This changes the contents of the readline editing buf‐ + fer. If not set, bash attempts to preserve what the user typed. + dirspell + If set, bash attempts spelling correction on directory names during word completion + if the directory name initially supplied does not exist. + dotglob If set, bash includes filenames beginning with a `.' in the results of pathname ex‐ + pansion. The filenames ``.'' and ``..'' must always be matched explicitly, even if + dotglob is set. + execfail + If set, a non-interactive shell will not exit if it cannot execute the file specified + as an argument to the exec builtin command. An interactive shell does not exit if + exec fails. + expand_aliases + If set, aliases are expanded as described above under ALIASES. This option is en‐ + abled by default for interactive shells. + extdebug + If set at shell invocation, arrange to execute the debugger profile before the shell + starts, identical to the --debugger option. If set after invocation, behavior in‐ + tended for use by debuggers is enabled: + 1. The -F option to the declare builtin displays the source file name and line + number corresponding to each function name supplied as an argument. + 2. If the command run by the DEBUG trap returns a non-zero value, the next com‐ + mand is skipped and not executed. + 3. If the command run by the DEBUG trap returns a value of 2, and the shell is + executing in a subroutine (a shell function or a shell script executed by the + . or source builtins), the shell simulates a call to return. + 4. BASH_ARGC and BASH_ARGV are updated as described in their descriptions above. + 5. Function tracing is enabled: command substitution, shell functions, and sub‐ + shells invoked with ( command ) inherit the DEBUG and RETURN traps. + 6. Error tracing is enabled: command substitution, shell functions, and subshells + invoked with ( command ) inherit the ERR trap. + extglob If set, the extended pattern matching features described above under Pathname Expan‐ + sion are enabled. + extquote + If set, $'string' and $"string" quoting is performed within ${parameter} expansions + enclosed in double quotes. This option is enabled by default. + failglob + If set, patterns which fail to match filenames during pathname expansion result in an + expansion error. + force_fignore + If set, the suffixes specified by the FIGNORE shell variable cause words to be ig‐ + nored when performing word completion even if the ignored words are the only possible + completions. See SHELL VARIABLES above for a description of FIGNORE. This option is + enabled by default. + globasciiranges + If set, range expressions used in pattern matching bracket expressions (see Pattern + Matching above) behave as if in the traditional C locale when performing comparisons. + That is, the current locale's collating sequence is not taken into account, so b will + not collate between A and B, and upper-case and lower-case ASCII characters will col‐ + late together. + globstar + If set, the pattern ** used in a pathname expansion context will match all files and + zero or more directories and subdirectories. If the pattern is followed by a /, only + directories and subdirectories match. + gnu_errfmt + If set, shell error messages are written in the standard GNU error message format. + histappend + If set, the history list is appended to the file named by the value of the HISTFILE + variable when the shell exits, rather than overwriting the file. + histreedit + If set, and readline is being used, a user is given the opportunity to re-edit a + failed history substitution. + histverify + If set, and readline is being used, the results of history substitution are not imme‐ + diately passed to the shell parser. Instead, the resulting line is loaded into the + readline editing buffer, allowing further modification. + hostcomplete + If set, and readline is being used, bash will attempt to perform hostname completion + when a word containing a @ is being completed (see Completing under READLINE above). + This is enabled by default. + huponexit + If set, bash will send SIGHUP to all jobs when an interactive login shell exits. + inherit_errexit + If set, command substitution inherits the value of the errexit option, instead of un‐ + setting it in the subshell environment. This option is enabled when posix mode is + enabled. + interactive_comments + If set, allow a word beginning with # to cause that word and all remaining characters + on that line to be ignored in an interactive shell (see COMMENTS above). This option + is enabled by default. + lastpipe + If set, and job control is not active, the shell runs the last command of a pipeline + not executed in the background in the current shell environment. + lithist If set, and the cmdhist option is enabled, multi-line commands are saved to the his‐ + tory with embedded newlines rather than using semicolon separators where possible. + localvar_inherit + If set, local variables inherit the value and attributes of a variable of the same + name that exists at a previous scope before any new value is assigned. The nameref + attribute is not inherited. + localvar_unset + If set, calling unset on local variables in previous function scopes marks them so + subsequent lookups find them unset until that function returns. This is identical to + the behavior of unsetting local variables at the current function scope. + login_shell + The shell sets this option if it is started as a login shell (see INVOCATION above). + The value may not be changed. + mailwarn + If set, and a file that bash is checking for mail has been accessed since the last + time it was checked, the message ``The mail in mailfile has been read'' is displayed. + no_empty_cmd_completion + If set, and readline is being used, bash will not attempt to search the PATH for pos‐ + sible completions when completion is attempted on an empty line. + nocaseglob + If set, bash matches filenames in a case-insensitive fashion when performing pathname + expansion (see Pathname Expansion above). + nocasematch + If set, bash matches patterns in a case-insensitive fashion when performing matching + while executing case or [[ conditional commands, when performing pattern substitution + word expansions, or when filtering possible completions as part of programmable com‐ + pletion. + nullglob + If set, bash allows patterns which match no files (see Pathname Expansion above) to + expand to a null string, rather than themselves. + progcomp + If set, the programmable completion facilities (see Programmable Completion above) + are enabled. This option is enabled by default. + progcomp_alias + If set, and programmable completion is enabled, bash treats a command name that + doesn't have any completions as a possible alias and attempts alias expansion. If it + has an alias, bash attempts programmable completion using the command word resulting + from the expanded alias. + promptvars + If set, prompt strings undergo parameter expansion, command substitution, arithmetic + expansion, and quote removal after being expanded as described in PROMPTING above. + This option is enabled by default. + restricted_shell + The shell sets this option if it is started in restricted mode (see RESTRICTED SHELL + below). The value may not be changed. This is not reset when the startup files are + executed, allowing the startup files to discover whether or not a shell is re‐ + stricted. + shift_verbose + If set, the shift builtin prints an error message when the shift count exceeds the + number of positional parameters. + sourcepath + If set, the source (.) builtin uses the value of PATH to find the directory contain‐ + ing the file supplied as an argument. This option is enabled by default. + xpg_echo + If set, the echo builtin expands backslash-escape sequences by default. + + suspend [-f] + Suspend the execution of this shell until it receives a SIGCONT signal. A login shell cannot + be suspended; the -f option can be used to override this and force the suspension. The re‐ + turn status is 0 unless the shell is a login shell and -f is not supplied, or if job control + is not enabled. + + test expr + [ expr ] + Return a status of 0 (true) or 1 (false) depending on the evaluation of the conditional ex‐ + pression expr. Each operator and operand must be a separate argument. Expressions are com‐ + posed of the primaries described above under CONDITIONAL EXPRESSIONS. test does not accept + any options, nor does it accept and ignore an argument of -- as signifying the end of op‐ + tions. + + Expressions may be combined using the following operators, listed in decreasing order of + precedence. The evaluation depends on the number of arguments; see below. Operator prece‐ + dence is used when there are five or more arguments. + ! expr True if expr is false. + ( expr ) + Returns the value of expr. This may be used to override the normal precedence of op‐ + erators. + expr1 -a expr2 + True if both expr1 and expr2 are true. + expr1 -o expr2 + True if either expr1 or expr2 is true. + + test and [ evaluate conditional expressions using a set of rules based on the number of argu‐ + ments. + + 0 arguments + The expression is false. + 1 argument + The expression is true if and only if the argument is not null. + 2 arguments + If the first argument is !, the expression is true if and only if the second argument + is null. If the first argument is one of the unary conditional operators listed above + under CONDITIONAL EXPRESSIONS, the expression is true if the unary test is true. If + the first argument is not a valid unary conditional operator, the expression is false. + 3 arguments + The following conditions are applied in the order listed. If the second argument is + one of the binary conditional operators listed above under CONDITIONAL EXPRESSIONS, + the result of the expression is the result of the binary test using the first and + third arguments as operands. The -a and -o operators are considered binary operators + when there are three arguments. If the first argument is !, the value is the negation + of the two-argument test using the second and third arguments. If the first argument + is exactly ( and the third argument is exactly ), the result is the one-argument test + of the second argument. Otherwise, the expression is false. + 4 arguments + If the first argument is !, the result is the negation of the three-argument expres‐ + sion composed of the remaining arguments. Otherwise, the expression is parsed and + evaluated according to precedence using the rules listed above. + 5 or more arguments + The expression is parsed and evaluated according to precedence using the rules listed + above. + + When used with test or [, the < and > operators sort lexicographically using ASCII ordering. + + times Print the accumulated user and system times for the shell and for processes run from the + shell. The return status is 0. + + trap [-lp] [[arg] sigspec ...] + The command arg is to be read and executed when the shell receives signal(s) sigspec. If arg + is absent (and there is a single sigspec) or -, each specified signal is reset to its origi‐ + nal disposition (the value it had upon entrance to the shell). If arg is the null string the + signal specified by each sigspec is ignored by the shell and by the commands it invokes. If + arg is not present and -p has been supplied, then the trap commands associated with each + sigspec are displayed. If no arguments are supplied or if only -p is given, trap prints the + list of commands associated with each signal. The -l option causes the shell to print a list + of signal names and their corresponding numbers. Each sigspec is either a signal name de‐ + fined in , or a signal number. Signal names are case insensitive and the SIG pre‐ + fix is optional. + + If a sigspec is EXIT (0) the command arg is executed on exit from the shell. If a sigspec is + DEBUG, the command arg is executed before every simple command, for command, case command, + select command, every arithmetic for command, and before the first command executes in a + shell function (see SHELL GRAMMAR above). Refer to the description of the extdebug option to + the shopt builtin for details of its effect on the DEBUG trap. If a sigspec is RETURN, the + command arg is executed each time a shell function or a script executed with the . or source + builtins finishes executing. + + If a sigspec is ERR, the command arg is executed whenever a pipeline (which may consist of a + single simple command), a list, or a compound command returns a non-zero exit status, subject + to the following conditions. The ERR trap is not executed if the failed command is part of + the command list immediately following a while or until keyword, part of the test in an if + statement, part of a command executed in a && or || list except the command following the fi‐ + nal && or ||, any command in a pipeline but the last, or if the command's return value is be‐ + ing inverted using !. These are the same conditions obeyed by the errexit (-e) option. + + Signals ignored upon entry to the shell cannot be trapped or reset. Trapped signals that are + not being ignored are reset to their original values in a subshell or subshell environment + when one is created. The return status is false if any sigspec is invalid; otherwise trap + returns true. + + type [-aftpP] name [name ...] + With no options, indicate how each name would be interpreted if used as a command name. If + the -t option is used, type prints a string which is one of alias, keyword, function, + builtin, or file if name is an alias, shell reserved word, function, builtin, or disk file, + respectively. If the name is not found, then nothing is printed, and an exit status of false + is returned. If the -p option is used, type either returns the name of the disk file that + would be executed if name were specified as a command name, or nothing if ``type -t name'' + would not return file. The -P option forces a PATH search for each name, even if ``type -t + name'' would not return file. If a command is hashed, -p and -P print the hashed value, + which is not necessarily the file that appears first in PATH. If the -a option is used, type + prints all of the places that contain an executable named name. This includes aliases and + functions, if and only if the -p option is not also used. The table of hashed commands is + not consulted when using -a. The -f option suppresses shell function lookup, as with the + command builtin. type returns true if all of the arguments are found, false if any are not + found. + + ulimit [-HSabcdefiklmnpqrstuvxPT [limit]] + Provides control over the resources available to the shell and to processes started by it, on + systems that allow such control. The -H and -S options specify that the hard or soft limit + is set for the given resource. A hard limit cannot be increased by a non-root user once it + is set; a soft limit may be increased up to the value of the hard limit. If neither -H nor + -S is specified, both the soft and hard limits are set. The value of limit can be a number + in the unit specified for the resource or one of the special values hard, soft, or unlimited, + which stand for the current hard limit, the current soft limit, and no limit, respectively. + If limit is omitted, the current value of the soft limit of the resource is printed, unless + the -H option is given. When more than one resource is specified, the limit name and unit + are printed before the value. Other options are interpreted as follows: + -a All current limits are reported + -b The maximum socket buffer size + -c The maximum size of core files created + -d The maximum size of a process's data segment + -e The maximum scheduling priority ("nice") + -f The maximum size of files written by the shell and its children + -i The maximum number of pending signals + -k The maximum number of kqueues that may be allocated + -l The maximum size that may be locked into memory + -m The maximum resident set size (many systems do not honor this limit) + -n The maximum number of open file descriptors (most systems do not allow this value to + be set) + -p The pipe size in 512-byte blocks (this may not be set) + -q The maximum number of bytes in POSIX message queues + -r The maximum real-time scheduling priority + -s The maximum stack size + -t The maximum amount of cpu time in seconds + -u The maximum number of processes available to a single user + -v The maximum amount of virtual memory available to the shell and, on some systems, to + its children + -x The maximum number of file locks + -P The maximum number of pseudoterminals + -T The maximum number of threads + + If limit is given, and the -a option is not used, limit is the new value of the specified re‐ + source. If no option is given, then -f is assumed. Values are in 1024-byte increments, ex‐ + cept for -t, which is in seconds; -p, which is in units of 512-byte blocks; -P, -T, -b, -k, + -n, and -u, which are unscaled values; and, when in posix mode, -c and -f, which are in + 512-byte increments. The return status is 0 unless an invalid option or argument is sup‐ + plied, or an error occurs while setting a new limit. + + umask [-p] [-S] [mode] + The user file-creation mask is set to mode. If mode begins with a digit, it is interpreted + as an octal number; otherwise it is interpreted as a symbolic mode mask similar to that ac‐ + cepted by chmod(1). If mode is omitted, the current value of the mask is printed. The -S + option causes the mask to be printed in symbolic form; the default output is an octal number. + If the -p option is supplied, and mode is omitted, the output is in a form that may be reused + as input. The return status is 0 if the mode was successfully changed or if no mode argument + was supplied, and false otherwise. + + unalias [-a] [name ...] + Remove each name from the list of defined aliases. If -a is supplied, all alias definitions + are removed. The return value is true unless a supplied name is not a defined alias. + + unset [-fv] [-n] [name ...] + For each name, remove the corresponding variable or function. If the -v option is given, + each name refers to a shell variable, and that variable is removed. Read-only variables may + not be unset. If -f is specified, each name refers to a shell function, and the function + definition is removed. If the -n option is supplied, and name is a variable with the nameref + attribute, name will be unset rather than the variable it references. -n has no effect if + the -f option is supplied. If no options are supplied, each name refers to a variable; if + there is no variable by that name, any function with that name is unset. Each unset variable + or function is removed from the environment passed to subsequent commands. If any of + COMP_WORDBREAKS, RANDOM, SECONDS, LINENO, HISTCMD, FUNCNAME, GROUPS, or DIRSTACK are unset, + they lose their special properties, even if they are subsequently reset. The exit status is + true unless a name is readonly. + + wait [-fn] [id ...] + Wait for each specified child process and return its termination status. Each id may be a + process ID or a job specification; if a job spec is given, all processes in that job's pipe‐ + line are waited for. If id is not given, all currently active child processes are waited + for, and the return status is zero. If the -n option is supplied, wait waits for any job to + terminate and returns its exit status. If the -f option is supplied, and job control is en‐ + abled, wait forces id to terminate before returning its status, instead of returning when it + changes status. If id specifies a non-existent process or job, the return status is 127. + Otherwise, the return status is the exit status of the last process or job waited for. + +RESTRICTED SHELL + If bash is started with the name rbash, or the -r option is supplied at invocation, the shell be‐ + comes restricted. A restricted shell is used to set up an environment more controlled than the + standard shell. It behaves identically to bash with the exception that the following are disallowed + or not performed: + + • changing directories with cd + + • setting or unsetting the values of SHELL, PATH, ENV, or BASH_ENV + + • specifying command names containing / + + • specifying a filename containing a / as an argument to the . builtin command + + • specifying a filename containing a slash as an argument to the -p option to the hash builtin + command + + • importing function definitions from the shell environment at startup + + • parsing the value of SHELLOPTS from the shell environment at startup + + • redirecting output using the >, >|, <>, >&, &>, and >> redirection operators + + • using the exec builtin command to replace the shell with another command + + • adding or deleting builtin commands with the -f and -d options to the enable builtin command + + • using the enable builtin command to enable disabled shell builtins + + • specifying the -p option to the command builtin command + + • turning off restricted mode with set +r or set +o restricted. + + These restrictions are enforced after any startup files are read. + + When a command that is found to be a shell script is executed (see COMMAND EXECUTION above), rbash + turns off any restrictions in the shell spawned to execute the script. + +SEE ALSO + Bash Reference Manual, Brian Fox and Chet Ramey + The Gnu Readline Library, Brian Fox and Chet Ramey + The Gnu History Library, Brian Fox and Chet Ramey + Portable Operating System Interface (POSIX) Part 2: Shell and Utilities, IEEE -- + http://pubs.opengroup.org/onlinepubs/9699919799/ + http://tiswww.case.edu/~chet/bash/POSIX -- a description of posix mode + sh(1), ksh(1), csh(1) + emacs(1), vi(1) + readline(3) + +FILES + /bin/bash + The bash executable + /etc/profile + The systemwide initialization file, executed for login shells + /etc/bash.bashrc + The systemwide per-interactive-shell startup file + /etc/bash.bash.logout + The systemwide login shell cleanup file, executed when a login shell exits + ~/.bash_profile + The personal initialization file, executed for login shells + ~/.bashrc + The individual per-interactive-shell startup file + ~/.bash_logout + The individual login shell cleanup file, executed when a login shell exits + ~/.inputrc + Individual readline initialization file + +AUTHORS + Brian Fox, Free Software Foundation + bfox@gnu.org + + Chet Ramey, Case Western Reserve University + chet.ramey@case.edu + +BUG REPORTS + If you find a bug in bash, you should report it. But first, you should make sure that it really is + a bug, and that it appears in the latest version of bash. The latest version is always available + from ftp://ftp.gnu.org/pub/gnu/bash/. + + Once you have determined that a bug actually exists, use the bashbug command to submit a bug report. + If you have a fix, you are encouraged to mail that as well! Suggestions and `philosophical' bug re‐ + ports may be mailed to bug-bash@gnu.org or posted to the Usenet newsgroup gnu.bash.bug. + + ALL bug reports should include: + + The version number of bash + The hardware and operating system + The compiler used to compile + A description of the bug behaviour + A short script or `recipe' which exercises the bug + + bashbug inserts the first three items automatically into the template it provides for filing a bug + report. + + Comments and bug reports concerning this manual page should be directed to chet.ramey@case.edu. + +BUGS + It's too big and too slow. + + There are some subtle differences between bash and traditional versions of sh, mostly because of the + POSIX specification. + + Aliases are confusing in some uses. + + Shell builtin commands and functions are not stoppable/restartable. + + Compound commands and command sequences of the form `a ; b ; c' are not handled gracefully when + process suspension is attempted. When a process is stopped, the shell immediately executes the next + command in the sequence. It suffices to place the sequence of commands between parentheses to force + it into a subshell, which may be stopped as a unit. + + Array variables may not (yet) be exported. + + There may be only one active coprocess at a time. + +GNU Bash 5.0 2018 December 7 BASH(1) diff --git a/week-04/csh.txt b/week-04/csh.txt new file mode 100644 index 0000000..fccdfdc --- /dev/null +++ b/week-04/csh.txt @@ -0,0 +1,1200 @@ +CSH(1) BSD General Commands Manual CSH(1) + +NAME + csh — a shell (command interpreter) with C-like syntax + +SYNOPSIS + csh [-bcefimnstVvXx] [argument ...] + csh [-l] + +DESCRIPTION + csh is a command language interpreter incorporating a history mechanism (see History substitutions), + job control facilities (see Jobs), interactive file name and user name completion (see File name + completion), and a C-like syntax. It is used both as an interactive login shell and a shell script + command processor. + + Argument list processing + If the first argument (argument 0) to the shell is a dash (‘-’), then this is a login shell. A login + shell also can be specified by invoking the shell with the -l flag as the only argument. + + The rest of the flag arguments are interpreted as follows: + + -b This flag forces a “break” from option processing, causing any further shell arguments to be + treated as non-option arguments. The remaining arguments will not be interpreted as shell op‐ + tions. This may be used to pass options to a shell script without confusion or possible sub‐ + terfuge. The shell will not run a set-user-ID script without this option. + + -c Commands are read from the (single) following argument which must be present. Any remaining + arguments are placed in argv. + + -e The shell exits if any invoked command terminates abnormally or yields a non-zero exit status. + + -f The shell will start faster, because it will neither search for nor execute commands from the + file .cshrc in the invoker's home directory. Note: if the environment variable HOME is not + set, fast startup is the default. + + -i The shell is interactive and prompts for its top-level input, even if it appears not to be a + terminal. Shells are interactive without this option if their inputs and outputs are termi‐ + nals. + + -l The shell is a login shell (only applicable if -l is the only flag specified). + + -m Read .cshrc, regardless of its owner and group. This option is dangerous and should only be + used by su(1). + + -n Commands are parsed, but not executed. This aids in syntactic checking of shell scripts. When + used interactively, the shell can be terminated by pressing control-D (end-of-file character), + since exit will not work. + + -s Command input is taken from the standard input. + + -t A single line of input is read and executed. A backslash (‘\’) may be used to escape the new‐ + line at the end of this line and continue onto another line. + + -V Causes the verbose variable to be set even before .cshrc is executed. + + -v Causes the verbose variable to be set, with the effect that command input is echoed after his‐ + tory substitution. + + -X Causes the echo variable to be set even before .cshrc is executed. + + -x Causes the echo variable to be set, so that commands are echoed immediately before execution. + + After processing of flag arguments, if arguments remain but none of the -c, -i, -s, or -t options were + given, the first argument is taken as the name of a file of commands to be executed. The shell opens + this file, and saves its name for possible resubstitution by ‘$0’. Since many systems use either the + standard version 6 or version 7 shells whose shell scripts are not compatible with this shell, the + shell will execute such a “standard” shell if the first character of a script is not a hash mark + (‘#’); i.e., if the script does not start with a comment. Remaining arguments initialize the variable + argv. + + An instance of csh begins by executing commands from the file /etc/csh.cshrc and, if this is a login + shell, /etc/csh.login. It then executes commands from .cshrc in the home directory of the invoker, + and, if this is a login shell, the file .login in the same location. It is typical for users on CRTs + to put the command stty crt in their .login file, and to also invoke tset(1) there. + + In the normal case, the shell will begin reading commands from the terminal, prompting with ‘% .’ Pro‐ + cessing of arguments and the use of the shell to process files containing command scripts will be de‐ + scribed later. + + The shell repeatedly performs the following actions: a line of command input is read and broken into + “words”. This sequence of words is placed on the command history list and parsed. Finally each com‐ + mand in the current line is executed. + + When a login shell terminates it executes commands from the files .logout in the user's home directory + and /etc/csh.logout. + + Lexical structure + The shell splits input lines into words at blanks and tabs with the following exceptions. The charac‐ + ters ‘&’, ‘|’, ‘;’, ‘<’, ‘>’, ‘(’, and ‘)’ form separate words. If doubled in ‘&&’, ‘||’, ‘<<’, or + ‘>>’, these pairs form single words. These parser metacharacters may be made part of other words, or + have their special meaning prevented, by preceding them with a backslash (‘\’). A newline preceded by + a ‘\’ is equivalent to a blank. + + Strings enclosed in matched pairs of quotations, ‘'’, ‘`’, or ‘"’, form parts of a word; metacharac‐ + ters in these strings, including blanks and tabs, do not form separate words. These quotations have + semantics to be described later. Within pairs of ‘'’ or ‘"’ characters, a newline preceded by a ‘\’ + gives a true newline character. + + When the shell's input is not a terminal, the character ‘#’ introduces a comment that continues to the + end of the input line. This special meaning is prevented when preceded by ‘\’ and in quotations using + ‘`’, ‘'’, and ‘"’. + + Commands + A simple command is a sequence of words, the first of which specifies the command to be executed. A + simple command or a sequence of simple commands separated by ‘|’ characters forms a pipeline. The + output of each command in a pipeline is connected to the input of the next. Sequences of pipelines + may be separated by ‘;’, and are then executed sequentially. A sequence of pipelines may be executed + without immediately waiting for it to terminate by following it with a ‘&’. + + Any of the above may be placed in ‘(’ ‘)’ to form a simple command (that may be a component of a pipe‐ + line, for example). It is also possible to separate pipelines with ‘||’ or ‘&&’ showing, as in the C + language, that the second is to be executed only if the first fails or succeeds, respectively. (See + Expressions.) + + Jobs + The shell associates a job with each pipeline. It keeps a table of current jobs, printed by the jobs + command, and assigns them small integer numbers. When a job is started asynchronously with ‘&’, the + shell prints a line that looks like: + + [1] 1234 + + showing that the job which was started asynchronously was job number 1 and had one (top-level) + process, whose process ID was 1234. + + If you are running a job and wish to do something else you may hit ^Z (control-Z), which sends a + SIGSTOP signal to the current job. The shell will then normally show that the job has been “Stopped”, + and print another prompt. You can then manipulate the state of this job, putting it in the background + with the bg command, or run some other commands and eventually bring the job back into the foreground + with the fg command. A ^Z takes effect immediately and is like an interrupt in that pending output + and unread input are discarded when it is typed. There is another special key ^Y that does not gener‐ + ate a SIGSTOP signal until a program attempts to read(2) it. This request can usefully be typed ahead + when you have prepared some commands for a job that you wish to stop after it has read them. + + A job being run in the background will stop if it tries to read from the terminal. Background jobs + are normally allowed to produce output, but this can be disabled by giving the command stty tostop. + If you set this tty option, then background jobs will stop when they try to produce output like they + do when they try to read input. + + There are several ways to refer to jobs in the shell. The character ‘%’ introduces a job name. If + you wish to refer to job number 1, you can name it as ‘%1’. Just naming a job brings it to the fore‐ + ground; thus %1 is a synonym for fg %1, bringing job number 1 back into the foreground. Similarly, + saying %1 & resumes job number 1 in the background. Jobs can also be named by prefixes of the string + typed in to start them, if these prefixes are unambiguous; thus %ex would normally restart a suspended + ex(1) job, if there were only one suspended job whose name began with the string "ex". It is also + possible to say %?string, which specifies a job whose text contains string, if there is only one such + job. + + The shell maintains a notion of the current and previous jobs. In output about jobs, the current job + is marked with a ‘+’ and the previous job with a ‘-’. The abbreviation ‘%+’ refers to the current job + and ‘%-’ refers to the previous job. For close analogy with the syntax of the history mechanism (de‐ + scribed below), ‘%%’ is also a synonym for the current job. + + The job control mechanism requires that the stty(1) option new be set. It is an artifact from a new + implementation of the tty driver that allows generation of interrupt characters from the keyboard to + tell jobs to stop. See stty(1) for details on setting options in the new tty driver. + + Status reporting + The shell learns immediately whenever a process changes state. It normally informs you whenever a job + becomes blocked so that no further progress is possible, but only just before it prints a prompt. + This is done so that it does not otherwise disturb your work. If, however, you set the shell variable + notify, the shell will notify you immediately of changes of status in background jobs. There is also + a shell command notify that marks a single process so that its status changes will be immediately re‐ + ported. By default notify marks the current process; simply say notify after starting a background + job to mark it. + + When you try to leave the shell while jobs are stopped, you will be warned that “You have stopped + jobs”. You may use the jobs command to see what they are. If you try to exit again immediately, the + shell will not warn you a second time, and the suspended jobs will be terminated. + + File name completion + When the file name completion feature is enabled by setting the shell variable filec (see set), csh + will interactively complete file names and user names from unique prefixes when they are input from + the terminal followed by the escape character (the escape key, or control-[). For example, if the + current directory looks like + + DSC.OLD bin cmd lib xmpl.c + DSC.NEW chaosnet cmtest mail xmpl.o + bench class dev mbox xmpl.out + + and the input is + + % vi ch + + csh will complete the prefix “ch” to the only matching file name “chaosnet”, changing the input line + to + + % vi chaosnet + + However, given + + % vi D + + csh will only expand the input to + + % vi DSC. + + and will sound the terminal bell to indicate that the expansion is incomplete, since there are two + file names matching the prefix ‘D’. + + If a partial file name is followed by the end-of-file character (usually control-D), then, instead of + completing the name, csh will list all file names matching the prefix. For example, the input + + % vi D + + causes all files beginning with ‘D’ to be listed: + + DSC.NEW DSC.OLD + + while the input line remains unchanged. + + The same system of escape and end-of-file can also be used to expand partial user names, if the word + to be completed (or listed) begins with the tilde character (‘~’). For example, typing + + cd ~ro + + may produce the expansion + + cd ~root + + The use of the terminal bell to signal errors or multiple matches can be inhibited by setting the + variable nobeep. + + Normally, all files in the particular directory are candidates for name completion. Files with cer‐ + tain suffixes can be excluded from consideration by setting the variable fignore to the list of suf‐ + fixes to be ignored. Thus, if fignore is set by the command + + % set fignore = (.o .out) + + then typing + + % vi x + + would result in the completion to + + % vi xmpl.c + + ignoring the files "xmpl.o" and "xmpl.out". However, if the only completion possible requires not ig‐ + noring these suffixes, then they are not ignored. In addition, fignore does not affect the listing of + file names by control-D. All files are listed regardless of their suffixes. + + Substitutions + We now describe the various transformations the shell performs on the input in the order in which they + occur. + + History substitutions + History substitutions place words from previous command input as portions of new commands, making it + easy to repeat commands, repeat arguments of a previous command in the current command, or fix spell‐ + ing mistakes in the previous command with little typing and a high degree of confidence. History sub‐ + stitutions begin with the character ‘!’ and may begin anywhere in the input stream (with the proviso + that they do not nest). This ‘!’ may be preceded by a ‘\’ to prevent its special meaning; for conve‐ + nience, a ‘!’ character is passed unchanged when it is followed by a blank, tab, newline, ‘=’ or ‘(’. + (History substitutions also occur when an input line begins with ‘^’. This special abbreviation will + be described later.) Any input line that contains history substitution is echoed on the terminal be‐ + fore it is executed as it would have been typed without history substitution. + + Commands input from the terminal that consist of one or more words are saved on the history list. The + history substitutions reintroduce sequences of words from these saved commands into the input stream. + The size of the history list is controlled by the history variable; the previous command is always re‐ + tained, regardless of the value of the history variable. Commands are numbered sequentially from 1. + + For definiteness, consider the following output from the history command: + + 09 write michael + 10 ex write.c + 11 cat oldwrite.c + 12 diff *write.c + + The commands are shown with their event numbers. It is not usually necessary to use event numbers, + but the current event number can be made part of the prompt by placing a ‘!’ in the prompt string. + + With the current event 13 we can refer to previous events by event number ‘!11’, relatively as in + ‘!-2’ (referring to the same event), by a prefix of a command word as in ‘!d’ for event 12 or ‘!wri’ + for event 9, or by a string contained in a word in the command as in ‘!?mic?’ also referring to event + 9. These forms, without further change, simply reintroduce the words of the specified events, each + separated by a single blank. As a special case, ‘!!’ refers to the previous command; thus ‘!!’ alone + is a redo. + + To select words from an event we can follow the event specification by a ‘:’ and a designator for the + desired words. The words of an input line are numbered from 0, the first (usually command) word being + 0, the second word (first argument) being 1, etc. The basic word designators are: + + 0 first (command) word + n n'th argument + ^ first argument; i.e., ‘1’ + $ last argument + % word matched by (immediately preceding) ?s? search + x-y range of words + -y abbreviates ‘0-y’ + * abbreviates ‘^-$’, or nothing if only 1 word in event + x* abbreviates ‘x-$’ + x- like ‘x*’ but omitting word ‘$’ + + The ‘:’ separating the event specification from the word designator can be omitted if the argument se‐ + lector begins with a ‘^’, ‘$’, ‘*’, ‘-’, or ‘%’. After the optional word designator, a sequence of + modifiers can be placed, each preceded by a ‘:’. The following modifiers are defined: + + h Remove a trailing pathname component, leaving the head. + r Remove a trailing ‘.xxx’ component, leaving the root name. + e Remove all but the extension ‘.xxx’ part. + s/l/r/ Substitute l for r. + t Remove all leading pathname components, leaving the tail. + & Repeat the previous substitution. + g Apply the change once on each word, prefixing the above; e.g., ‘g&’. + a Apply the change as many times as possible on a single word, prefixing the above. It + can be used together with ‘g’ to apply a substitution globally. + p Print the new command line but do not execute it. + q Quote the substituted words, preventing further substitutions. + x Like ‘q’, but break into words at blanks, tabs, and newlines. + + Unless preceded by a ‘g’ the change is applied only to the first modifiable word. With substitutions, + it is an error for no word to be applicable. + + The left-hand side of substitutions are not regular expressions in the sense of the editors, but in‐ + stead strings. Any character may be used as the delimiter in place of ‘/’; a ‘\’ quotes the delimiter + into the l and r strings. The character ‘&’ in the right-hand side is replaced by the text from + the left. A ‘\’ also quotes ‘&’. A NULL l (‘//’) uses the previous string either from an l or from a + contextual scan string s in ‘!?s\?’. The trailing delimiter in the substitution may be omitted if a + newline follows immediately as may the trailing ‘?’ in a contextual scan. + + A history reference may be given without an event specification; e.g., ‘!$’. Here, the reference is + to the previous command unless a previous history reference occurred on the same line in which case + this form repeats the previous reference. Thus “!?foo?^ !$” gives the first and last arguments from + the command matching “?foo?”. + + A special abbreviation of a history reference occurs when the first non-blank character of an input + line is a ‘^’. This is equivalent to “!:s^” providing a convenient shorthand for substitutions on the + text of the previous line. Thus ^lb^lib fixes the spelling of “lib” in the previous command. Fi‐ + nally, a history substitution may be surrounded with ‘{’ and ‘}’ if necessary to insulate it from the + characters that follow. Thus, after ls -ld ~paul we might do !{l}a to do ls -ld ~paula, while !la + would look for a command starting with “la”. + + Quotations with ´ and " + The quotation of strings by ‘'’ and ‘"’ can be used to prevent all or some of the remaining substitu‐ + tions. Strings enclosed in ‘'’ are prevented from any further interpretation. Strings enclosed in + ‘"’ may be expanded as described below. + + In both cases the resulting text becomes (all or part of) a single word; only in one special case (see + Command Substitution below) does a ‘"’ quoted string yield parts of more than one word; ‘'’ quoted + strings never do. + + Alias substitution + The shell maintains a list of aliases that can be established, displayed and modified by the alias and + unalias commands. After a command line is scanned, it is parsed into distinct commands and the first + word of each command, left-to-right, is checked to see if it has an alias. If it does, then the text + that is the alias for that command is reread with the history mechanism available as though that com‐ + mand were the previous input line. The resulting words replace the command and argument list. If no + reference is made to the history list, then the argument list is left unchanged. + + Thus if the alias for “ls” is “ls -l”, the command ls /usr would map to ls -l /usr, the argument list + here being undisturbed. Similarly, if the alias for “lookup” was “grep !^ /etc/passwd” then lookup + bill would map to grep bill /etc/passwd. + + If an alias is found, the word transformation of the input text is performed and the aliasing process + begins again on the reformed input line. Looping is prevented if the first word of the new text is + the same as the old by flagging it to prevent further aliasing. Other loops are detected and cause an + error. + + Note that the mechanism allows aliases to introduce parser metasyntax. Thus, we can alias print 'pr + \!* | lpr' to make a command that pr's its arguments to the line printer. + + Variable substitution + The shell maintains a set of variables, each of which has as value a list of zero or more words. Some + of these variables are set by the shell or referred to by it. For instance, the argv variable is an + image of the shell's argument list, and words of this variable's value are referred to in special + ways. + + The values of variables may be displayed and changed by using the set and unset commands. Of the + variables referred to by the shell a number are toggles; the shell does not care what their value is, + only whether they are set or not. For instance, the verbose variable is a toggle that causes command + input to be echoed. The setting of this variable results from the -v command-line option. + + Other operations treat variables numerically. The @ command permits numeric calculations to be per‐ + formed and the result assigned to a variable. Variable values are, however, always represented as + (zero or more) strings. For the purposes of numeric operations, the null string is considered to be + zero, and the second and additional words of multiword values are ignored. + + After the input line is aliased and parsed, and before each command is executed, variable substitution + is performed, keyed by ‘$’ characters. This expansion can be prevented by preceding the ‘$’ with a + ‘\’ except within double quotes (`"'), where it always occurs, and within single quotes (`''), where + it never occurs. Strings quoted by backticks (` `) are interpreted later (see Command substitution + below), so ‘$’ substitution does not occur there until later, if at all. A ‘$’ is passed unchanged if + followed by a blank, tab, or end-of-line. + + Input/output redirections are recognized before variable expansion, and are variable expanded sepa‐ + rately. Otherwise, the command name and entire argument list are expanded together. It is thus pos‐ + sible for the first (command) word (to this point) to generate more than one word, the first of which + becomes the command name, and the rest of which become arguments. + + Unless enclosed in ‘"’ or given the ‘:q’ modifier, the results of variable substitution may eventually + be command and filename substituted. Within ‘"’, a variable whose value consists of multiple words + expands to (a portion of) a single word, with the words of the variable's value separated by blanks. + When the ‘:q’ modifier is applied to a substitution the variable will expand to multiple words with + each word separated by a blank and quoted to prevent later command or filename substitution. + + The following metasequences are provided for introducing variable values into the shell input. Except + as noted, it is an error to reference a variable that is not set. + + $name + ${name} + Are replaced by the words of the value of variable name, each separated by a blank. + Braces insulate name from following characters that would otherwise be part of it. + Shell variables have names consisting of up to 20 letters and digits starting with a + letter. The underscore character is considered a letter. If name is not a shell vari‐ + able, but is set in the environment, then that value is returned (but ‘:’ modifiers and + the other forms given below are not available here). + $name[selector] + ${name[selector]} + May be used to select only some of the words from the value of name. The selector is + subjected to ‘$’ substitution and may consist of a single number or two numbers sepa‐ + rated by a ‘-’. The first word of a variable's value is numbered ‘1’. If the first + number of a range is omitted it defaults to ‘1’. If the last number of a range is omit‐ + ted it defaults to ‘$#name’. The selector ‘*’ selects all words. It is not an error + for a range to be empty if the second argument is omitted or in range. + $#name + ${#name} + Gives the number of words in the variable. This is useful for later use in a + “$argv[selector]”. + $0 Substitutes the name of the file from which command input is being read. An error oc‐ + curs if the name is not known. + $number + ${number} + Equivalent to “$argv[number]”. + $* Equivalent to “$argv[*]”. + + The modifiers ‘:e’, ‘:h’, ‘:t’, ‘:r’, ‘:q’, and ‘:x’ may be applied to the substitutions above as may + ‘:gh’, ‘:gt’, and ‘:gr’. If braces ‘{’ ‘}’ appear in the command form then the modifiers must appear + within the braces. The current implementation allows only one ‘:’ modifier on each ‘$’ expansion. + + The following substitutions may not be modified with ‘:’ modifiers. + $?name + ${?name} + Substitutes the string “1” if name is set, “0” if it is not. + $?0 Substitutes ‘1’ if the current input filename is known, ‘0’ if it is not. + $$ Substitute the (decimal) process number of the (parent) shell. Do NOT use this mecha‐ + nism for generating temporary file names; see mktemp(1) instead. + $! Substitute the (decimal) process number of the last background process started by this + shell. + $< Substitutes a line from the standard input, with no further interpretation. It can be + used to read from the keyboard in a shell script. + + Command and filename substitution + The remaining substitutions, command and filename substitution, are applied selectively to the argu‐ + ments of built-in commands. By selectively, we mean that portions of expressions which are not evalu‐ + ated are not subjected to these expansions. For commands that are not internal to the shell, the com‐ + mand name is substituted separately from the argument list. This occurs very late, after input-output + redirection is performed, and in a child of the main shell. + + Command substitution + Command substitution is shown by a command enclosed in ‘`’. The output from such a command is nor‐ + mally broken into separate words at blanks, tabs, and newlines, with null words being discarded; this + text then replaces the original string. Within double quotes (`"'), only newlines force new words; + blanks and tabs are preserved. + + In any case, the single final newline does not force a new word. Note that it is thus possible for a + command substitution to yield only part of a word, even if the command outputs a complete line. + + Filename substitution + If a word contains any of the characters ‘*’, ‘?’, ‘[’, or ‘{’, or begins with the character ‘~’, then + that word is a candidate for filename substitution, also known as “globbing”. This word is then re‐ + garded as a pattern, and replaced with an alphabetically sorted list of file names that match the pat‐ + tern. In a list of words specifying filename substitution it is an error for no pattern to match an + existing file name, but it is not required for each pattern to match. Only the metacharacters ‘*’, + ‘?’, and ‘[’ imply pattern matching, the characters ‘~’ and ‘{’ being more akin to abbreviations. + + In matching filenames, the character ‘.’ at the beginning of a filename or immediately following a + ‘/’, as well as the character ‘/’ must be matched explicitly. The character ‘*’ matches any string of + characters, including the null string. The character ‘?’ matches any single character. + + The sequence “[...]” matches any one of the characters enclosed. Within “[...]”, a pair of characters + separated by ‘-’ matches any character lexically between the two (inclusive). Within “[...]”, the + name of a character class enclosed in ‘[:’ and ‘:]’ stands for the list of all characters belonging to + that class. Supported character classes: + + alnum cntrl lower space + alpha digit print upper + blank graph punct xdigit + + These match characters using the macros specified in ctype(3). A character class may not be used as + an endpoint of a range. + + The character ‘~’ at the beginning of a filename refers to home directories. Standing alone, i.e., + ‘~’, it expands to the invoker's home directory as reflected in the value of the variable home. When + followed by a name consisting of letters, digits, and ‘-’ characters, the shell searches for a user + with that name and substitutes their home directory; thus “~ken” might expand to “/usr/ken” and + “~ken/chmach” to “/usr/ken/chmach”. If the character ‘~’ is followed by a character other than a let‐ + ter or ‘/’, or does not appear at the beginning of a word, it is left undisturbed. + + The metanotation “a{b,c,d}e” is a shorthand for “abe ace ade”. Left to right order is preserved, with + results of matches being sorted separately at a low level to preserve this order. This construct may + be nested. Thus, “~source/s1/{oldls,ls}.c” expands to “/usr/source/s1/oldls.c /usr/source/s1/ls.c” + without chance of error if the home directory for “source” is “/usr/source”. Similarly + “../{memo,*box}” might expand to “../memo ../box ../mbox”. (Note that “memo” was not sorted with the + results of the match to “*box”.) As a special case ‘{’, ‘}’, and ‘{}’ are passed undisturbed. + + Input/output + The standard input and the standard output of a command may be redirected with the following syntax: + + < name Open file name (which is first variable, command, and filename expanded) as the standard + input. + << word + Read the shell input up to a line that is identical to word. word is not subjected to + variable, command, or filename substitution, and each input line is compared to word be‐ + fore any substitutions are done on the input line. Unless a quoting ‘\’, ‘"’, ‘'’ or + ‘`’ appears in word, variable and command substitution is performed on the intervening + lines, allowing ‘\’ to quote ‘$’, ‘\’ and ‘`’. Commands that are substituted have all + blanks, tabs, and newlines preserved, except for the final newline which is dropped. + The resultant text is placed in an anonymous temporary file that is given to the command + as its standard input. + > name + >! name + >& name + >&! name + The file name is used as the standard output. If the file does not exist then it is + created; if the file exists, it is truncated; its previous contents are lost. + + If the variable noclobber is set, then the file must not exist or be a character special + file (e.g., a terminal or /dev/null) or an error results. This helps prevent accidental + destruction of files. Here, the ‘!’ forms can be used to suppress this check. + + The forms involving ‘&’ route the standard error output into the specified file as well + as the standard output. name is expanded in the same way as ‘<’ input filenames are. + >> name + >>& name + >>! name + >>&! name + Uses file name as the standard output; like ‘>’ but places output at the end of the + file. If the variable noclobber is set, then it is an error for the file not to exist + unless one of the ‘!’ forms is given. Otherwise similar to ‘>’. + + A command receives the environment in which the shell was invoked as modified by the input-output pa‐ + rameters and the presence of the command in a pipeline. Thus, unlike some previous shells, commands + run from a file of shell commands have no access to the text of the commands by default; instead they + receive the original standard input of the shell. The ‘<<’ mechanism should be used to present inline + data. This permits shell command scripts to function as components of pipelines and allows the shell + to block read its input. Note that the default standard input for a command run detached is not modi‐ + fied to be the empty file /dev/null; instead the standard input remains as the original standard input + of the shell. If this is a terminal and if the process attempts to read from the terminal, then the + process will block and the user will be notified (see Jobs above). + + The standard error output may be directed through a pipe with the standard output. Simply use the + form ‘|&’ instead of just ‘|’. + + Expressions + Several of the built-in commands (to be described later) take expressions, in which the operators are + similar to those of C, with the same precedence, but with the opposite grouping: right to left. These + expressions appear in the @, exit, if, and while commands. The following operators are available: + + || && | ↑ & == != =~ !~ <= >= < > << >> + - * / % ! ~ ( ) + + Here the precedence increases to the right, ‘==’ ‘!=’ ‘=~’ and ‘!~’, ‘<=’ ‘>=’ ‘<’ and ‘>’, ‘<<’ and + ‘>>’, ‘+’ and ‘-’, ‘*’ ‘/’ and ‘%’ being, in groups, at the same level. The ‘==’ ‘!=’ ‘=~’ and ‘!~’ + operators compare their arguments as strings; all others operate on numbers. The operators ‘=~’ and + ‘!~’ are like ‘!=’ and ‘==’ except that the right hand side is a pattern (containing, e.g., *'s, ?'s, + and instances of “[...]”) against which the left-hand operand is matched. This reduces the need for + use of the switch statement in shell scripts when all that is really needed is pattern matching. + + Strings that begin with ‘0’ are considered octal numbers. Null or missing arguments are considered + ‘0’. The results of all expressions are strings, which represent decimal numbers. It is important to + note that no two components of an expression can appear in the same word; except when adjacent to com‐ + ponents of expressions that are syntactically significant to the parser (‘&’, ‘|’, ‘<’, ‘>’, ‘(’, and + ‘)’), they should be surrounded by spaces. + + Also available in expressions as primitive operands are command executions enclosed in ‘{’ and ‘}’ and + file enquiries of the form -l name where l is one of: + + r read access + w write access + x execute access + e existence + o ownership + z zero size + f plain file + d directory + + The specified name is command and filename expanded and then tested to see if it has the specified re‐ + lationship to the real user. If the file does not exist or is inaccessible then all enquiries return + false, i.e., ‘0’. Command executions succeed, returning true, i.e., ‘1’, if the command exits with + status 0, otherwise they fail, returning false, i.e., ‘0’. If more detailed status information is re‐ + quired then the command should be executed outside an expression and the variable status examined. + + Control flow + The shell contains several commands that can be used to regulate the flow of control in command files + (shell scripts) and (in limited but useful ways) from terminal input. These commands all operate by + forcing the shell to reread or skip in its input and, because of the implementation, restrict the + placement of some of the commands. + + The foreach, switch, and while statements, as well as the if-then-else form of the if statement re‐ + quire that the major keywords appear in a single simple command on an input line as shown below. + + If the shell's input is not seekable, the shell buffers up input whenever a loop is being read and + performs seeks in this internal buffer to accomplish the rereading implied by the loop. (To the ex‐ + tent that this allows, backward goto's will succeed on non-seekable inputs.) + + Built-in commands + Built-in commands are executed within the shell. If a built-in command occurs as any component of a + pipeline except the last then it is executed in a sub-shell. + + alias + alias name + alias name wordlist + The first form prints all aliases. The second form prints the alias for name. The fi‐ + nal form assigns the specified wordlist as the alias of name; wordlist is command and + filename substituted. name is not allowed to be “alias” or “unalias”. + + alloc Shows the amount of dynamic memory acquired, broken down into used and free memory. + With an argument shows the number of free and used blocks in each size category. The + categories start at size 8 and double at each step. This command's output may vary + across system types, since systems other than the VAX may use a different memory alloca‐ + tor. + + bg + bg %job ... + Puts the current or specified jobs into the background, continuing them if they were + stopped. + + break Causes execution to resume after the end of the nearest enclosing foreach or while. The + remaining commands on the current line are executed. Multi-level breaks are thus possi‐ + ble by writing them all on one line. + + breaksw + Causes a break from a switch, resuming after the endsw. + + case label: + A label in a switch statement as discussed below. + + cd + cd name + chdir + chdir name + Change the shell's working directory to directory name. If no argument is given then + change to the home directory of the user. If name is not found as a subdirectory of the + current directory (and does not begin with ‘/’, ‘./’ or ‘../’), then each component of + the variable cdpath is checked to see if it has a subdirectory name. Finally, if all + else fails but name is a shell variable whose value begins with ‘/’, then this is tried + to see if it is a directory. + + continue + Continue execution of the nearest enclosing while or foreach. The rest of the commands + on the current line are executed. + + default: + Labels the default case in a switch statement. The default should come after all case + labels. + + dirs Prints the directory stack; the top of the stack is at the left, the first directory in + the stack being the current directory. + + echo wordlist + echo -n wordlist + The specified words are written to the shell's standard output, separated by spaces, and + terminated with a newline unless the -n option is specified. + + else + end + endif + endsw See the description of the foreach, if, switch, and while statements below. + + eval arg ... + (As in sh(1).) The arguments are read as input to the shell and the resulting com‐ + mand(s) executed in the context of the current shell. This is usually used to execute + commands generated as the result of command or variable substitution, since parsing oc‐ + curs before these substitutions. See tset(1) for an example of using eval. + + exec command + The specified command is executed in place of the current shell. + + exit + exit (expr) + The shell exits either with the value of the status variable (first form) or with the + value of the specified expr (second form). + + fg + fg %job ... + Brings the current or specified jobs into the foreground, continuing them if they were + stopped. + + foreach name (wordlist) + ... + end The variable name is successively set to each member of wordlist and the sequence of + commands between this command and the matching end are executed. (Both foreach and end + must appear alone on separate lines.) The built-in command continue may be used to con‐ + tinue the loop prematurely and the built-in command break to terminate it prematurely. + When this command is read from the terminal, the loop is read once prompting with ‘?’ + before any statements in the loop are executed. If you make a mistake typing in a loop + at the terminal you can rub it out. + + glob wordlist + Like echo but no ‘\’ escapes are recognized and words are delimited by NUL characters in + the output. Useful for programs that wish to use the shell to filename expand a list of + words. + + goto word + The specified word is filename and command expanded to yield a string of the form + ‘label’. The shell rewinds its input as much as possible and searches for a line of the + form “label:”, possibly preceded by blanks or tabs. Execution continues after the spec‐ + ified line. + + hashstat + Print a statistics line showing how effective the internal hash table has been at locat‐ + ing commands (and avoiding exec´s). An exec is attempted for each component of the path + where the hash function indicates a possible hit, and in each component that does not + begin with a ‘/’. + + history + history n + history -h n + history -r n + Displays the history event list; if n is given, only the n most recent events are + printed. The -h option causes the history list to be printed without leading numbers. + This format produces files suitable for sourcing using the -h option to source. The -r + option reverses the order of printout to be most recent first instead of oldest first. + + if (expr) command + If the specified expression evaluates to true, then the single command with arguments is + executed. Variable substitution on command happens early, at the same time it does for + the rest of the if command. command must be a simple command, not a pipeline, a command + list, or a parenthesized command list. Input/output redirection occurs even if expr is + false, i.e., when command is not executed (this is a bug). + + if (expr) then + ... + else if (expr2) then + ... + else + ... + endif If the specified expr is true then the commands up to the first else are executed; oth‐ + erwise if expr2 is true then the commands up to the second else are executed, etc. Any + number of else-if pairs are possible; only one endif is needed. The else part is like‐ + wise optional. (The words else and endif must appear at the beginning of input lines; + the if must appear alone on its input line or after an else.) + + jobs + jobs -l + Lists the active jobs; the -l option lists process IDs in addition to the normal infor‐ + mation. + + kill %job + kill [-s signal_name] pid + kill -sig pid ... + kill -l [exit_status] + Sends either the SIGTERM (terminate) signal or the specified signal to the specified + jobs or processes. Signals are either given by number or by names (as given in + ⟨signal.h⟩, stripped of the prefix “SIG”). The signal names are listed by “kill -l”; if + an exit_status is specified, only the corresponding signal name will be written. There + is no default; just saying “kill” does not send a signal to the current job. If the + signal being sent is SIGTERM (terminate) or SIGHUP (hangup), then the job or process + will be sent a SIGCONT (continue) signal as well. + + limit + limit resource + limit resource maximum-use + limit -h + limit -h resource + limit -h resource maximum-use + Limits the consumption by the current process and each process it creates to not indi‐ + vidually exceed maximum-use on the specified resource. If no maximum-use is given, then + the current limit is printed; if no resource is given, then all limitations are given. + If the -h flag is given, the hard limits are used instead of the current limits. The + hard limits impose a ceiling on the values of the current limits. Only the superuser + may raise the hard limits, but a user may lower or raise the current limits within the + legal range. + + Resources controllable currently include: + + cputime the maximum number of CPU-seconds to be used by each process. + + filesize the largest single file (in bytes) that can be created. + + datasize the maximum growth of the data+stack region via sbrk(2) beyond the end of + the program text. + + stacksize the maximum size of the automatically-extended stack region. + + coredumpsize the size of the largest core dump (in bytes) that will be created. + + memoryuse the maximum size (in bytes) to which a process's resident set size (RSS) + may grow. + + memorylocked The maximum size (in bytes) which a process may lock into memory using the + mlock(2) function. + + maxproc The maximum number of simultaneous processes for this user ID. + + openfiles The maximum number of simultaneous open files for this user ID. + + vmemoryuse the maximum size (in bytes) to which a process's total size may grow. + + The maximum-use may be given as a (floating point or integer) number followed by a scale + factor. For all limits other than cputime the default scale is ‘k’ or “kilobytes” (1024 + bytes); a scale factor of ‘m’ or “megabytes” may also be used. For cputime the default + scale is “seconds”; a scale factor of ‘m’ for minutes or ‘h’ for hours, or a time of the + form “mm:ss” giving minutes and seconds also may be used. + + For both resource names and scale factors, unambiguous prefixes of the names suffice. + + login Terminate a login shell, replacing it with an instance of /usr/bin/login. This is one + way to log off, included for compatibility with sh(1). + + logout Terminate a login shell. Especially useful if ignoreeof is set. + + nice + nice +number + nice command + nice +number command + The first form sets the scheduling priority for this shell to 4. The second form sets + the priority to the given number. The final two forms run command at priority 4 and + number respectively. The greater the number, the less CPU the process will get. The + superuser may specify negative priority by using “nice -number ...”. command is always + executed in a sub-shell, and the restrictions placed on commands in simple if statements + apply. + + nohup + nohup command + The first form can be used in shell scripts to cause hangups to be ignored for the re‐ + mainder of the script. The second form causes the specified command to be run with + hangups ignored. All processes detached with ‘&’ are effectively nohup´ed. + + notify + notify %job ... + Causes the shell to notify the user asynchronously when the status of the current or + specified jobs change; normally notification is presented before a prompt. This is au‐ + tomatic if the shell variable notify is set. + + onintr + onintr - + onintr label + Control the action of the shell on interrupts. The first form restores the default ac‐ + tion of the shell on interrupts, which is to terminate shell scripts or to return to the + terminal command input level. The second form onintr - causes all interrupts to be ig‐ + nored. The final form causes the shell to execute a goto label when an interrupt is re‐ + ceived or a child process terminates because it was interrupted. + + In any case, if the shell is running detached and interrupts are being ignored, all + forms of onintr have no meaning and interrupts continue to be ignored by the shell and + all invoked commands. Finally, onintr statements are ignored in the system startup + files where interrupts are disabled (/etc/csh.cshrc, /etc/csh.login). + + popd + popd +n + Pops the directory stack, returning to the new top directory. With an argument “+n” + discards the n´th entry in the stack. The members of the directory stack are numbered + from the top starting at 0. + + pushd + pushd name + pushd +n + With no arguments, pushd exchanges the top two elements of the directory stack. Given a + name argument, pushd changes to the new directory (ala cd) and pushes the old current + working directory (as in cwd) onto the directory stack. With a numeric argument, pushd + rotates the n´th argument of the directory stack around to be the top element and + changes to it. The members of the directory stack are numbered from the top starting at + 0. + + rehash Causes the internal hash table of the contents of the directories in the path variable + to be recomputed. This is needed if new commands are added to directories in the path + while you are logged in. This should only be necessary if you add commands to one of + your own directories, or if a systems programmer changes the contents of a system direc‐ + tory. + + repeat count command + The specified command, which is subject to the same restrictions as the command in the + one line if statement above, is executed count times. I/O redirections occur exactly + once, even if count is 0. + + set + set name + set name=word + set name[index]=word + set name=(wordlist) + The first form of the command shows the value of all shell variables. Variables that + have other than a single word as their value print as a parenthesized word list. The + second form sets name to the null string. The third form sets name to the single word. + The fourth form sets the index'th component of name to word; this component must already + exist. The final form sets name to the list of words in wordlist. The value is always + command and filename expanded. + + These arguments may be repeated to set multiple values in a single set command. Note + however, that variable expansion happens for all arguments before any setting occurs. + + setenv + setenv name + setenv name value + The first form lists all current environment variables. It is equivalent to + printenv(1). The last form sets the value of environment variable name to be value, a + single string. The second form sets name to an empty string. The most commonly used + environment variables USER, TERM, and PATH are automatically imported to and exported + from the csh variables user, term, and path; there is no need to use setenv for these. + + shift + shift variable + The members of argv are shifted to the left, discarding argv[1]. It is an error for + argv not to be set or to have less than one word as value. The second form performs the + same function on the specified variable. + + source name + source -h name + The shell reads commands from name. source commands may be nested; if they are nested + too deeply the shell may run out of file descriptors. An error in a source at any level + terminates all nested source commands. Normally input during source commands is not + placed on the history list; the -h option causes the commands to be placed on the his‐ + tory list without being executed. + + stop + stop %job ... + Stops the current or specified jobs that are executing in the background. + + suspend + Causes the shell to stop in its tracks, much as if it had been sent a stop signal with + ^Z. This is most often used to stop shells started by su(1). + + switch (string) + case str1: + ... + breaksw + ... + default: + ... + breaksw + endsw Each case label is successively matched against the specified string, which is first + command and filename expanded. The file metacharacters ‘*’, ‘?’ and “[...]” may be used + in the case labels, which are variable expanded. If none of the labels match before the + “default” label is found, then the execution begins after the default label. Each case + label and the default label must appear at the beginning of a line. The command breaksw + causes execution to continue after the endsw. Otherwise control may fall through case + labels and the default label as in C. If no label matches and there is no default, exe‐ + cution continues after the endsw. + + time + time command + With no argument, a summary of time used by this shell and its children is printed. If + arguments are given the specified simple command is timed and a time summary as de‐ + scribed under the time variable is printed. If necessary, an extra shell is created to + print the time statistic when the command completes. + + umask + umask value + The file creation mask is displayed (first form) or set to the specified value (second + form). The mask is given in octal. Common values for the mask are 002 giving all ac‐ + cess to the group and read and execute access to others or 022 giving all access except + write access for users in the group or others. + + unalias pattern + All aliases whose names match the specified pattern are discarded. Thus all aliases are + removed by unalias *. It is not an error for nothing to be unaliased. + + unhash Use of the internal hash table to speed location of executed programs is disabled. + + unlimit + unlimit resource + unlimit -h + unlimit -h resource + Removes the limitation on resource. If no resource is specified, then all resource lim‐ + itations are removed. If -h is given, the corresponding hard limits are removed. Only + the superuser may do this. + + unset pattern + All variables whose names match the specified pattern are removed. Thus all variables + are removed by unset *; this has noticeably distasteful side-effects. It is not an er‐ + ror for nothing to be unset. + + unsetenv pattern + Removes all variables whose names match the specified pattern from the environment. See + also the setenv command above and printenv(1). + + wait Wait for all background jobs. If the shell is interactive, then an interrupt can dis‐ + rupt the wait. After the interrupt, the shell prints names and job numbers of all jobs + known to be outstanding. + + which command + Displays the resolved command that will be executed by the shell. + + while (expr) + ... + end While the specified expression evaluates to non-zero, the commands between the while and + the matching end are evaluated. break and continue may be used to terminate or continue + the loop prematurely. (The while and end must appear alone on their input lines.) + Prompting occurs here the first time through the loop as for the foreach statement if + the input is a terminal. + + %job Brings the specified job into the foreground. + + %job & Continues the specified job in the background. + + @ + @ name= expr + @ name[index]= expr + The first form prints the values of all the shell variables. The second form sets the + specified name to the value of expr. If the expression contains ‘<’, ‘>’, ‘&’ or ‘|’ + then at least this part of the expression must be placed within ‘(’ ‘)’. The third form + assigns the value of expr to the index'th argument of name. Both name and its index'th + component must already exist. + + The operators ‘*=’, ‘+=’, etc. are available as in C. The space separating the name + from the assignment operator is optional. Spaces are, however, mandatory in separating + components of expr, which would otherwise be single words. + + Special postfix ‘++’ and ‘--’ operators increment and decrement name respectively; i.e., + “@ i++”. + + Pre-defined and environment variables + The following variables have special meaning to the shell. Of these, argv, cwd, home, path, prompt, + shell and status are always set by the shell. Except for cwd and status, this setting occurs only at + initialization; these variables will not then be modified unless done explicitly by the user. + + The shell copies the environment variable USER into the variable user, TERM into term, and HOME into + home, and copies these back into the environment whenever the normal shell variables are reset. The + environment variable PATH is likewise handled; it is not necessary to worry about its setting other + than in the file .cshrc as inferior csh processes will import the definition of path from the environ‐ + ment, and re-export it if you then change it. + + argv Set to the arguments to the shell, it is from this variable that positional parameters are + substituted; i.e., “$1” is replaced by “$argv[1]”, etc. + + cdpath Gives a list of alternate directories searched to find subdirectories in chdir commands. + + cwd The full pathname of the current directory. + + echo Set when the -x command-line option is given. Causes each command and its arguments to be + echoed just before it is executed. For non-built-in commands all expansions occur before + echoing. Built-in commands are echoed before command and filename substitution, since + these substitutions are then done selectively. + + filec Enable file name completion. + + histchars Can be given a string value to change the characters used in history substitution. The + first character of its value is used as the history substitution character, replacing the + default character ‘!’. The second character of its value replaces the character ‘^’ in + quick substitutions. + + histfile Can be set to the pathname where history is going to be saved/restored. + + history Can be given a numeric value to control the size of the history list. Any command that has + been referenced in this many events will not be discarded. Too large values of history may + run the shell out of memory. The last executed command is always saved on the history + list. + + home The home directory of the invoker, initialized from the environment. The filename expan‐ + sion of “~” refers to this variable. + + ignoreeof If set the shell ignores end-of-file from input devices which are terminals. This prevents + shells from accidentally being killed by control-Ds. + + mail The files where the shell checks for mail. This checking is done after each command com‐ + pletion that will result in a prompt, if a specified interval has elapsed. The shell says + “You have new mail.” if the file exists with an access time not greater than its modify + time. + + If the first word of the value of mail is numeric it specifies a different mail checking + interval, in seconds, than the default, which is 10 minutes. + + If multiple mail files are specified, then the shell says “New mail in name” when there is + mail in the file name. + + noclobber As described in the section on Input/output, restrictions are placed on output redirection + to ensure that files are not accidentally destroyed, and that ‘>>’ redirections refer to + existing files. + + noglob If set, filename expansion is inhibited. This inhibition is most useful in shell scripts + that are not dealing with filenames, or after a list of filenames has been obtained and + further expansions are not desirable. + + nonomatch If set, it is not an error for a filename expansion to not match any existing files; in‐ + stead the primitive pattern is returned. It is still an error for the primitive pattern to + be malformed; i.e., “echo [” still gives an error. + + notify If set, the shell notifies asynchronously of job completions; the default is to present job + completions just before printing a prompt. + + path Each word of the path variable specifies a directory in which commands are to be sought for + execution. A null word specifies the current directory. If there is no path variable then + only full path names will execute. The usual search path is “.”, “/bin”, “/usr/bin”, + “/sbin” and “/usr/sbin”, but this may vary from system to system. For the superuser the + default search path is “/bin”, “/usr/bin”, “/sbin”, and “/usr/sbin”. A shell that is given + neither the -c nor the -t option will normally hash the contents of the directories in the + path variable after reading .cshrc, and each time the path variable is reset. If new com‐ + mands are added to these directories while the shell is active, it may be necessary to do a + rehash or the commands may not be found. + + prompt The string that is printed before each command is read from an interactive terminal input. + If a ‘!’ appears in the string it will be replaced by the current event number unless a + preceding ‘\’ is given. Default is “%”, or “#” for the superuser. + + savehist Is given a numeric value to control the number of entries of the history list that are + saved in ~/.history when the user logs out. Any command that has been referenced in this + many events will be saved. During start up the shell sources ~/.history into the history + list enabling history to be saved across logins. Too large values of savehist will slow + down the shell during start up. If savehist is just set, the shell will use the value of + history. + + shell The file in which the shell resides. This variable is used in forking shells to interpret + files that have execute bits set, but which are not executable by the system. (See the de‐ + scription of Non-built-in command execution below.) Initialized to the (system-dependent) + home of the shell. + + status The status returned by the last command. If it terminated abnormally, then 0200 is added + to the status. Built-in commands that fail return exit status 1, all other built-in com‐ + mands set status to 0. + + time Controls automatic timing of commands. If set, then any command that takes more than this + many CPU seconds will cause a line giving user, system, and real times, and a utilization + percentage which is the ratio of user plus system times to real time to be printed when it + terminates. + + verbose Set by the -v command-line option, causes the words of each command to be printed after + history substitution. + + Non-built-in command execution + When a command to be executed is found to not be a built-in command the shell attempts to execute the + command via execve(2). Each word in the variable path names a directory from which the shell will at‐ + tempt to execute the command. If it is given neither a -c nor a -t option, the shell will hash the + names in these directories into an internal table so that it will only try an exec in a directory if + there is a possibility that the command resides there. This shortcut greatly speeds command location + when many directories are present in the search path. If this mechanism has been turned off (via + unhash), or if the shell was given a -c or -t argument, and in any case for each directory component + of path that does not begin with a ‘/’, the shell concatenates with the given command name to form a + path name of a file which it then attempts to execute. + + Parenthesized commands are always executed in a sub-shell. Thus + + (cd; pwd); pwd + + prints the home directory; leaving you where you were (printing this after the home directory), while + + cd; pwd + + leaves you in the home directory. Parenthesized commands are most often used to prevent chdir from + affecting the current shell. + + If the file has execute permissions but is not an executable binary to the system, then it is assumed + to be a file containing shell commands and a new shell is spawned to read it. + + If there is an alias for shell then the words of the alias will be prepended to the argument list to + form the shell command. The first word of the alias should be the full path name of the shell (e.g., + “$shell”). Note that this is a special, late occurring, case of alias substitution, and only allows + words to be prepended to the argument list without change. + + Signal handling + The shell normally ignores SIGQUIT signals. Jobs running detached (either by & or the bg or %... & + commands) are immune to signals generated from the keyboard, including hangups. Other signals have + the values which the shell inherited from its parent. The shell's handling of interrupts and termi‐ + nate signals in shell scripts can be controlled by onintr. Login shells catch the SIGTERM (terminate) + signal; otherwise this signal is passed on to children from the state in the shell's parent. Inter‐ + rupts are not allowed when a login shell is reading the file .logout. + +LIMITATIONS + Word lengths - Words can be no longer than 1024 characters. The number of arguments to a command that + involves filename expansion is limited to 1/6th the number of characters allowed in an argument list. + Command substitutions may substitute no more characters than are allowed in an argument list. To de‐ + tect looping, the shell restricts the number of alias substitutions on a single line to 20. + +FILES + ~/.cshrc read at beginning of execution by each shell + ~/.login read by login shell, after .cshrc at login + ~/.logout read by login shell, at logout + /bin/sh standard shell, for shell scripts not starting with a ‘#’ + /tmp/sh.* temporary file for ‘<<’ + /etc/passwd source of home directories for “~name” + +SEE ALSO + sh(1), access(2), execve(2), fork(2), pipe(2), setrlimit(2), umask(2), wait(2), killpg(3), sigvec(3), + tty(4), a.out(5), environ(7), script(7) + +HISTORY + csh appeared in 3BSD. It was a first implementation of a command language interpreter incorporating a + history mechanism (see History substitutions), job control facilities (see Jobs), interactive file + name and user name completion (see File name completion), and a C-like syntax. There are now many + shells that also have these mechanisms, plus a few more (and maybe some bugs too), which are available + through the usenet. + +AUTHORS + William Joy. Job control and directory stack features first implemented by J.E. Kulp of IIASA, Laxen‐ + burg, Austria, with different syntax than that used now. File name completion code written by Ken + Greer, HP Labs. Eight-bit implementation Christos S. Zoulas, Cornell University. + +BUGS + When a command is restarted from a stop, the shell prints the directory it started in if this is dif‐ + ferent from the current directory; this can be misleading (i.e., wrong) as the job may have changed + directories internally. + + Shell built-in functions are not stoppable/restartable. Command sequences of the form “a ; b ; c” are + also not handled gracefully when stopping is attempted. If you suspend ‘b’, the shell will immedi‐ + ately execute ‘c’. This is especially noticeable if this expansion results from an alias. It suf‐ + fices to place the sequence of commands in ()'s to force it to a sub-shell; i.e., “(a ; b ; c)”. + + Control over tty output after processes are started is primitive; perhaps this will inspire someone to + work on a good virtual terminal interface. In a virtual terminal interface much more interesting + things could be done with output control. + + Alias substitution is most often used to clumsily simulate shell procedures; shell procedures should + be provided instead of aliases. + + Commands within loops, prompted for by ‘?’, are not placed on the history list. Control structure + should be parsed instead of being recognized as built-in commands. This would allow control commands + to be placed anywhere, to be combined with ‘|’, and to be used with ‘&’ and ‘;’ metasyntax. + + It should be possible to use the ‘:’ modifiers on the output of command substitutions. + + The way the filec facility is implemented is ugly and expensive. + +BSD May 2, 2011 BSD diff --git a/week-04/korn.txt b/week-04/korn.txt new file mode 100644 index 0000000..0c398df --- /dev/null +++ b/week-04/korn.txt @@ -0,0 +1,2564 @@ +KSH(1) General Commands Manual KSH(1) + +NAME + ksh2020, rksh2020 - KornShell, a standard/restricted command and programming language + +NOTE + Currently, rksh and pfksh are not available on macOS / Darwin. + +SYNOPSIS + ksh [ ±abcefhiknoprstuvxBCDP ] [ -R file ] [ ±o option ] ... [ - ] [ arg ... ] + +DESCRIPTION + Ksh is a command and programming language that executes commands read from a terminal or a file. + Rksh is a restricted version of the command interpreter ksh; See Invocation below for the meaning of + arguments to the shell. + + Definitions. + A metacharacter is one of the following characters: + + ; & ( ) ⎪ < > new-line space tab + + A blank is a tab or a space. An identifier is a sequence of letters, digits, or underscores start‐ + ing with a letter or underscore. Identifiers are used as components of variable names. A vname is + a sequence of one or more identifiers separated by a . and optionally preceded by a .. Vnames are + used as function and variable names. A word is a sequence of characters from the character set de‐ + fined by the current locale, excluding non-quoted metacharacters. + + A command is a sequence of characters in the syntax of the shell language. The shell reads each + command and carries out the desired action either directly or by invoking separate utilities. A + built-in command is a command that is carried out by the shell itself without creating a separate + process. Some commands are built-in purely for convenience and are not documented here. Built-ins + that cause side effects in the shell environment and built-ins that are found before performing a + path search (see Execution below) are documented here. For historical reasons, some of these built- + ins behave differently than other built-ins and are called special built-ins. + + Commands. + A simple-command is a list of variable assignments (see Variable Assignments below) or a sequence of + blank separated words which may be preceded by a list of variable assignments (see Environment be‐ + low). The first word specifies the name of the command to be executed. Except as specified below, + the remaining words are passed as arguments to the invoked command. The command name is passed as + argument 0 (see exec(2)). The value of a simple-command is its exit status; 0-255 if it terminates + normally; 256+signum if it terminates abnormally (the name of the signal corresponding to the exit + status can be obtained via the -l option of the kill built-in utility). + + A pipeline is a sequence of one or more commands separated by ⎪. The standard output of each com‐ + mand but the last is connected by a pipe(2) to the standard input of the next command. Each com‐ + mand, except possibly the last, is run as a separate process; the shell waits for the last command + to terminate. The exit status of a pipeline is the exit status of the last command unless the + pipefail option is enabled. Each pipeline can be preceded by the reserved word ! which causes the + exit status of the pipeline to become 0 if the exit status of the last command is non-zero, and 1 if + the exit status of the last command is 0. + + A list is a sequence of one or more pipelines separated by ;, &, ⎪&, &&, or ⎪⎪, and optionally ter‐ + minated by ;, &, or ⎪&. Of these five symbols, ;, &, and ⎪& have equal precedence, which is lower + than that of && and ⎪⎪. The symbols && and ⎪⎪ also have equal precedence. A semicolon (;) causes + sequential execution of the preceding pipeline; an ampersand (&) causes asynchronous execution of + the preceding pipeline (i.e., the shell does not wait for that pipeline to finish). The symbol ⎪& + causes asynchronous execution of the preceding pipeline with a two-way pipe established to the par‐ + ent shell; the standard input and output of the spawned pipeline can be written to and read from by + the parent shell by applying the redirection operators <& and >& with arg p to commands and by using + -p option of the built-in commands read and print described later. The symbol && (⎪⎪) causes the + list following it to be executed only if the preceding pipeline returns a zero (non-zero) value. + One or more new-lines may appear in a list instead of a semicolon, to delimit a command. The first + item of the first pipeline of a list that is a simple command not beginning with a redirection, and + not occurring within a while, until, or if list, can be preceded by a semicolon. This semicolon is + ignored unless the showme option is enabled as described with the set built-in below. + + A command is either a simple-command or one of the following. Unless otherwise stated, the value + returned by a command is that of the last simple-command executed in the command. + + for vname [ in word ... ] ;do list ;done + Each time a for command is executed, vname is set to the next word taken from the in word + list. If in word ... is omitted, then the for command executes the do list once for each + positional parameter that is set starting from 1 (see Parameter Expansion below). Execution + ends when there are no more words in the list. + + for (( [expr1] ; [expr2] ; [expr3] )) ;do list ;done + The arithmetic expression expr1 is evaluated first (see Arithmetic evaluation below). The + arithmetic expression expr2 is repeatedly evaluated until it evaluates to zero and when non- + zero, list is executed and the arithmetic expression expr3 evaluated. If any expression is + omitted, then it behaves as if it evaluated to 1. + + select vname [ in word ... ] ;do list ;done + A select command prints on standard error (file descriptor 2) the set of words, each preceded + by a number. If in word ... is omitted, then the positional parameters starting from 1 are + used instead (see Parameter Expansion below). The PS3 prompt is printed and a line is read + from the standard input. If this line consists of the number of one of the listed words, + then the value of the variable vname is set to the word corresponding to this number. If + this line is empty, the selection list is printed again. Otherwise the value of the variable + vname is set to null. The contents of the line read from standard input is saved in the + variable REPLY. The list is executed for each selection until a break or end-of-file is en‐ + countered. If the REPLY variable is set to null by the execution of list, then the selection + list is printed before displaying the PS3 prompt for the next selection. + + case word in [ [(]pattern [ ⎪ pattern ] ... ) list ;; ] ... esac + A case command executes the list associated with the first pattern that matches word. The + form of the patterns is the same as that used for file-name generation (see File Name Genera‐ + tion below). The ;; operator causes execution of case to terminate. If ;& is used in place + of ;; the next subsequent list, if any, is executed. + + if list ;then list [ ;elif list ;then list ] ... [ ;else list ] ;fi + The list following if is executed and, if it returns a zero exit status, the list following + the first then is executed. Otherwise, the list following elif is executed and, if its value + is zero, the list following the next then is executed. Failing each successive elif list, + the else list is executed. If the if list has non-zero exit status and there is no else + list, then the if command returns a zero exit status. + + while list ;do list ;done + until list ;do list ;done + A while command repeatedly executes the while list and, if the exit status of the last com‐ + mand in the list is zero, executes the do list; otherwise the loop terminates. If no com‐ + mands in the do list are executed, then the while command returns a zero exit status; until + may be used in place of while to negate the loop termination test. + + ((expression)) + The expression is evaluated using the rules for arithmetic evaluation described below. If + the value of the arithmetic expression is non-zero, the exit status is 0, otherwise the exit + status is 1. + + (list) + Execute list in a separate environment. Note, that if two adjacent open parentheses are + needed for nesting, a space must be inserted to avoid evaluation as an arithmetic command as + described above. + + { list;} + list is simply executed. Note that unlike the metacharacters ( and ), { and } are reserved + words and must occur at the beginning of a line or after a ; in order to be recognized. + + [[ expression ]] + Evaluates expression and returns a zero exit status when expression is true. See Conditional + Expressions below, for a description of expression. + + function varname { list ;} + varname () { list ;} + Define a function which is referenced by varname. A function whose varname contains a . is + called a discipline function and the portion of the varname preceding the last . must refer + to an existing variable. The body of the function is the list of commands between { and }. + A function defined with the function varname syntax can also be used as an argument to the . + special built-in command to get the equivalent behavior as if the varname() syntax were used + to define it. (See Functions below.) + + namespace varname { list ;} + Defines or uses the name space identifier and runs the commands in list in this name space. + (See Name Spaces below.) + + & [ name [ arg... ] ] + Causes subsequent list commands terminated by & to be placed in the background job pool name. + If name is omitted a default unnamed pool is used. Commands in a named background pool may + be executed remotely. + + time [ pipeline ] + If pipeline is omitted the user and system time for the current shell and completed child + processes is printed on standard error. Otherwise, pipeline is executed and the elapsed time + as well as the user and system time are printed on standard error. The TIMEFORMAT variable + may be set to a format string that specifies how the timing information should be displayed. + See Shell Variables below for a description of the TIMEFORMAT variable. + + The following reserved words are recognized as reserved only when they are the first word of a com‐ + mand and are not quoted: + + if then else elif fi case esac for while until do done { } function select time [[ ]] ! + + Variable Assignments. + One or more variable assignments can start a simple command or can be arguments to the typeset, + enum, export, or readonly special built-in commands as well as to other declaration commands created + as types. The syntax for an assignment is of the form: + + varname=word + varname[word]=word + No space is permitted between varname and the = or between = and word. + + varname=(assign_list) + No space is permitted between varname and the =. The variable varname is unset before the + assignment. An assign_list can be one of the following: + word ... + Indexed array assignment. + [word]=word ... + Associative array assignment. If preceded by typeset -a this will create an + indexed array instead. + assignment ... + Compound variable assignment. This creates a compound variable varname with + sub-variables of the form varname.name, where name is the name portion of as‐ + signment. The value of varname will contain all the assignment elements. Ad‐ + ditional assignments made to sub-variables of varname will also be displayed + as part of the value of varname. If no assignments are specified, varname + will be a compound variable allowing subsequence child elements to be defined. + typeset [options] assignment ... + Nested variable assignment. Multiple assignments can be specified by separat‐ + ing each of them with a ;. The previous value is unset before the assignment. + Other declaration commands such as readonly, enum, and other declaration com‐ + mands can be used in place of typeset. + . filename + Include the assignment commands contained in filename. + + In addition, a += can be used in place of the = to signify adding to or appending to the previous + value. When += is applied to an arithmetic type, word is evaluated as an arithmetic expression and + added to the current value. When applied to a string variable, the value defined by word is ap‐ + pended to the value. For compound assignments, the previous value is not unset and the new values + are appended to the current ones provided that the types are compatible. + + The right hand side of a variable assignment undergoes all the expansion listed below except word + splitting, brace expansion, and file name generation. When the left hand side is an assignment is a + compound variable and the right hand is the name of a compound variable, the compound variable on + the right will be copied or appended to the compound variable on the left. + + Comments. + A word beginning with # causes that word and all the following characters up to a new-line to be ig‐ + nored. + Aliasing. + The first word of each command is replaced by the text of an alias if an alias for this word has + been defined. An alias name consists of any number of characters excluding metacharacters, quoting + characters, file expansion characters, parameter expansion and command substitution characters, the + characters / and =. The replacement string can contain any valid shell script including the + metacharacters listed above. The first word of each command in the replaced text, other than any + that are in the process of being replaced, will be tested for aliases. If the last character of the + alias value is a blank then the word following the alias will also be checked for alias substitu‐ + tion. Aliases can be used to redefine built-in commands but cannot be used to redefine the reserved + words listed above. Aliases can be created and listed with the alias command and can be removed + with the unalias command. + Aliasing is performed when scripts are read, not while they are executed. Therefore, for an alias + to take effect, the alias definition command has to be executed before the command which references + the alias is read. + The following aliases are compiled into the shell but can be unset or redefined: + autoload=′typeset -fu′ + bool=′_Bool′ + command=′command ′ + compound=′typeset -C′ + fc=hist + float=′typeset -lE′ + functions=′typeset -f′ + hash=′alias -t --′ + history=′hist -l′ + integer=′typeset -li′ + nameref=′typeset -n′ + nohup=′nohup ′ + r=′hist -s′ + redirect=′command exec′ + source=′command .′ + stop=′kill -s STOP′ + suspend=′kill -s STOP "$$"′ + type=′whence -v′ + + Tilde Substitution. + After alias substitution is performed, each word is checked to see if it begins with an unquoted ∼. + For tilde substitution, word also refers to the word portion of parameter expansion (see Parameter + Expansion below). If it does, then the word up to a / is checked to see if it matches a user name + in the password database (See getpwname(3).) If a match is found, the ∼ and the matched login name + are replaced by the login directory of the matched user. If no match is found, the original text is + left unchanged. A ∼ by itself, or in front of a /, is replaced by $HOME. A ∼ followed by a + or - + is replaced by the value of $PWD and $OLDPWD respectively. A ∼ followed by {fd} where fd is a file + descriptor number or the name of a variable whose value is a file descriptor, is replaced by a + string that is the equivalent to the path name of the file or directory corresponding to this file + descriptor. + + In addition, when expanding a variable assignment, tilde substitution is attempted when the value of + the assignment begins with a ∼, and when a ∼ appears after a :. The : also terminates a ∼ login + name. + + Command Substitution. + The standard output from a command list enclosed in parentheses preceded by a dollar sign ( $(list) + ), or in a brace group preceded by a dollar sign ( ${ list;} ), or in a pair of grave accents (``) + may be used as part or all of a word; trailing new-lines are removed. In the second case, the { and + } are treated as a reserved words so that { must be followed by a blank and } must appear at the be‐ + ginning of the line or follow a ;. In the third (obsolete) form, the string between the quotes is + processed for special quoting characters before the command is executed (see Quoting below). The + command substitution $(cat file) can be replaced by the equivalent but faster $((list) will run process list asynchronously connected + to some file in /dev/fd if this directory exists, or else a fifo a temporary directory. The name of + this file will become the argument to the command. If the form with > is selected then writing on + this file will provide input for list. If < is used, then the file passed as an argument will con‐ + tain the output of the list process. For example, + + paste <(cut -f1 file1) <(cut -f3 file2) | tee >(process1) >(process2) + + cuts fields 1 and 3 from the files file1 and file2 respectively, pastes the results together, and + sends it to the processes process1 and process2, as well as putting it onto the standard output. + Note that the file, which is passed as an argument to the command, is a UNIX pipe(2) so programs + that expect to lseek(2) on the file will not work. + + Process substitution of the form <(list) can also be used with the < redirection operator which + causes the output of list to be standard input or the input for whatever file descriptor is speci‐ + fied. + + Parameter Expansion. + A parameter is a variable, one or more digits, or any of the characters *, @, #, ?, -, $, and !. A + variable is denoted by a vname. To create a variable whose vname contains a ., a variable whose + vname consists of everything before the last . must already exist. A variable has a value and zero + or more attributes. Variables can be assigned values and attributes by using the typeset special + built-in command. The attributes supported by the shell are described later with the typeset spe‐ + cial built-in command. Exported variables pass values and attributes to the environment. + + The shell supports both indexed and associative arrays. An element of an array variable is refer‐ + enced by a subscript. A subscript for an indexed array is denoted by an arithmetic expression (see + Arithmetic evaluation below) between a [ and a ]. To assign values to an indexed array, use + vname=(value ...) or set -A vname value ... . The value of all non-negative subscripts must be in + the range of 0 through 4,194,303. A negative subscript is treated as an offset from the maximum + current index +1 so that -1 refers to the last element. Indexed arrays can be declared with the -a + option to typeset. Indexed arrays need not be declared. Any reference to a variable with a valid + subscript is legal and an array will be created if necessary. + + An associative array is created with the -A option to typeset. A subscript for an associative array + is denoted by a string enclosed between [ and ]. + + Referencing any array without a subscript is equivalent to referencing the array with subscript 0. + + The value of a variable may be assigned by writing: + + vname=value [ vname=value ] ... + + or + vname[subscript]=value [ vname[subscript]=value ] ... + Note that no space is allowed before or after the =. + Attributes assigned by the typeset special built-in command apply to all elements of the array. An + array element can be a simple variable, a compound variable or an array variable. An element of an + indexed array can be either an indexed array or an associative array. An element of an associative + array can also be either. To refer to an array element that is part of an array element, concate‐ + nate the subscript in brackets. For example, to refer to the foobar element of an associative array + that is defined as the third element of the indexed array, use ${vname[3][foobar]} + A nameref is a variable that is a reference to another variable. A nameref is created with the -n + attribute of typeset. The value of the variable at the time of the typeset command becomes the + variable that will be referenced whenever the nameref variable is used. The name of a nameref can‐ + not contain a .. When a variable or function name contains a ., and the portion of the name up to + the first . matches the name of a nameref, the variable referred to is obtained by replacing the + nameref portion with the name of the variable referenced by the nameref. If a nameref is used as + the index of a for loop, a name reference is established for each item in the list. A nameref pro‐ + vides a convenient way to refer to the variable inside a function whose name is passed as an argu‐ + ment to a function. For example, if the name of a variable is passed as the first argument to a + function, the command + typeset -n var=$1 + inside the function causes references and assignments to var to be references and assignments to the + variable whose name has been passed to the function. + If any of the floating point attributes, -E, -F, or -X, or the integer attribute, -i, is set for + vname, then the value is subject to arithmetic evaluation as described below. + Positional parameters, parameters denoted by a number, may be assigned values with the set special + built-in command. Parameter $0 is set from argument zero when the shell is invoked. + The character $ is used to introduce substitutable parameters. + ${parameter} + The shell reads all the characters from ${ to the matching } as part of the same word even if + it contains braces or metacharacters. The value, if any, of the parameter is substituted. + The braces are required when parameter is followed by a letter, digit, or underscore that is + not to be interpreted as part of its name, when the variable name contains a .. The braces + are also required when a variable is subscripted unless it is part of an Arithmetic Expres‐ + sion or a Conditional Expression. If parameter is one or more digits then it is a positional + parameter. A positional parameter of more than one digit must be enclosed in braces. If pa‐ + rameter is * or @, then all the positional parameters, starting with $1, are substituted + (separated by a field separator character). If an array vname with last subscript * @, or + for index arrays of the form sub1 .. sub2. is used, then the value for each of the elements + between sub1 and sub2 inclusive (or all elements for * and @) is substituted, separated by + the first character of the value of IFS. + ${#parameter} + If parameter is * or @, the number of positional parameters is substituted. Otherwise, the + length of the value of the parameter is substituted. + ${#vname[*]} + ${#vname[@]} + The number of elements in the array vname is substituted. + + ${@vname} + Expands to the type name (See Type Variables below) or attributes of the variable referred + to by vname. + ${$parameter} + If $parameter expands to the name of a variable, this expands to the value of that variable. + Otherwise, it expands to the empty string. It is undefined for special parameters. + ${!vname} + Expands to the name of the variable referred to by vname. This will be vname except when + vname is a name reference. + ${!vname[subscript]} + Expands to name of the subscript unless subscript is *, @. or of the form sub1 .. sub2. + When subscript is *, the list of array subscripts for vname is generated. For a variable + that is not an array, the value is 0 if the variable is set. Otherwise it is null. When + subscript is @, same as above, except that when used in double quotes, each array subscript + yields a separate argument. When subscript is of the form sub1 .. sub2 it expands to the + list of subscripts between sub1 and sub2 inclusive using the same quoting rules as @. + ${!prefix*} + Expands to the names of the variables whose names begin with prefix. + ${parameter:-word} + If parameter is set and is non-null then substitute its value; otherwise substitute word. + ${parameter:=word} + If parameter is not set or is null then set it to word; the value of the parameter is then + substituted. Positional parameters may not be assigned to in this way. + ${parameter:?word} + If parameter is set and is non-null then substitute its value; otherwise, print word and exit + from the shell (if not interactive). If word is omitted then a standard message is printed. + ${parameter:+word} + If parameter is set and is non-null then substitute word; otherwise substitute nothing. + In the above, word is not evaluated unless it is to be used as the substituted string, so that, in + the following example, pwd is executed only if d is not set or is null: + print ${d:-$(pwd)} + If the colon ( : ) is omitted from the above expressions, then the shell only checks whether parame‐ + ter is set or not. + ${parameter:offset:length} + ${parameter:offset} + Expands to the portion of the value of parameter starting at the character (counting from 0) + determined by expanding offset as an arithmetic expression and consisting of the number of + characters determined by the arithmetic expression defined by length. In the second form, + the remainder of the value is used. If A negative offset counts backwards from the end of + parameter. Note that one or more blanks is required in front of a minus sign to prevent the + shell from interpreting the operator as :-. If parameter is * or @, or is an array name in‐ + dexed by * or @, then offset and length refer to the array index and number of elements re‐ + spectively. A negative offset is taken relative to one greater than the highest subscript + for indexed arrays. The order for associate arrays is unspecified. + ${parameter#pattern} + ${parameter##pattern} + If the shell pattern matches the beginning of the value of parameter, then the value of this + expansion is the value of the parameter with the matched portion deleted; otherwise the value + of this parameter is substituted. In the first form the smallest matching pattern is deleted + and in the second form the largest matching pattern is deleted. When parameter is @, *, or + an array variable with subscript @ or *, the substring operation is applied to each element + in turn. + + ${parameter%pattern} + ${parameter%%pattern} + If the shell pattern matches the end of the value of parameter, then the value of this expan‐ + sion is the value of the parameter with the matched part deleted; otherwise substitute the + value of parameter. In the first form the smallest matching pattern is deleted and in the + second form the largest matching pattern is deleted. When parameter is @, *, or an array + variable with subscript @ or *, the substring operation is applied to each element in turn. + + ${parameter/pattern/string} + ${parameter//pattern/string} + ${parameter/#pattern/string} + ${parameter/%pattern/string} + Expands parameter and replaces the longest match of pattern with the given string. Each oc‐ + currence of \n in string is replaced by the portion of parameter that matches the n-th sub- + pattern. In the first form, only the first occurrence of pattern is replaced. In the second + form, each match for pattern is replaced by the given string. The third form restricts the + pattern match to the beginning of the string while the fourth form restricts the pattern + match to the end of the string. When string is null, the pattern will be deleted and the / + in front of string may be omitted. When parameter is @, *, or an array variable with sub‐ + script @ or *, the substitution operation is applied to each element in turn. In this case, + the string portion of word will be re-evaluated for each element. + + ${parameter^pattern} + ${parameter^^pattern} + ${parameter,pattern} + ${parameter,,pattern} + Case modification. This expansion modifies the case of alphabetic characters in parameter. + The pattern is expanded to produce a pattern just as in pathname expansion. The ^ operator + converts lowercase characters matching pattern to uppercase. The , operator converts match‐ + ing uppercase characters to lowercase. The ^^ and ,, expansions convert all matched + character in the expanded value. The ^ and , expansions match and convert only the first + character in the expanded value. If pattern is omitted it is treated like a ?, which + matches every character. If parameter is @ or *, or an array subscripted by @ or *, the case + modification operation is applied to each element. + + The following parameters are automatically set by the shell: + # The number of positional parameters in decimal. + - Options supplied to the shell on invocation or by the set command. + ? The decimal value returned by the last executed command. + $ The process number of this shell. + _ Initially, the value of _ is an absolute pathname of the shell or script being exe‐ + cuted as passed in the environment. Subsequently it is assigned the last argument of + the previous command. This parameter is not set for commands which are asynchronous. + This parameter is also used to hold the name of the matching MAIL file when checking + for mail. While defining a compound variable or a type, _ is initialized as a refer‐ + ence to the compound variable or type. When a discipline function is invoked, _ is + initialized as a reference to the variable associated with the call to this function. + Finally when _ is used as the name of the first variable of a type definition, the new + type is derived from the type of the first variable (See Type Variables below.). + ! The process id or the pool name and job number of the last background command invoked + or the most recent job put in the background with the bg built-in command. Background + jobs started in a named pool will be in the form pool.number where pool is the pool + name and number is the job number within that pool. + .sh.command + When processing a DEBUG trap, this variable contains the current command line that is + about to run. + .sh.edchar + This variable contains the value of the keyboard character (or sequence of characters + if the first character is an ESC, ascii 033) that has been entered when processing a + KEYBD trap (see Key Bindings below). If the value is changed as part of the trap ac‐ + tion, then the new value replaces the key (or key sequence) that caused the trap. + .sh.edcol + The character position of the cursor at the time of the most recent KEYBD trap. + .sh.edmode + The value is set to ESC when processing a KEYBD trap while in vi insert mode. (See Vi + Editing Mode below.) Otherwise, .sh.edmode is null when processing a KEYBD trap. + .sh.edtext + The characters in the input buffer at the time of the most recent KEYBD trap. The + value is null when not processing a KEYBD trap. + .sh.file + The pathname of the file than contains the current command. + .sh.fun + The name of the current function that is being executed. + .sh.level + Set to the current function depth. This can be changed inside a DEBUG trap and will + set the context to the specified level. + .sh.lineno + Set during a DEBUG trap to the line number for the caller of each function. + .sh.match + An indexed array which stores the most recent match and sub-pattern matches after con‐ + ditional pattern matches that match and after variables expansions using the operators + #, %, or /. The 0-th element stores the complete match and the i-th. element stores + the i-th submatch. For // the array is two dimensional with the first subscript indi‐ + cating the most recent match and sub-pattern match and the second script indicating + which match with 0 representing the first match. The .sh.match variable becomes unset + when the variable that has expanded is assigned a new value. + .sh.math + Used for defining arithmetic functions (see Arithmetic evaluation below). and stores + the list of user defined arithmetic functions. + .sh.name + Set to the name of the variable at the time that a discipline function is invoked. + .sh.op_astbin + The directory where several shell built-in commands are bound to. The default is + /opt/ast/bin. When the value is /bin, then builtins will be bound to /bin or /usr/bin + depending on where the executable is found. This variable can be set by including it + in the SH_OPTIONS variable. + .sh.pgrp + The current process group of this shell. + .sh.pwdfd + The file descriptor number for the present working directory. + .sh.sig + Set when executing a trap to the information contained in the siginfo_t structure (See + siginfo(2) for a description of this structure.) + .sh.subscript + Set to the name subscript of the variable at the time that a discipline function is + invoked. + .sh.subshell + The current depth for subshells and command substitution. + .sh.value + Set to the value of the variable at the time that the set or append discipline func‐ + tion is invoked. When a user defined arithmetic function is invoked, the value of + .sh.value is saved and .sh.value is set to long double precision floating point. + .sh.value is restored when the function returns. + .sh.version + Set to a value that identifies the version of this shell. + KSH_VERSION + A name reference to .sh.version. + LINENO The current line number within the script or function being executed. + OLDPWD The previous working directory set by the cd command. + OPTARG The value of the last option argument processed by the getopts built-in command. + OPTIND The index of the last option argument processed by the getopts built-in command. + PPID The process number of the parent of the shell. + PWD The present working directory set by the cd command. + RANDOM Each time this variable is referenced, a random integer, uniformly distributed between + 0 and 32767, is generated. The sequence of random numbers can be initialized by as‐ + signing a numeric value to RANDOM. + REPLY This variable is set by the select statement and by the read built-in command when no + arguments are supplied. + SECONDS + Each time this variable is referenced, the number of seconds since shell invocation is + returned. If this variable is assigned a value, then the value returned upon refer‐ + ence will be the value that was assigned plus the number of seconds since the assign‐ + ment. + SHLVL An integer variable the is incremented each time the shell is invoked and is exported. + If SHLVL is not in the environment when the shell is invoked, it is set to 1. + + The following variables are used by the shell: + CDPATH The search path for the cd command. + COLUMNS + If this variable is set, the value is used to define the width of the edit window for + the shell edit modes and for printing select lists. + EDITOR If the VISUAL variable is not set, the value of this variable will be checked for the + patterns as described with VISUAL below and the corresponding editing option (see Spe‐ + cial Command set below) will be turned on. + ENV If this variable is set, then parameter expansion, command substitution, and arith‐ + metic substitution are performed on the value to generate the pathname of the script + that will be executed when the shell is invoked interactively (see Invocation below). + This file is typically used for alias and function definitions. The default value is + $HOME/.kshrc. On systems that support a system wide /etc/ksh.kshrc initialization + file, if the filename generated by the expansion of ENV begins with /./ or ././ the + system wide initialization file will not be executed. + FCEDIT Obsolete name for the default editor name for the hist command. FCEDIT is not used + when HISTEDIT is set. + FIGNORE + A pattern that defines the set of filenames that will be ignored when performing file‐ + name matching. + FPATH The search path for function definitions. The directories in this path are searched + for a file with the same name as the function or command when a function with the -u + attribute is referenced and when a command is not found. If an executable file with + the name of that command is found, then it is read and executed in the current envi‐ + ronment. Unlike PATH, the current directory must be represented explicitly by . + rather than by adjacent : characters or a beginning or ending :. + HISTCMD + Number of the current command in the history file. + HISTEDIT + Name for the default editor name for the hist command. + HISTFILE + If this variable is set when the shell is invoked, then the value is the pathname of + the file that will be used to store the command history (see Command Re-entry below). + HISTSIZE + If this variable is set when the shell is invoked, then the number of previously en‐ + tered commands that are accessible by this shell will be greater than or equal to this + number. The default is 512. + HOME The default argument (home directory) for the cd command. + IFS Internal field separators, normally space, tab, and new-line that are used to separate + the results of command substitution or parameter expansion and to separate fields with + the built-in command read. The first character of the IFS variable is used to sepa‐ + rate arguments for the "$*" substitution (see Quoting below). Each single occurrence + of an IFS character in the string to be split, that is not in the isspace character + class, and any adjacent characters in IFS that are in the isspace character class, de‐ + limit a field. One or more characters in IFS that belong to the isspace character + class, delimit a field. In addition, if the same isspace character appears consecu‐ + tively inside IFS, this character is treated as if it were not in the isspace class, + so that if IFS consists of two tab characters, then two adjacent tab characters de‐ + limit a null field. + JOBMAX This variable defines the maximum number running background jobs that can run at a + time. When this limit is reached, the shell will wait for a job to complete before + staring a new job. + LANG This variable determines the locale category for any category not specifically se‐ + lected with a variable starting with LC_ or LANG. + LC_ALL This variable overrides the value of the LANG variable and any other LC_ variable. + LC_COLLATE + This variable determines the locale category for character collation information. + LC_CTYPE + This variable determines the locale category for character handling functions. It de‐ + termines the character classes for pattern matching (see File Name Generation below). + LC_NUMERIC + This variable determines the locale category for the decimal point character. + LINES If this variable is set, the value is used to determine the column length for printing + select lists. Select lists will print vertically until about two-thirds of LINES + lines are filled. + MAIL If this variable is set to the name of a mail file and the MAILPATH variable is not + set, then the shell informs the user of arrival of mail in the specified file. + MAILCHECK + This variable specifies how often (in seconds) the shell will check for changes in the + modification time of any of the files specified by the MAILPATH or MAIL variables. + The default value is 600 seconds. When the time has elapsed the shell will check be‐ + fore issuing the next prompt. + MAILPATH + A colon ( : ) separated list of file names. If this variable is set, then the shell + informs the user of any modifications to the specified files that have occurred within + the last MAILCHECK seconds. Each file name can be followed by a ? and a message that + will be printed. The message will undergo parameter expansion, command substitution, + and arithmetic substitution with the variable $_ defined as the name of the file that + has changed. The default message is you have mail in $_. + PATH The search path for commands (see Execution below). The user may not change PATH if + executing under rksh (except in .profile). + PS1 The value of this variable is expanded for parameter expansion, command substitution, + and arithmetic substitution to define the primary prompt string which by default is + ``$ ''. The character ! in the primary prompt string is replaced by the command num‐ + ber (see Command Re-entry below). Two successive occurrences of ! will produce a + single ! when the prompt string is printed. + PS2 Secondary prompt string, by default ``> ''. + PS3 Selection prompt string used within a select loop, by default ``#? ''. + PS4 The value of this variable is expanded for parameter evaluation, command substitution, + and arithmetic substitution and precedes each line of an execution trace. By default, + PS4 is ``+ ''. In addition when PS4 is unset, the execution trace prompt is also ``+ + ''. + SH_OPTIONS + The value consists of blank separated name=value words. For each name that is the + name of a known option the variable .sh.opt_name is assigned value. Currently the + only valid option name is astbin. + SHELL The pathname of the shell is kept in the environment. At invocation, if the basename + of this variable is rsh, rksh, or krsh, then the shell becomes restricted. + TIMEFORMAT + The value of this parameter is used as a format string specifying how the timing in‐ + formation for pipelines prefixed with the time reserved word should be displayed. The + % character introduces a format sequence that is expanded to a time value or other in‐ + formation. The format sequences and their meanings are as follows. + %% A literal %. + %[p][l]R The elapsed time in seconds. + %[p][l]U The number of CPU seconds spent in user mode. + %[p][l]S The number of CPU seconds spent in system mode. + %[p][l]C The total number of CPU seconds; i.e., the sum of the time spent in user + plus system mode. + %P The CPU percentage (i.e., CPU utilization), computed as C / R. + + The brackets denote optional portions. The optional p is a digit specifying the pre‐ + cision, the number of fractional digits after a decimal point. A value of 0 causes no + decimal point or fraction to be output. At most three places after the decimal point + can be displayed; values of p greater than 3 are treated as 3. If p is not specified, + the value 3 is used. + + The optional l specifies a longer format, including hours if greater than zero, min‐ + utes, and seconds of the form HHhMMmSS.FFs. The value of p determines whether or not + the fraction is included. + + All other characters are output without change and a trailing newline is added. If + unset, the default value, $'\nreal\t%2lR\nuser\t%2lU\nsys%2lS', is used. If the value + is null, no timing information is displayed. + + TMOUT If set to a value greater than zero, TMOUT will be the default timeout value for the + read built-in command. The select compound command terminates after TMOUT seconds + when input is from a terminal. Otherwise, the shell will terminate if a line is not + entered within the prescribed number of seconds while reading from a terminal. (Note + that the shell can be compiled with a maximum bound for this value which cannot be ex‐ + ceeded.) + + VISUAL If the value of this variable matches the pattern *[Vv][Ii]*, then the vi option (see + Special Command set below) is turned on. If the value matches the pattern *gmacs* , + the gmacs option is turned on. If the value matches the pattern *macs*, then the + emacs option will be turned on. The value of VISUAL overrides the value of EDITOR. + + The shell gives default values to PATH, PS1, PS2, PS3, PS4, MAILCHECK, FCEDIT, TMOUT and IFS, while + HOME, SHELL, ENV, and MAIL are not set at all by the shell (although HOME is set by login(1)). On + some systems MAIL and SHELL are also set by login(1). + + Field Splitting. + After parameter expansion and command substitution, the results of substitutions are scanned for the + field separator characters (those found in IFS) and split into distinct fields where such characters + are found. Explicit null fields ("" or ′′) are retained. Implicit null fields (those resulting + from parameters that have no values or command substitutions with no output) are removed. + + If the braceexpand (-B) option is set then each of the fields resulting from IFS are checked to see + if they contain one or more of the brace patterns {*,*}, {l1..l2} , {n1..n2} , {n1..n2% fmt} , + {n1..n2 ..n3} , or {n1..n2 ..n3%fmt} , where * represents any character, l1,l2 are letters and + n1,n2,n3 are signed numbers and fmt is a format specified as used by printf. In each case, fields + are created by prepending the characters before the { and appending the characters after the } to + each of the strings generated by the characters between the { and }. The resulting fields are + checked to see if they have any brace patterns. + + In the first form, a field is created for each string between { and ,, between , and ,, and between + , and }. The string represented by * can contain embedded matching { and } without quoting. Other‐ + wise, each { and } with * must be quoted. + + In the seconds form, l1 and l2 must both be either upper case or both be lower case characters in + the C locale. In this case a field is created for each character from l1 thru l2. + + In the remaining forms, a field is created for each number starting at n1 and continuing until it + reaches n2 incrementing n1 by n3. The cases where n3 is not specified behave as if n3 where 1 if + n1<=n2 and -1 otherwise. If forms which specify %fmt any format flags, widths and precisions can be + specified and fmt can end in any of the specifiers cdiouxX. For example, {a,z}{1..5..3%02d}{b..c}x + expands to the 8 fields, a01bx, a01cx, a04bx, a04cx, z01bx, z01cx, z04bx and z4cx. + + File Name Generation. + Following splitting, each field is scanned for the characters *, ?, (, and [ unless the -f option + has been set. If one of these characters appears, then the word is regarded as a pattern. Each + file name component that contains any pattern character is replaced with a lexicographically sorted + set of names that matches the pattern from that directory. If no file name is found that matches + the pattern, then that component of the filename is left unchanged unless the pattern is prefixed + with ∼(N) in which case it is removed as described below. If FIGNORE is set, then each file name + component that matches the pattern defined by the value of FIGNORE is ignored when generating the + matching filenames. The names . and .. are also ignored. If FIGNORE is not set, the character . + at the start of each file name component will be ignored unless the first character of the pattern + corresponding to this component is the character . itself. Note, that for other uses of pattern + matching the / and . are not treated specially. + + * Matches any string, including the null string. When used for filename expansion, if + the globstar option is on, an isolated pattern of two adjacent *'s will match all + files and zero or more directories and subdirectories. If followed by a / then only + directories and subdirectories will match. + ? Matches any single character. + [...] Matches any one of the enclosed characters. A pair of characters separated by - + matches any character lexically between the pair, inclusive. If the first character + following the opening [ is a ! or ^ then any character not enclosed is matched. A - + can be included in the character set by putting it as the first or last character. + Within [ and ], character classes can be specified with the syntax [:class:] where + class is one of the following classes defined in the ANSI-C standard: (Note that word + is equivalent to alnum plus the character _.) + alnum alpha blank cntrl digit graph lower print punct space upper word xdigit + Within [ and ], an equivalence class can be specified with the syntax [=c=] which + matches all characters with the same primary collation weight (as defined by the cur‐ + rent locale) as the character c. Within [ and ], [.symbol.] matches the collating + symbol symbol. + A pattern-list is a list of one or more patterns separated from each other with a & or ⎪. A & sig‐ + nifies that all patterns must be matched whereas ⎪ requires that only one pattern be matched. Com‐ + posite patterns can be formed with one or more of the following sub-patterns: + ?(pattern-list) + Optionally matches any one of the given patterns. + *(pattern-list) + Matches zero or more occurrences of the given patterns. + +(pattern-list) + Matches one or more occurrences of the given patterns. + {n}(pattern-list) + Matches n occurrences of the given patterns. + {m,n}(pattern-list) + Matches from m to n occurrences of the given patterns. If m is omitted, 0 will be + used. If n is omitted at least m occurrences will be matched. + @(pattern-list) + Matches exactly one of the given patterns. + !(pattern-list) + Matches anything except one of the given patterns. + By default, each pattern, or sub-pattern will match the longest string possible consistent with gen‐ + erating the longest overall match. If more than one match is possible, the one starting closest to + the beginning of the string will be chosen. However, for each of the above compound patterns a - + can be inserted in front of the ( to cause the shortest match to the specified pattern-list to be + used. + + When pattern-list is contained within parentheses, the backslash character \ is treated specially + even when inside a character class. All ANSI-C character escapes are recognized and match the + specified character. In addition the following escape sequences are recognized: + \d Matches any character in the digit class. + \D Matches any character not in the digit class. + \s Matches any character in the space class. + \S Matches any character not in the space class. + \w Matches any character in the word class. + \W Matches any character not in the word class. + + A pattern of the form %(pattern-pair(s)) is a sub-pattern that can be used to match nested character + expressions. Each pattern-pair is a two character sequence which cannot contain & or ⎪. The first + pattern-pair specifies the starting and ending characters for the match. Each subsequent pattern- + pair represents the beginning and ending characters of a nested group that will be skipped over when + counting starting and ending character matches. The behavior is unspecified when the first charac‐ + ter of a pattern-pair is alpha-numeric except for the following: + D Causes the ending character to terminate the search for this pattern without finding a + match. + E Causes the ending character to be interpreted as an escape character. + L Causes the ending character to be interpreted as a quote character causing all charac‐ + ters to be ignored when looking for a match. + Q Causes the ending character to be interpreted as a quote character causing all charac‐ + ters other than any escape character to be ignored when looking for a match. + Thus, %({}Q"E\), matches characters starting at { until the matching } is found not counting any { + or } that is inside a double quoted string or preceded by the escape character \. Without the {} + this pattern matches any C language string. + + Each sub-pattern in a composite pattern is numbered, starting at 1, by the location of the ( within + the pattern. The sequence \n, where n is a single digit and \n comes after the n-th. sub-pattern, + matches the same string as the sub-pattern itself. + + Finally a pattern can contain sub-patterns of the form ∼(options:pattern-list), where either options + or :pattern-list can be omitted. Unlike the other compound patterns, these sub-patterns are not + counted in the numbered sub-patterns. :pattern-list must be omitted for options F, G, N , and V be‐ + low. If options is present, it can consist of one or more of the following: + + Enable the following options. This is the default. + - Disable the following options. + E The remainder of the pattern uses extended regular expression syntax like the egrep(1) + command. + F The remainder of the pattern uses fgrep(1) expression syntax. + G The remainder of the pattern uses basic regular expression syntax like the grep(1) + command. + K The remainder of the pattern uses shell pattern syntax. This is the default. + N This is ignored. However, when it is the first letter and is used with file name gen‐ + eration, and no matches occur, the file pattern expands to the empty string. + X The remainder of the pattern uses augmented regular expression syntax like the + xgrep(1) command. + P The remainder of the pattern uses perl(1) regular expression syntax. Not all perl + regular expression syntax is currently implemented. + V The remainder of the pattern uses System V regular expression syntax. + i Treat the match as case insensitive. + g File the longest match (greedy). This is the default. + l Left anchor the pattern. This is the default for K style patterns. + r Right anchor the pattern. This is the default for K style patterns. + If both options and :pattern-list are specified, then the options apply only to pattern-list. Oth‐ + erwise, these options remain in effect until they are disabled by a subsequent ∼(...) or at the end + of the sub-pattern containing ∼(...). + + Quoting. + Each of the metacharacters listed earlier (see Definitions above) has a special meaning to the shell + and causes termination of a word unless quoted. A character may be quoted (i.e., made to stand for + itself) by preceding it with a \. The pair \new-line is removed. All characters enclosed between a + pair of single quote marks (′′) that is not preceded by a $ are quoted. A single quote cannot ap‐ + pear within the single quotes. A single quoted string preceded by an unquoted $ is processed as an + ANSI-C string except for the following: + \0 Causes the remainder of the string to be ignored. + \E Equivalent to the escape character (ascii 033), + \e Equivalent to the escape character (ascii 033), + \cx Expands to the character control-x. + \C[.name.] + Expands to the collating element name. + + Inside double quote marks (""), parameter and command substitution occur and \ quotes the characters + \, `, ", and $. A $ in front of a double quoted string will be ignored in the "C" or "POSIX" lo‐ + cale, and may cause the string to be replaced by a locale specific string otherwise. The meaning of + $* and $@ is identical when not quoted or when used as a variable assignment value or as a file + name. However, when used as a command argument, "$*" is equivalent to "$1d$2d...", where d is the + first character of the IFS variable, whereas "$@" is equivalent to "$1" "$2" .... Inside grave + quote marks (``), \ quotes the characters \, `, and $. If the grave quotes occur within double + quotes, then \ also quotes the character ". + + The special meaning of reserved words or aliases can be removed by quoting any character of the re‐ + served word. The recognition of function names or built-in command names listed below cannot be al‐ + tered by quoting them. + + Arithmetic Evaluation. + The shell performs arithmetic evaluation for arithmetic substitution, to evaluate an arithmetic com‐ + mand, to evaluate an indexed array subscript, and to evaluate arguments to the built-in commands + shift and let. Evaluations are performed using double precision floating point arithmetic or long + double precision floating point for systems that provide this data type. Floating point constants + follow the ANSI-C programming language floating point conventions. The floating point constants Nan + and Inf can be use to represent "not a number" and infinity respectively. Integer constants follow + the ANSI-C programming language integer constant conventions although only single byte character + constants are recognized and character casts are not recognized. In addition constants can be of + the form [base#]n where base is a decimal number between two and sixty-four representing the arith‐ + metic base and n is a number in that base. The digits above 9 are represented by the lower case + letters, the upper case letters, @, and _ respectively. For bases less than or equal to 36, upper + and lower case characters can be used interchangeably. + + An arithmetic expression uses the same syntax, precedence, and associativity of expression as the C + language. All the C language operators that apply to floating point quantities can be used. In ad‐ + dition, the operator ** can be used for exponentiation. It has higher precedence than multiplica‐ + tion and is left associative. In addition, when the value of an arithmetic variable or sub-expres‐ + sion can be represented as a long integer, all C language integer arithmetic operations can be per‐ + formed. Variables can be referenced by name within an arithmetic expression without using the pa‐ + rameter expansion syntax. When a variable is referenced, its value is evaluated as an arithmetic + expression. + + Any of the following math library functions that are in the C math library can be used within an + arithmetic expression: + + abs acos acosh asin asinh atan atan2 atanh cbrt ceil copysign cos cosh erf erfc exp exp2 expm1 fabs + fdim finite floor fma fmax fmin fmod hypot ilogb int isfinite sinf isnan isnormal issubnormal issub‐ + ordered iszero j0 j1 jn lgamma log log10 log2 logb nearbyint pow remainder rint round scanb signbit + sin sinh sqrt tan tanh tgamma trunc y0 y1 yn In addition, arithmetic functions can be defined as + shell functions with a variant of the function name syntax, + + function .sh.math.name ident ... { list ;} + where name is the function name used in the arithmetic expression. If the calling argument + corresponding to ident is the name of an array variable, then ident is a name reference to + this array. Otherwise, ident is a reference to long double precision floating point variable + containing the value from the caller. The value of .sh.value when the function returns is + the value of this function. User defined functions can take up to 3 arguments and override C + math library functions. + + An internal representation of a variable as a double precision floating point can be specified with + the -E [n], -F [n], or -X [n] option of the typeset special built-in command. The -E option causes + the expansion of the value to be represented using scientific notation when it is expanded. The op‐ + tional option argument n defines the number of significant figures. The -F option causes the expan‐ + sion to be represented as a floating decimal number when it is expanded. The -X option cause the + expansion to be represented using the %a format defined by ISO C-99. The optional option argument n + defines the number of places after the decimal (or radix) point in this case. + + An internal integer representation of a variable can be specified with the -i [n] option of the + typeset special built-in command. The optional option argument n specifies an arithmetic base to be + used when expanding the variable. If you do not specify an arithmetic base, base 10 will be used. + + Arithmetic evaluation is performed on the value of each assignment to a variable with the -E, -F, + -X, or -i attribute. Assigning a floating point number to a variable whose type is an integer + causes the fractional part to be truncated. + + Inside an arithmetic expression, all integer and floating point variables can be following by .MIN, + .MAX, or .DIG to give the maximum value, minimum value, or number of significant digits for vari‐ + ables of that type. + + Floating point variables can be also followed by .INT_MAX or .INT_MIN to give the largest or small‐ + est integers represented by that type. + + Floating point variables can also be followed by .EPSILON to give the distance to the next floating + point number of that type. Floating point variables can be followed by MAX_10_EXP to give the maxi‐ + mum base 10 exponent that can be represented by that type. + + Inside an arithmetic expression, the following constants are recongnized and are of type typeset-lE. + NaN Not a number. It is case insensitive. + Inf Infinity. It is case insensitive. + E + PI + 1_PI 1.0/PI. + 2_PI 2.0/PI. + PI_2 PI/2.0 + PI_4 PI/4.0. + SQRTPI sqrt(PI). + SQRT2 sqrt(2.0). + SQRT1_2 + sqrt(1./2.) + LOGE log(E) + LOG10E log10(E) + LN2 log(2.0) + LOG2E log2(E) + + Array Sorting. + The -s option of the set built-in command can be used to sort its arguments or to sort indexed ar‐ + rays, indexed arrays of compound variables, and indexed arrays of types (see "Type Variables" sec‐ + tion below). By default the sort order is defined by the current locale. For compound variables + and for types, the -K option for set can be followed by a comma separated list of sub-fields to sort + on. Each field can be followed by a : and the letter n for numerical sorting and/or r for reverse + sorting. For an plain indexed array the -K option can be followed by :n and :r for numerical or + reverse sorting. + + Prompting. + When used interactively, the shell prompts with the value of PS1 after expanding it for parameter + expansion, command substitution, and arithmetic substitution, before reading a command. In addi‐ + tion, each single ! in the prompt is replaced by the command number. A !! is required to place ! + in the prompt. If at any time a new-line is typed and further input is needed to complete a com‐ + mand, then the secondary prompt (i.e., the value of PS2) is issued. + + Conditional Expressions. + A conditional expression is used with the [[ compound command to test attributes of files and to + compare strings. Field splitting and file name generation are not performed on the words between [[ + and ]]. Each expression can be constructed from one or more of the following unary or binary ex‐ + pressions: + string True, if string is not null. + -a file + Same as -e below. This is obsolete. + -b file + True, if file exists and is a block special file. + -c file + True, if file exists and is a character special file. + -d file + True, if file exists and is a directory. + -e file + True, if file exists. + -f file + True, if file exists and is an ordinary file. + -g file + True, if file exists and it has its setgid bit set. + -k file + True, if file exists and it has its sticky bit set. + -n string + True, if length of string is non-zero. + -o ?option + True, if option named option is a valid option name. + -o option + True, if option named option is on. + -p file + True, if file exists and is a fifo special file or a pipe. + -r file + True, if file exists and is readable by current process. + -s file + True, if file exists and has size greater than zero. + -t fildes + True, if file descriptor number fildes is open and associated with a terminal device. + -u file + True, if file exists and it has its setuid bit set. + -v name + True, if variable name is a valid variable name and is set. + -w file + True, if file exists and is writable by current process. + -x file + True, if file exists and is executable by current process. If file exists and is a direc‐ + tory, then true if the current process has permission to search in the directory. + -z string + True, if length of string is zero. + -L file + True, if file exists and is a symbolic link. + -h file + True, if file exists and is a symbolic link. + -N file + True, if file exists and the modification time is greater than the last access time. + -O file + True, if file exists and is owned by the effective user id of this process. + -G file + True, if file exists and its group matches the effective group id of this process. + -R name + True if variable name is a name reference. + -S file + True, if file exists and is a socket. + file1 -nt file2 + True, if file1 exists and file2 does not, or file1 is newer than file2. + file1 -ot file2 + True, if file2 exists and file1 does not, or file1 is older than file2. + file1 -ef file2 + True, if file1 and file2 exist and refer to the same file. + string == pattern + True, if string matches pattern. Any part of pattern can be quoted to cause it to be matched + as a string. With a successful match to a pattern, the .sh.match array variable will contain + the match and sub-pattern matches. + string = pattern + Same as == above, but is obsolete. + string != pattern + True, if string does not match pattern. When the string matches the pattern the .sh.match + array variable will contain the match and sub-pattern matches. + string =∼ ere + True if string matches the pattern ∼(E)ere where ere is an extended regular expression. + string1 < string2 + True, if string1 comes before string2 based on the current locale. + string1 > string2 + True, if string1 comes after string2 based on the current locale. + The following obsolete arithmetic comparisons are also permitted: + exp1 -eq exp2 + True, if exp1 is equal to exp2. + exp1 -ne exp2 + True, if exp1 is not equal to exp2. + exp1 -lt exp2 + True, if exp1 is less than exp2. + exp1 -gt exp2 + True, if exp1 is greater than exp2. + exp1 -le exp2 + True, if exp1 is less than or equal to exp2. + exp1 -ge exp2 + True, if exp1 is greater than or equal to exp2. + + In each of the above expressions, if file is of the form /dev/fd/n, where n is an integer, then the + test is applied to the open file whose descriptor number is n. + + A compound expression can be constructed from these primitives by using any of the following, listed + in decreasing order of precedence. + (expression) + True, if expression is true. Used to group expressions. + ! expression + True if expression is false. + expression1 && expression2 + True, if expression1 and expression2 are both true. + expression1 ⎪⎪ expression2 + True, if either expression1 or expression2 is true. + + Input/Output. + Before a command is executed, its input and output may be redirected using a special notation inter‐ + preted by the shell. The following may appear anywhere in a simple-command or may precede or follow + a command and are not passed on to the invoked command. Command substitution, parameter expansion, + and arithmetic substitution occur before word or digit is used except as noted below. File name + generation occurs only if the shell is interactive and the pattern matches a single file. Field + splitting is not performed. + + In each of the following redirections, if file is of the form /dev/sctp/host/port, + /dev/tcp/host/port, or /dev/udp/host/port, where host is a hostname or host address, and port is a + service given by name or an integer port number, then the redirection attempts to make a tcp, sctp + or udp connection to the corresponding socket. + + No intervening space is allowed between the characters of redirection operators. + + word Use file word as standard output (file descriptor 1). If the file does not exist then + it is created. If the file exists, and the noclobber option is on, this causes an er‐ + ror; otherwise, it is truncated to zero length. + + >|word Same as >, except that it overrides the noclobber option. + + >;word Write output to a temporary file. If the command completes successfully rename it to + word, otherwise, delete the temporary file. >;word cannot be used with the exec(2). + built-in. + + >>word Use file word as standard output. If the file exists, then output is appended to it + (by first seeking to the end-of-file); otherwise, the file is created. + + <>word Open file word for reading and writing as standard input. + + <>;word The same as <>word except that if the command completes successfully, word is trun‐ + cated to the offset at command completion. <>;word cannot be used with the exec(2). + built-in. + + <<[-]word The shell input is read up to a line that is the same as word after any quoting has + been removed, or to an end-of-file. No parameter substitution, command substitution, + arithmetic substitution or file name generation is performed on word. The resulting + document, called a here-document, becomes the standard input. If any character of + word is quoted, then no interpretation is placed upon the characters of the document; + otherwise, parameter expansion, command substitution, and arithmetic substitution oc‐ + cur, \new-line is ignored, and \ must be used to quote the characters \, $, `. If - + is appended to <<, then all leading tabs are stripped from word and from the document. + If # is appended to <<, then leading spaces and tabs will be stripped off the first + line of the document and up to an equivalent indentation will be stripped from the re‐ + maining lines and from word. A tab stop is assumed to occur at every 8 columns for + the purposes of determining the indentation. + + <<&digit. + + <&digit- The file descriptor given by digit is moved to standard input. Similarly for the + standard output using >&digit-. + + <&- The standard input is closed. Similarly for the standard output using >&-. + + <&p The input from the co-process is moved to standard input. + + >&p The output to the co-process is moved to standard output. + + <#((expr)) Evaluate arithmetic expression expr and position file descriptor 0 to the resulting + value bytes from the start of the file. The variables CUR and EOF evaluate to the + current offset and end-of-file offset respectively when evaluating expr. + + >#((offset)) The same as <# except applies to file descriptor 1. + + <#pattern Seeks forward to the beginning of the next line containing pattern. + + <##pattern The same as <# except that the portion of the file that is skipped is copied to stan‐ + dard output. + + If one of the above is preceded by a digit, with no intervening space, then the file descriptor num‐ + ber referred to is that specified by the digit (instead of the default 0 or 1). If one of the + above, other than >&- and the ># and <# forms, is preceded by {varname} with no intervening space, + then a file descriptor number > 10 will be selected by the shell and stored in the variable varname. + If >&- or the any of the ># and <# forms is preceded by {varname} the value of varname defines the + file descriptor to close or position. For example: + + ... 2>&1 + + means file descriptor 2 is to be opened for writing as a duplicate of file descriptor 1 and + + exec {n}fname 2>&1 + + first associates file descriptor 1 with file fname. It then associates file descriptor 2 with the + file associated with file descriptor 1 (i.e. fname). If the order of redirections were reversed, + file descriptor 2 would be associated with the terminal (assuming file descriptor 1 had been) and + then file descriptor 1 would be associated with file fname. + + If a command is followed by & and job control is not active, then the default standard input for the + command is the empty file /dev/null. Otherwise, the environment for the execution of a command con‐ + tains the file descriptors of the invoking shell as modified by input/output specifications. + + Environment. + The environment (see environ(7)) is a list of name-value pairs that is passed to an executed program + in the same way as a normal argument list. The names must be identifiers and the values are charac‐ + ter strings. The shell interacts with the environment in several ways. On invocation, the shell + scans the environment and creates a variable for each name found, giving it the corresponding value + and attributes and marking it export. Executed commands inherit the environment. If the user modi‐ + fies the values of these variables or creates new ones, using the export or typeset -x commands, + they become part of the environment. The environment seen by any executed command is thus composed + of any name-value pairs originally inherited by the shell, whose values may be modified by the cur‐ + rent shell, plus any additions which must be noted in export or typeset -x commands. + + The environment for any simple-command or function may be augmented by prefixing it with one or more + variable assignments. A variable assignment argument is a word of the form identifier=value. Thus: + + TERM=450 cmd args and + (export TERM; TERM=450; cmd args) + + are equivalent (as far as the above execution of cmd is concerned except for special built-in com‐ + mands listed below - those that are preceded with a dagger). + + If the obsolete -k option is set, all variable assignment arguments are placed in the environment, + even if they occur after the command name. The following first prints a=b c and then c: + + echo a=b c + set -k + echo a=b c + This feature is intended for use with scripts written for early versions of the shell and its use in + new scripts is strongly discouraged. It is likely to disappear someday. + + Functions. + For historical reasons, there are two ways to define functions, the name() syntax and the function + name syntax, described in the Commands section above. Shell functions are read in and stored inter‐ + nally. Alias names are resolved when the function is read. Functions are executed like commands + with the arguments passed as positional parameters. (See Execution below.) + + Functions defined by the function name syntax and called by name execute in the same process as the + caller and share all files and present working directory with the caller. Traps caught by the + caller are reset to their default action inside the function. A trap condition that is not caught + or ignored by the function causes the function to terminate and the condition to be passed on to the + caller. A trap on EXIT set inside a function is executed in the environment of the caller after the + function completes. Ordinarily, variables are shared between the calling program and the function. + However, the typeset special built-in command used within a function defines local variables whose + scope includes the current function. They can be passed to functions that they call in the variable + assignment list that precedes the call or as arguments passed as name references. Errors within + functions return control to the caller. + + Functions defined with the name() syntax and functions defined with the function name syntax that + are invoked with the . special built-in are executed in the caller's environment and share all + variables and traps with the caller. Errors within these function executions cause the script that + contains them to abort. + + The special built-in command return is used to return from function calls. + + Function names can be listed with the -f or +f option of the typeset special built-in command. The + text of functions, when available, will also be listed with -f. Functions can be undefined with the + -f option of the unset special built-in command. + + Ordinarily, functions are unset when the shell executes a shell script. Functions that need to be + defined across separate invocations of the shell should be placed in a directory and the FPATH vari‐ + able should contain the name of this directory. They may also be specified in the ENV file. + + Discipline Functions. + Each variable can have zero or more discipline functions associated with it. The shell initially + understands the discipline names get, set, append, and unset but can be added when defining new + types. On most systems others can be added at run time via the C programming interface extension + provided by the builtin built-in utility. If the get discipline is defined for a variable, it is + invoked whenever the given variable is referenced. If the variable .sh.value is assigned a value + inside the discipline function, the referenced variable will evaluate to this value instead. If the + set discipline is defined for a variable, it is invoked whenever the given variable is assigned a + value. If the append discipline is defined for a variable, it is invoked whenever a value is ap‐ + pended to the given variable. The variable .sh.value is given the value of the variable before in‐ + voking the discipline, and the variable will be assigned the value of .sh.value after the discipline + completes. If .sh.value is unset inside the discipline, then that value is unchanged. If the unset + discipline is defined for a variable, it is invoked whenever the given variable is unset. The vari‐ + able will not be unset unless it is unset explicitly from within this discipline function. + + The variable .sh.name contains the name of the variable for which the discipline function is called, + .sh.subscript is the subscript of the variable, and .sh.value will contain the value being assigned + inside the set discipline function. The variable _ is a reference to the variable including the + subscript if any. For the set discipline, changing .sh.value will change the value that gets as‐ + signed. Finally, the expansion ${var.name}, when name is the name of a discipline, and there is no + variable of this name, is equivalent to the command substitution ${ var.name;}. + + Name Spaces. + Commands and functions that are executed as part of the list of a namespace command that modify + variables or create new ones, create a new variable whose name is the name of the name space as + given by identifier preceded by .. When a variable whose name is name is referenced, it is first + searched for using .identifier.name. Similarly, a function defined by a command in the namespace + list is created using the name space name preceded by a .. + + When the list of a namespace command contains a namespace command, the names of variables and func‐ + tions that are created consist of the variable or function name preceded by the list of identifiers + each preceded by .. + + Outside of a name space, a variable or function created inside a name space can be referenced by + preceding it with the name space name. + + By default, variables staring with .sh are in the sh name space. + + Type Variables. + Typed variables provide a way to create data structure and objects. A type can be defined either by + a shared library, by the enum built-in command described below, or by using the new -T option of the + typeset built-in command. With the -T option of typeset, the type name, specified as an option ar‐ + gument to -T, is set with a compound variable assignment that defines the type. Function defini‐ + tions can appear inside the compound variable assignment and these become discipline functions for + this type and can be invoked or redefined by each instance of the type. The function name create is + treated specially. It is invoked for each instance of the type that is created but is not inherited + and cannot be redefined for each instance. + + When a type is defined a special built-in command of that name is added. These built-ins are decla‐ + ration commands and follow the same expansion rules as all the special built-in commands defined be‐ + low that are preceded by ††. These commands can subsequently be used inside further type defini‐ + tions. The man page for these commands can be generated by using the --man option or any of the + other -- options described with getopts. The -r, -a, -A, -h, and -S options of typeset are permit‐ + ted with each of these new built-ins. + + An instance of a type is created by invoking the type name followed by one or more instance names. + Each instance of the type is initialized with a copy of the sub-variables except for sub-variables + that are defined with the -S option. Variables defined with the -S are shared by all instances of + the type. Each instance can change the value of any sub-variable and can also define new discipline + functions of the same names as those defined by the type definition as well as any standard disci‐ + pline names. No additional sub-variables can be defined for any instance. + + When defining a type, if the value of a sub-variable is not set and the -r attribute is specified, + it causes the sub-variable to be a required sub-variable. Whenever an instance of a type is cre‐ + ated, all required sub-variables must be specified. These sub-variables become readonly in each in‐ + stance. + + When unset is invoked on a sub-variable within a type, and the -r attribute has not been specified + for this field, the value is reset to the default value associative with the type. Invoking unset + on a type instance not contained within another type deletes all sub-variables and the variable it‐ + self. + + A type definition can be derived from another type definition by defining the first sub-variable + name as _ and defining its type as the base type. Any remaining definitions will be additions and + modifications that apply to the new type. If the new type name is the same as that of the base + type, the type will be replaced and the original type will no longer be accessible. + + The typeset command with the -T and no option argument or operands will write all the type defini‐ + tions to standard output in a form that can be read in to create all the types. + + Jobs. + If the monitor option of the set command is turned on, an interactive shell associates a job with + each pipeline. It keeps a table of current jobs, printed by the jobs command, and assigns them + small integer numbers. When a job is started asynchronously with &, the shell prints a line which + looks like: + + [1] 1234 + + indicating that the job which was started asynchronously was job number 1 and had one (top-level) + process, whose process id was 1234. + + This paragraph and the next require features that are not in all versions of UNIX and may not apply. + If you are running a job and wish to do something else you may hit the key ^Z (control-Z) which + sends a STOP signal to the current job. The shell will then normally indicate that the job has been + `Stopped', and print another prompt. You can then manipulate the state of this job, putting it in + the background with the bg command, or run some other commands and then eventually bring the job + back into the foreground with the foreground command fg. A ^Z takes effect immediately and is like + an interrupt in that pending output and unread input are discarded when it is typed. + + A job being run in the background will stop if it tries to read from the terminal. Background jobs + are normally allowed to produce output, but this can be disabled by giving the command stty tostop. + If you set this tty option, then background jobs will stop when they try to produce output like they + do when they try to read input. + + A job pool is a collection of jobs started with list & associated with a name. + + There are several ways to refer to jobs in the shell. A job can be referred to by the process id of + any process of the job or by one of the following: + %number + The job with the given number. + pool All the jobs in the job pool named by pool. + pool.number + The job number number in the job pool named by pool. + %string + Any job whose command line begins with string. + %?string + Any job whose command line contains string. + %% Current job. + %+ Equivalent to %%. + %- Previous job. In addition, unless noted otherwise, wherever a job can be specified, the name + of a background job pool can be used to represent all the jobs in that pool. + + The shell learns immediately whenever a process changes state. It normally informs you whenever a + job becomes blocked so that no further progress is possible, but only just before it prints a + prompt. This is done so that it does not otherwise disturb your work. The notify option of the set + command causes the shell to print these job change messages as soon as they occur. + + When the monitor option is on, each background job that completes triggers any trap set for CHLD. + + When you try to leave the shell while jobs are running or stopped, you will be warned that `You have + stopped(running) jobs.' You may use the jobs command to see what they are. If you immediately try + to exit again, the shell will not warn you a second time, and the stopped jobs will be terminated. + When a login shell receives a HUP signal, it sends a HUP signal to each job that has not been dis‐ + owned with the disown built-in command described below. + + Signals. + The INT and QUIT signals for an invoked command are ignored if the command is followed by & and the + monitor option is active. Otherwise, signals have the values inherited by the shell from its parent + (but see also the trap built-in command below). + + Execution. + Each time a command is read, the above substitutions are carried out. If the command name matches + one of the Special Built-in Commands listed below, it is executed within the current shell process. + Next, the command name is checked to see if it matches a user defined function. If it does, the po‐ + sitional parameters are saved and then reset to the arguments of the function call. A function is + also executed in the current shell process. When the function completes or issues a return, the po‐ + sitional parameter list is restored. For functions defined with the function name syntax, any trap + set on EXIT within the function is executed. The exit value of a function is the value of the last + command executed. If a command name is not a special built-in command or a user defined function, + but it is one of the built-in commands listed below, it is executed in the current shell process. + + The shell variables PATH followed by the variable FPATH defines the list of directories to search + for the command name. Alternative directory names are separated by a colon (:). The default path + is equal to getconf PATH output. The current directory can be specified by two or more adjacent + colons, or by a colon at the beginning or end of the path list. If the command name contains a /, + then the search path is not used. Otherwise, each directory in the list of directories defined by + PATH and FPATH is checked in order. If the directory being searched is contained in FPATH and con‐ + tains a file whose name matches the command being searched, then this file is loaded into the cur‐ + rent shell environment as if it were the argument to the . command except that only preset aliases + are expanded, and a function of the given name is executed as described above. + + If this directory is not in FPATH the shell first determines whether there is a built-in version of + a command corresponding to a given pathname and if so it is invoked in the current process. If no + built-in is found, the shell checks for a file named .paths in this directory. If found and there + is a line of the form FPATH=path where path names an existing directory then that directory is + searched immediately after the current directory as if it were found in the FPATH variable. If path + does not begin with /, it is checked for relative to the directory being searched. + + The .paths file is then checked for a line of the form PLUGIN_LIB=libname [ : libname ] ... . Each + library named by libname will be searched for as if it were an option argument to builtin -f, and if + it contains a built-in of the specified name this will be executed instead of a command by this + name. Any built-in loaded from a library found this way will be associated with the directory con‐ + taining the .paths file so it will only execute if not found in an earlier directory. + + Finally, the directory will be checked for a file of the given name. If the file has execute per‐ + mission but is not an a.out file, it is assumed to be a file containing shell commands. A separate + shell is spawned to read it. All non-exported variables are removed in this case. If the shell + command file doesn't have read permission, or if the setuid and/or setgid bits are set on the file, + then the shell executes an agent whose job it is to set up the permissions and execute the shell + with the shell command file passed down as an open file. If the .paths contains a line of the form + name=value in the first or second line, then the environment variable name is modified by prepending + the directory specified by value to the directory list. If value is not an absolute directory, then + it specifies a directory relative to the directory that the executable was found. If the environ‐ + ment variable name does not already exist it will be added to the environment list for the specified + command. A parenthesized command is executed in a sub-shell without removing non-exported vari‐ + ables. + + Command Re-entry. + The text of the last HISTSIZE (default 512) commands entered from a terminal device is saved in a + history file. The file $HOME/.sh_history is used if the HISTFILE variable is not set or if the file + it names is not writable. A shell can access the commands of all interactive shells which use the + same named HISTFILE. The built-in command hist is used to list or edit a portion of this file. The + portion of the file to be edited or listed can be selected by number or by giving the first charac‐ + ter or characters of the command. A single command or range of commands can be specified. If you + do not specify an editor program as an argument to hist then the value of the variable HISTEDIT is + used. If HISTEDIT is unset, the obsolete variable FCEDIT is used. If FCEDIT is not defined, then + /bin/ed is used. The edited command(s) is printed and re-executed upon leaving the editor unless + you quit without writing. The -s option (and in obsolete versions, the editor name -) is used to + skip the editing phase and to re-execute the command. In this case a substitution parameter of the + form old=new can be used to modify the command before execution. For example, with the preset alias + r, which is aliased to ′hist -s′, typing `r bad=good c' will re-execute the most recent command + which starts with the letter c, replacing the first occurrence of the string bad with the string + good. + + In-line Editing Options. + Normally, each command line entered from a terminal device is simply typed followed by a new-line + (`RETURN' or `LINE FEED'). If either the emacs, gmacs, or vi option is active, the user can edit + the command line. To be in either of these edit modes set the corresponding option. An editing op‐ + tion is automatically selected each time the VISUAL or EDITOR variable is assigned a value ending in + either of these option names. + + The editing features require that the user's terminal accept `RETURN' as carriage return without + line feed and that a space (` ') must overwrite the current character on the screen. + + Unless the multiline option is on, the editing modes implement a concept where the user is looking + through a window at the current line. The window width is the value of COLUMNS if it is defined, + otherwise 80. If the window width is too small to display the prompt and leave at least 8 columns + to enter input, the prompt is truncated from the left. If the line is longer than the window width + minus two, a mark is displayed at the end of the window to notify the user. As the cursor moves and + reaches the window boundaries the window will be centered about the cursor. The mark is a > (<, *) + if the line extends on the right (left, both) side(s) of the window. + + The search commands in each edit mode provide access to the history file. Only strings are matched, + not patterns, although a leading ^ in the string restricts the match to begin at the first character + in the line. + + Each of the edit modes has an operation to list the files or commands that match a partially entered + word. When applied to the first word on the line, or the first word after a ;, ⎪, &, or (, and the + word does not begin with ∼ or contain a /, the list of aliases, functions, and executable commands + defined by the PATH variable that could match the partial word is displayed. Otherwise, the list of + files that match the given word is displayed. If the partially entered word does not contain any + file expansion characters, a * is appended before generating these lists. After displaying the gen‐ + erated list, the input line is redrawn. These operations are called command name listing and file + name listing, respectively. There are additional operations, referred to as command name completion + and file name completion, which compute the list of matching commands or files, but instead of + printing the list, replace the current word with a complete or partial match. For file name comple‐ + tion, if the match is unique, a / is appended if the file is a directory and a space is appended if + the file is not a directory. Otherwise, the longest common prefix for all the matching files re‐ + places the word. For command name completion, only the portion of the file names after the last / + are used to find the longest command prefix. If only a single name matches this prefix, then the + word is replaced with the command name followed by a space. When using a tab for completion that + does not yield a unique match, a subsequent tab will provide a numbered list of matching alterna‐ + tives. A specific selection can be made by entering the selection number followed by a tab. + + Key Bindings. + The KEYBD trap can be used to intercept keys as they are typed and change the characters that are + actually seen by the shell. This trap is executed after each character (or sequence of characters + when the first character is ESC) is entered while reading from a terminal. The variable .sh.edchar + contains the character or character sequence which generated the trap. Changing the value of + .sh.edchar in the trap action causes the shell to behave as if the new value were entered from the + keyboard rather than the original value. + + The variable .sh.edcol is set to the input column number of the cursor at the time of the input. + The variable .sh.edmode is set to ESC when in vi insert mode (see below) and is null otherwise. By + prepending ${.sh.editmode} to a value assigned to .sh.edchar it will cause the shell to change to + control mode if it is not already in this mode. + + This trap is not invoked for characters entered as arguments to editing directives, or while reading + input for a character search. + + Emacs Editing Mode. + This mode is entered by enabling either the emacs or gmacs option. The only difference between + these two modes is the way they handle ^T. To edit, the user moves the cursor to the point needing + correction and then inserts or deletes characters or words as needed. All the editing commands are + control characters or escape sequences. The notation for control characters is caret (^) followed + by the character. For example, ^F is the notation for control F. This is entered by depressing `f' + while holding down the `CTRL' (control) key. The `SHIFT' key is not depressed. (The notation ^? + indicates the DEL (delete) key.) + + The notation for escape sequences is M- followed by a character. For example, M-f (pronounced Meta + f) is entered by depressing ESC (ascii 033) followed by `f'. (M-F would be the notation for ESC + followed by `SHIFT' (capital) `F'.) + + All edit commands operate from any place on the line (not just at the beginning). Neither the `RE‐ + TURN' nor the `LINE FEED' key is entered after edit commands except when noted. + + ^F Move cursor forward (right) one character. + M-[C Move cursor forward (right) one character. + M-f Move cursor forward one word. (The emacs editor's idea of a word is a string of charac‐ + ters consisting of only letters, digits and underscores.) + ^B Move cursor backward (left) one character. + M-[D Move cursor backward (left) one character. + M-b Move cursor backward one word. + ^A Move cursor to start of line. + M-[H Move cursor to start of line. + ^E Move cursor to end of line. + M-[Y Move cursor to end of line. + ^]char Move cursor forward to character char on current line. + M-^]char Move cursor backward to character char on current line. + ^X^X Interchange the cursor and mark. + erase (User defined erase character as defined by the stty(1) command, usually ^H or #.) Delete + previous character. + lnext (User defined literal next character as defined by the stty(1) command, or ^V if not de‐ + fined.) Removes the next character's editing features (if any). + ^D Delete current character. + M-d Delete current word. + M-^H (Meta-backspace) Delete previous word. + M-h Delete previous word. + M-^? (Meta-DEL) Delete previous word (if your interrupt character is ^? (DEL, the default) + then this command will not work). + ^T Transpose current character with previous character and advance the cursor in emacs mode. + Transpose two previous characters in gmacs mode. + ^C Capitalize current character. + M-c Capitalize current word. + M-l Change the current word to lower case. + ^K Delete from the cursor to the end of the line. If preceded by a numerical parameter whose + value is less than the current cursor position, then delete from given position up to the + cursor. If preceded by a numerical parameter whose value is greater than the current cur‐ + sor position, then delete from cursor up to given cursor position. + ^W Kill from the cursor to the mark. + M-p Push the region from the cursor to the mark on the stack. + kill (User defined kill character as defined by the stty command, usually ^G or @.) Kill the + entire current line. If two kill characters are entered in succession, all kill charac‐ + ters from then on cause a line feed (useful when using paper terminals). + ^Y Restore last item removed from line. (Yank item back to the line.) + ^L Line feed and print current line. + M-^L Clear the screen. + ^@ (Null character) Set mark. + M-space (Meta space) Set mark. + ^J (New line) Execute the current line. + ^M (Return) Execute the current line. + eof End-of-file character, normally ^D, is processed as an End-of-file only if the current + line is null. + ^P Fetch previous command. Each time ^P is entered the previous command back in time is ac‐ + cessed. Moves back one line when not on the first line of a multi-line command. + M-[A If the cursor is at the end of the line, it is equivalent to ^R with string set to the + contents of the current line. Otherwise, it is equivalent to ^P. + M-< Fetch the least recent (oldest) history line. + M-> Fetch the most recent (youngest) history line. + ^N Fetch next command line. Each time ^N is entered the next command line forward in time is + accessed. + M-[B Equivalent to ^N. + ^Rstring Reverse search history for a previous command line containing string. If a parameter of + zero is given, the search is forward. String is terminated by a `RETURN' or `NEW LINE'. + If string is preceded by a ^, the matched line must begin with string. If string is omit‐ + ted, then the next command line containing the most recent string is accessed. In this + case a parameter of zero reverses the direction of the search. + ^O Operate - Execute the current line and fetch the next line relative to current line from + the history file. + M-digits (Escape) Define numeric parameter, the digits are taken as a parameter to the next com‐ + mand. The commands that accept a parameter are ^F, ^B, erase, ^C, ^D, ^K, ^R, ^P, ^N, ^], + M-., M-^], M-_, M-=, M-b, M-c, M-d, M-f, M-h, M-l and M-^H. + M-letter Soft-key - Your alias list is searched for an alias by the name _letter and if an alias of + this name is defined, its value will be inserted on the input queue. The letter must not + be one of the above meta-functions. + M-[letter Soft-key - Your alias list is searched for an alias by the name __letter and if an alias + of this name is defined, its value will be inserted on the input queue. This can be used + to program function keys on many terminals. + M-. The last word of the previous command is inserted on the line. If preceded by a numeric + parameter, the value of this parameter determines which word to insert rather than the + last word. + M-_ Same as M-.. + M-* Attempt file name generation on the current word. An asterisk is appended if the word + doesn't match any file or contain any special pattern characters. + M-ESC Command or file name completion as described above. + ^I tab Attempts command or file name completion as described above. If a partial completion oc‐ + curs, repeating this will behave as if M-= were entered. If no match is found or entered + after space, a tab is inserted. + M-= If not preceded by a numeric parameter, it generates the list of matching commands or file + names as described above. Otherwise, the word under the cursor is replaced by the item + corresponding to the value of the numeric parameter from the most recently generated com‐ + mand or file list. If the cursor is not on a word, it is inserted instead. + ^U Multiply parameter of next command by 4. + \ Escape next character. Editing characters, the user's erase, kill and interrupt (normally + ^?) characters may be entered in a command line or in a search string if preceded by a \. + The \ removes the next character's editing features (if any). + M-^V Display version of the shell. + M-# If the line does not begin with a #, a # is inserted at the beginning of the line and af‐ + ter each new-line, and the line is entered. This causes a comment to be inserted in the + history file. If the line begins with a #, the # is deleted and one # after each new-line + is also deleted. + + Vi Editing Mode. + There are two typing modes. Initially, when you enter a command you are in the input mode. To + edit, the user enters control mode by typing ESC (033) and moves the cursor to the point needing + correction and then inserts or deletes characters or words as needed. Most control commands accept + an optional repeat count prior to the command. + + When in vi mode on most systems, canonical processing is initially enabled and the command will be + echoed again if the speed is 1200 baud or greater and it contains any control characters or less + than one second has elapsed since the prompt was printed. The ESC character terminates canonical + processing for the remainder of the command and the user can then modify the command line. This + scheme has the advantages of canonical processing with the type-ahead echoing of raw mode. + + If the option viraw is also set, the terminal will always have canonical processing disabled. This + mode is implicit for systems that do not support two alternate end of line delimiters, and may be + helpful for certain terminals. + + Input Edit Commands + By default the editor is in input mode. + erase (User defined erase character as defined by the stty command, usually ^H or #.) + Delete previous character. + ^W Delete the previous blank separated word. + eof As the first character of the line causes the shell to terminate unless the ig‐ + noreeof option is set. Otherwise this character is ignored. + lnext (User defined literal next character as defined by the stty(1) or ^V if not de‐ + fined.) Removes the next character's editing features (if any). + \ Escape the next erase or kill character. + ^I tab Attempts command or file name completion as described above and returns to input + mode. If a partial completion occurs, repeating this will behave as if = were en‐ + tered from control mode. If no match is found or entered after space, a tab is in‐ + serted. + Motion Edit Commands + These commands will move the cursor. + [count]l Cursor forward (right) one character. + [count][C Cursor forward (right) one character. + [count]w Cursor forward one alpha-numeric word. + [count]W Cursor to the beginning of the next word that follows a blank. + [count]e Cursor to end of word. + [count]E Cursor to end of the current blank delimited word. + [count]h Cursor backward (left) one character. + [count][D Cursor backward (left) one character. + [count]b Cursor backward one word. + [count]B Cursor to preceding blank separated word. + [count]⎪ Cursor to column count. + [count]fc Find the next character c in the current line. + [count]Fc Find the previous character c in the current line. + [count]tc Equivalent to f followed by h. + [count]Tc Equivalent to F followed by l. + [count]; Repeats count times, the last single character find command, f, F, t, or T. + [count], Reverses the last single character find command count times. + 0 Cursor to start of line. + ^ Cursor to start of line. + [H Cursor to first non-blank character in line. + $ Cursor to end of line. + [Y Cursor to end of line. + % Moves to balancing (, ), {, }, [, or ]. If cursor is not on one of the above char‐ + acters, the remainder of the line is searched for the first occurrence of one of + the above characters first. + Search Edit Commands + These commands access your command history. + [count]k Fetch previous command. Each time k is entered the previous command back in time + is accessed. + [count]- Equivalent to k. + [count][A If cursor is at the end of the line it is equivalent to / with string^set to the + contents of the current line. Otherwise, it is equivalent to k. + [count]j Fetch next command. Each time j is entered the next command forward in time is ac‐ + cessed. + [count]+ Equivalent to j. + [count][B Equivalent to j. + [count]G The command number count is fetched. The default is the least recent history com‐ + mand. + /string Search backward through history for a previous command containing string. String + is terminated by a `RETURN' or `NEW LINE'. If string is preceded by a ^, the + matched line must begin with string. If string is null, the previous string will + be used. + ?string Same as / except that search will be in the forward direction. + n Search for next match of the last pattern to / or ? commands. + N Search for next match of the last pattern to / or ?, but in reverse direction. + Text Modification Edit Commands + These commands will modify the line. + a Enter input mode and enter text after the current character. + A Append text to the end of the line. Equivalent to $a. + [count]cmotion + c[count]motion + Delete current character through the character that motion would move the cursor to + and enter input mode. If motion is c, the entire line will be deleted and input + mode entered. + C Delete the current character through the end of line and enter input mode. Equiva‐ + lent to c$. + S Equivalent to cc. + [count]s Replace characters under the cursor in input mode. + D Delete the current character through the end of line. Equivalent to d$. + [count]dmotion + d[count]motion + Delete current character through the character that motion would move to. If mo‐ + tion is d , the entire line will be deleted. + i Enter input mode and insert text before the current character. + I Insert text before the beginning of the line. Equivalent to 0i. + [count]P Place the previous text modification before the cursor. + [count]p Place the previous text modification after the cursor. + R Enter input mode and replace characters on the screen with characters you type + overlay fashion. + [count]rc Replace the count character(s) starting at the current cursor position with c, and + advance the cursor. + [count]x Delete current character. + [count]X Delete preceding character. + [count]. Repeat the previous text modification command. + [count]∼ Invert the case of the count character(s) starting at the current cursor position + and advance the cursor. + [count]_ Causes the count word of the previous command to be appended and input mode en‐ + tered. The last word is used if count is omitted. + * Causes an * to be appended to the current word and file name generation attempted. + If no match is found, it rings the bell. Otherwise, the word is replaced by the + matching pattern and input mode is entered. + \ Command or file name completion as described above. + Other Edit Commands + Miscellaneous commands. + [count]ymotion + y[count]motion + Yank current character through character that motion would move the cursor to and + puts them into the delete buffer. The text and cursor are unchanged. + yy Yanks the entire line. + Y Yanks from current position to end of line. Equivalent to y$. + u Undo the last text modifying command. + U Undo all the text modifying commands performed on the line. + [count]v Returns the command hist -e ${VISUAL:-${EDITOR:-vi}} count in the input buffer. If + count is omitted, then the current line is used. + ^L Line feed and print current line. Has effect only in control mode. + ^J (New line) Execute the current line, regardless of mode. + ^M (Return) Execute the current line, regardless of mode. + # If the first character of the command is a #, then this command deletes this # and + each # that follows a newline. Otherwise, sends the line after inserting a # in + front of each line in the command. Useful for causing the current line to be in‐ + serted in the history as a comment and uncommenting previously commented commands + in the history file. + [count]= If count is not specified, it generates the list of matching commands or file names + as described above. Otherwise, the word under the cursor is replaced by the count + item from the most recently generated command or file list. If the cursor is not + on a word, it is inserted instead. + @letter Your alias list is searched for an alias by the name _letter and if an alias of + this name is defined, its value will be inserted on the input queue for processing. + ^V Display version of the shell. + + Programmable Completion. + By default, hitting the tab key causes the current word to be matched against files starting with + the characters you typed and adding as many characters that provide a unique match. If the matching + prefix is not unique hitting tab again will output a numbered list with the choices and entering + number tab will replace the current word with that selection. + + Programmable completion allows you to control how words are expanded when you enter the tab key for + one or more specified commands. The complete built-in command allows you to specify how to complete + the current word of the specified command. + + Built-in Commands. + The following simple-commands are executed in the shell process. Input/Output redirection is per‐ + mitted. Unless otherwise indicated, the output is written on file descriptor 1 and the exit status, + when there is no syntax error, is zero. Except for :, true, false, echo, newgrp, and login, all + built-in commands accept -- to indicate end of options. They also interpret the option --man as a + request to display the man page onto standard error and -? as a help request which prints a usage + message on standard error. Commands that are preceded by one or two † symbols are special built-in + commands and are treated specially in the following ways: + 1. Variable assignment lists preceding the command remain in effect when the command completes. + 2. I/O redirections are processed after variable assignments. + 3. Errors cause a script that contains them to abort. + 4. They are not valid function names. + 5. Words following a command preceded by †† that are in the format of a variable assignment are + expanded with the same rules as a variable assignment. This means that tilde substitution is + performed after the = sign and field splitting and file name generation are not performed. + These are called declaration built-ins. + + † : [ arg ... ] + The command only expands parameters. + + † . name [ arg ... ] + If name is a function defined with the function name reserved word syntax, the function is + executed in the current environment (as if it had been defined with the name() syntax.) Oth‐ + erwise if name refers to a file, the file is read in its entirety and the commands are exe‐ + cuted in the current shell environment. The search path specified by PATH is used to find + the directory containing the file. If any arguments arg are given, they become the posi‐ + tional parameters while processing the . command and the original positional parameters are + restored upon completion. Otherwise the positional parameters are unchanged. The exit sta‐ + tus is the exit status of the last command executed. + + †† alias [ -ptx ] [ name[ =value ] ] ... + alias with no arguments prints the list of aliases in the form name=value on standard output. + The -p option causes the word alias to be inserted before each one. When one or more argu‐ + ments are given, an alias is defined for each name whose value is given. A trailing space in + value causes the next word to be checked for alias substitution. The obsolete -t option is + used to set and list tracked aliases. The value of a tracked alias is the full pathname cor‐ + responding to the given name. The value becomes undefined when the value of PATH is reset + but the alias remains tracked. Without the -t option, for each name in the argument list for + which no value is given, the name and value of the alias is printed. The obsolete -x option + has no effect. The exit status is non-zero if a name is given, but no value, and no alias + has been defined for the name. + + bg [ job... ] + This command is only on systems that support job control. Puts each specified job into the + background. The current job is put in the background if job is not specified. See Jobs for + a description of the format of job. + + † break [ n ] + Exit from the enclosing for, while, until, or select loop, if any. If n is specified, then + break n levels. + + builtin [ -dsp ] [ -f file ] [ name ... ] + If name is not specified, and no -f option is specified, the built-ins are printed on stan‐ + dard output. The -s option prints only the special built-ins. Otherwise, each name repre‐ + sents the pathname whose basename is the name of the built-in. The entry point function name + is determined by prepending b_ to the built-in name. A built-in specified by a pathname will + only be executed when that pathname would be found during the path search. Built-ins found + in libraries loaded via the .paths file will be associate with the pathname of the directory + containing the .paths file. + The ISO C/C++ prototype is b_mycommand(int argc, char *argv[], void *context) for the builtin + command mycommand where argv is array an of argc elements and context is an optional pointer + to a Shell_t structure as described in . + Special built-ins cannot be bound to a pathname or deleted. The -d option deletes each of + the given built-ins. On systems that support dynamic loading, the -f option names a shared + library containing the code for built-ins. The shared library prefix and/or suffix, which + depend on the system, can be omitted. Once a library is loaded, its symbols become available + for subsequent invocations of builtin. Multiple libraries can be specified with separate in‐ + vocations of the builtin command. Libraries are searched in the reverse order in which they + are specified. When a library is loaded, it looks for a function in the library whose name + is lib_init() and invokes this function with an argument of 0. + The -p causes the output to be in a form of builtin commands that can be used as input to the + shell to recreate the current set of builtins. + + cd [ -LP ] [ arg ] + cd [ -LP ] old new + This command can be in either of two forms. In the first form it changes the current direc‐ + tory to arg. If arg is - the directory is changed to the previous directory. The shell + variable HOME is the default arg. The variable PWD is set to the current directory. The + shell variable CDPATH defines the search path for the directory containing arg. Alternative + directory names are separated by a colon (:). The default path is (specifying the + current directory). Note that the current directory is specified by a null path name, which + can appear immediately after the equal sign or between the colon delimiters anywhere else in + the path list. If arg begins with a / then the search path is not used. Otherwise, each di‐ + rectory in the path is searched for arg. + The second form of cd substitutes the string new for the string old in the current directory + name, PWD, and tries to change to this new directory. + By default, symbolic link names are treated literally when finding the directory name. This + is equivalent to the -L option. The -P option causes symbolic links to be resolved when de‐ + termining the directory. The last instance of -L or -P on the command line determines which + method is used. + The cd command may not be executed by rksh. + + command [ -pvxV ] name [ arg ... ] + Without the -v or -V options, command executes name with the arguments given by arg. The -p + option causes a default path to be searched rather than the one defined by the value of PATH. + Functions will not be searched for when finding name. In addition, if name refers to a spe‐ + cial built-in, none of the special properties associated with the leading daggers will be + honored. (For example, the predefined alias redirect=′command exec′ prevents a script from + terminating when an invalid redirection is given.) With the -x option, if command execution + would result in a failure because there are too many arguments, errno E2BIG, the shell will + invoke command name multiple times with a subset of the arguments on each invocation. Argu‐ + ments that occur prior to the first word that expands to multiple arguments and after the + last word that expands to multiple arguments will be passed on each invocation. The exit + status will be the maximum invocation exit status. With the -v option, command is equivalent + to the built-in whence command described below. The -V option causes command to act like + whence -v. + + † continue [ n ] + Resume the next iteration of the enclosing for, while, until, or select loop. If n is speci‐ + fied, then resume at the n-th enclosing loop. + + disown [ job... ] + Causes the shell not to send a HUP signal to each given job, or all active jobs if job is + omitted, when a login shell terminates. + + echo [ -n -e ] [ arg ... ] + echo builtin prints all of its arguments separated by space and terminated by new-line. -n + will skip putting a newline character at the end of output. If -e is set, it will enable in‐ + terpreting escape sequences. + + †† enum [ -i ] type[=(value ...) ] + Creates a declaration command named type that is an integer type that allows one of the spec‐ + ified values as enumeration names. If =(value ...) is omitted, then type must be an indexed + array variable with at least two elements and the values are taken from this array variable. + If -i is specified the values are case insensitive. + When an enumeration variable is used in arithmetic expression, its value is the index into + the array that defined it starting from index 0. Enumeration strings can be used in an + arithmetic expression when comparing against an enumeration variable. Also, each non-sub‐ + scripted enumeration variable followed by .name where name is one of the enumeration names + expands to the index corresponding to name. + The enum _Bool is created with values true and false. The predefined alias bool is defined + as _Bool. + + † eval [ arg ... ] + The arguments are read as input to the shell and the resulting command(s) executed. + + † exec [ -c ] [ -a name ] [ arg ... ] + If arg is given, the command specified by the arguments is executed in place of this shell + without creating a new process. The -c option causes the environment to be cleared before + applying variable assignments associated with the exec invocation. The -a option causes name + rather than the first arg, to become argv[0] for the new process. Input/output arguments may + appear and affect the current process. If arg is not given, the effect of this command is to + modify file descriptors as prescribed by the input/output redirection list. In this case, + any file descriptor numbers greater than 2 that are opened with this mechanism are closed + when invoking another program. + + † exit [ n ] + Causes the shell to exit with the exit status specified by n. The value will be the least + significant 8 bits of the specified status. If n is omitted, then the exit status is that of + the last command executed. An end-of-file will also cause the shell to exit except for a + shell which has the ignoreeof option (see set below) turned on. + + †† export [ -p ] [ name[=value] ] ... + If name is not given, the names and values of each variable with the export attribute are + printed with the values quoted in a manner that allows them to be re-input. The export com‐ + mand is the same as typeset -x except that if you use export within a function, no local + variable is created. The -p option causes the word export to be inserted before each one. + Otherwise, the given names are marked for automatic export to the environment of subse‐ + quently-executed commands. + + false Does nothing, and exits 1. Used with until for infinite loops. + + fg [ job... ] + This command is only on systems that support job control. Each job specified is brought to + the foreground and waited for in the specified order. Otherwise, the current job is brought + into the foreground. See Jobs for a description of the format of job. + + getopts [ -a name ] optstring vname [ arg ... ] + Checks arg for legal options. If arg is omitted, the positional parameters are used. An op‐ + tion argument begins with a + or a -. An option not beginning with + or - or the argument -- + ends the options. Options beginning with + are only recognized when optstring begins with a + +. optstring contains the letters that getopts recognizes. If a letter is followed by a :, + that option is expected to have an argument. The options can be separated from the argument + by blanks. The option -? causes getopts to generate a usage message on standard error. The + -a argument can be used to specify the name to use for the usage message, which defaults to + $0. + getopts places the next option letter it finds inside variable vname each time it is invoked. + The option letter will be prepended with a + when arg begins with a +. The index of the next + arg is stored in OPTIND. The option argument, if any, gets stored in OPTARG. + A leading : in optstring causes getopts to store the letter of an invalid option in OPTARG, + and to set vname to ? for an unknown option and to : when a required option argument is + missing. Otherwise, getopts prints an error message. The exit status is non-zero when there + are no more options. + There is no way to specify any of the options :, +, -, ?, [, and ]. The option # can only be + specified as the first option. + + hist [ -e ename ] [ -nlr ] [ first [ last ] ] + hist -s [ old=new ] [ command ] + In the first form, a range of commands from first to last is selected from the last HISTSIZE + commands that were typed at the terminal. The arguments first and last may be specified as a + number or as a string. A string is used to locate the most recent command starting with the + given string. A negative number is used as an offset to the current command number. If the + -l option is selected, the commands are listed on standard output. Otherwise, the editor + program ename is invoked on a file containing these keyboard commands. If ename is not sup‐ + plied, then the value of the variable HISTEDIT is used. If HISTEDIT is not set, then FCEDIT + (default /bin/ed) is used as the editor. When editing is complete, the edited command(s) is + executed if the changes have been saved. If last is not specified, then it will be set to + first. If first is not specified, the default is the previous command for editing and -16 + for listing. The option -r reverses the order of the commands and the option -n suppresses + command numbers when listing. In the second form, command is interpreted as first described + above and defaults to the last command executed. The resulting command is executed after the + optional substitution old=new is performed. + + jobs [ -lnp ] [ job ... ] + Lists information about each given job; or all active jobs if job is omitted. The -l option + lists process ids in addition to the normal information. The -n option only displays jobs + that have stopped or exited since last notified. The -p option causes only the process group + to be listed. See Jobs for a description of the format of job. + + kill [ -s signame ] [ -q n ] job ... + kill [ -n signum ] [ -q n ] job ... + kill -Ll [ sig ... ] + Sends either the TERM (terminate) signal or the specified signal to the specified jobs or + processes. Signals are either given by number with the -n option or by name with the -s op‐ + tion (as given in , stripped of the prefix ``SIG'' with the exception that SIGCLD + is named CHLD). For backward compatibility, the n and s can be omitted and the number or + name placed immediately after the -. If the signal being sent is TERM (terminate) or HUP + (hangup), then the job or process will be sent a CONT (continue) signal if it is stopped. + The argument job can be the process id of a process that is not a member of one of the active + jobs. See Jobs for a description of the format of job. In the third form, kill -l, or kill + -L, if sig is not specified, the signal names are listed. The -l option list only the signal + names. -L options lists each signal name and corresponding number. Otherwise, for each sig + that is a name, the corresponding signal number is listed. For each sig that is a number, + the signal name corresponding to the least significant 8 bits of sig is listed. + On systems that support sigqueue(2) the -q option can be used to send a queued signal with + message number n. Each specified job must be a positive number. On systems that do not sup‐ + port sigqueue(2), a signal is sent without the message number n and the signal will not be + queued. If the signal cannot be queued because of a return of EAGAIN, the exit status will + be 2. + + let arg ... + Each arg is a separate arithmetic expression to be evaluated. let only recognizes octal con‐ + stants starting with 0 when the set option letoctal is on. See Arithmetic Evaluation above, + for a description of arithmetic expression evaluation. + The exit status is 0 if the value of the last expression is non-zero, and 1 otherwise. + + † newgrp [ arg ... ] + Equivalent to exec /bin/newgrp arg .... + + print [ -CRenprsv ] [ -u unit] [ -f format ] [ arg ... ] + With no options or with option - or --, each arg is printed on standard output. The -f op‐ + tion causes the arguments to be printed as described by printf. In this case, any e, n, r, R + options are ignored. Otherwise, unless the -C, -R, -r, or -v are specified, the following + escape conventions will be applied: + \a The alert character (ascii 07). + \b The backspace character (ascii 010). + \c Causes print to end without processing more arguments and not adding a new-line. + \f The formfeed character (ascii 014). + \n The new-line character (ascii 012). + \r The carriage return character (ascii 015). + \t The tab character (ascii 011). + \v The vertical tab character (ascii 013). + \E The escape character (ascii 033). + \\ The backslash character \. + \0x The character defined by the 1, 2, or 3-digit octal string given by x. + + The -R option will print all subsequent arguments and options other than -n. The -e causes + the above escape conventions to be applied. This is the default behavior. It reverses the + effect of an earlier -r. The -p option causes the arguments to be written onto the pipe of + the process spawned with ⎪& instead of standard output. The -v option treats each arg as a + variable name and writes the value in the printf %B format. The -C option treats each arg as + a variable name and writes the value in the printf %#B format. The -s option causes the ar‐ + guments to be written onto the history file instead of standard output. The -u option can be + used to specify a one digit file descriptor unit number unit on which the output will be + placed. The default is 1. If the option -n is used, no new-line is added to the output. + + printf [ -v varname ] format [ arg ... ] + The arguments arg are printed on standard output in accordance with the ANSI-C formatting + rules associated with the format string format. If the number of arguments exceeds the num‐ + ber of format specifications, the format string is reused to format remaining arguments. If + the -v option is specified the output is assigned to the variable varname. The following ex‐ + tensions can also be used: + %b A %b format can be used instead of %s to cause escape sequences in the corresponding + arg to be expanded as described in print. + %B A %B option causes each of the arguments to be treated as variable names and the bi‐ + nary value of variable will be printed. The alternate flag # causes a compound vari‐ + able to be output on a single line. This is most useful for compound variables and + variables whose attribute is -b. + %H A %H format can be used instead of %s to cause characters in arg that are special in + HTML and XML to be output as their entity name. The alternate flag # formats the out‐ + put for use as a URI. + %P A %P format can be used instead of %s to cause arg to be interpreted as an extended + regular expression and be printed as a shell pattern. + %R A %R format can be used instead of %s to cause arg to be interpreted as a shell pat‐ + tern and to be printed as an extended regular expression. + %q A %q format can be used instead of %s to cause the resulting string to be quoted in a + manner than can be reinput to the shell. When q is preceded by the alternative format + specifier, #, the string is quoted in manner suitable as a field in a .csv format + file. + %(date-format)T + A %(date-format)T format can be use to treat an argument as a date/time string and to + format the date/time according to the date-format as defined for the date(1) command. + Values specified as digits are interpreted as described in the touch(1) command. + %Z A %Z format will output a byte whose value is 0. + %d The precision field of the %d format can be followed by a . and the output base. In + this case, the # flag character causes base# to be prepended. + # The # flag, when used with the %d format without an output base, displays the output + in powers of 1000 indicated by one of the following suffixes: k M G T P E, and when + used with the %i format displays the output in powers of 1024 indicated by one of the + following suffixes: Ki Mi Gi Ti Pi Ei. + = The = flag centers the output within the specified field width. + L The L flag, when used with the %c or %s formats, treats precision as character width + instead of byte count. + , The , flag, when used with the %d or %f formats, separates groups of digits with the + grouping delimiter (, on groups of 3 in the C locale.) + + pwd [ -LP ] [ -f fd ] + Outputs the value of the current working directory. The -L option is the default; it prints + the logical name of the current directory. If the -P option is given, all symbolic links are + resolved from the name. The last instance of -L or -P on the command line determines which + method is used. If the -f option is specified, the directory name corresponding to file de‐ + scriptor fd is outputted. + + read [ -AaCSprsv ] [ -d delim] [ -n n] [ -N n] [ -m method] [ -t timeout] [ -u unit] [ vname?prompt + ] [ vname ... ] + The shell input mechanism. One line is read and is broken up into fields using the charac‐ + ters in IFS as separators. The escape character, \, is used to remove any special meaning + for the next character and for line continuation. The -d option causes the read to continue + to the first character of delim rather than new-line. The -n option causes at most n bytes + to read rather a full line but will return when reading from a slow device as soon as any + characters have been read. The -N option causes exactly n to be read unless an end-of-file + has been encountered or the read times out because of the -t option. In raw mode, -r, the \ + character is not treated specially. The first field is assigned to the first vname, the sec‐ + ond field to the second vname, etc., with leftover fields assigned to the last vname. When + vname has the binary attribute and -n or -N is specified, the bytes that are read are stored + directly into the variable. If the -v is specified, then the value of the first vname will + be used as a default value when reading from a terminal device. The -A option causes the + variable vname to be unset and each field that is read to be stored in successive elements of + the indexed array vname. -a is an alias for -A. The -m option reads a compound variable + with the read method defined by method. Currently, only the json and ksh methods exist. The + -C option causes the variable vname to be read as a compound variable. Blanks will be ig‐ + nored when finding the beginning open parenthesis. This is equivalent to -m ksh. The -S op‐ + tion causes the line to be treated like a record in a .csv format file so that double quotes + can be used to allow the delimiter character and the new-line character to appear within a + field. The -p option causes the input line to be taken from the input pipe of a process + spawned by the shell using ⎪&. If the -s option is present, the input will be saved as a + command in the history file. The option -u can be used to specify a one digit file descrip‐ + tor unit unit to read from. The file descriptor can be opened with the exec special built-in + command. The default value of unit n is 0. The option -t is used to specify a timeout in + seconds when reading from a terminal or pipe. If vname is omitted, then REPLY is used as the + default vname. An end-of-file with the -p option causes cleanup for this process so that an‐ + other can be spawned. If the first argument contains a ?, the remainder of this word is used + as a prompt on standard error when the shell is interactive. The exit status is 0 unless an + end-of-file is encountered or read has timed out. + + †† readonly [ -p ] [ vname[=value] ] ... + If vname is not given, the names and values of each variable with the readonly attribute is + printed with the values quoted in a manner that allows them to be re-inputted. The -p option + causes the word readonly to be inserted before each one. Otherwise, the given vnames are + marked readonly and these names cannot be changed by subsequent assignment. When defining a + type, if the value of a readonly sub-variable is not defined the value is required when cre‐ + ating each instance. + + † return [ n ] + Causes a shell function or . script to return to the invoking script with the exit status + specified by n. The value will be the least significant 8 bits of the specified status. If + n is omitted, then the return status is that of the last command executed. If return is in‐ + voked while not in a function or a . script, then it behaves the same as exit. + + † set [ ±BCGabefhkmnoprstuvx ] [ ±o [ option ] ] ... [ ±A vname ] [ -K keylist ] [ arg ... ] + The options for this command have meaning as follows: + -A Array assignment. If arg is specified, unset the variable vname and assign values + sequentially from the arg list. If +A is used, the variable vname is not unset + first. + -B Enable brace group expansion. On by default. + -C Prevents redirection > from truncating existing files. Files that are created are + opened with the O_EXCL mode. Requires >⎪ to truncate a file when turned on. + -G Causes the pattern ** by itself to match files and zero or more directories and sub- + directories when used for file name generation. If followed by a / only directories + and sub-directories are matched. + -H Enable !-style history expansion similar to csh(1). + -K When no arguments are specified, it is used along with -s to specify the sort fields + and sort options for sorting an array. (See "Array Sorting" above for the descrip‐ + tion of the keylist option.) + -a All subsequent variables that are defined are automatically exported. + -b Prints job completion messages as soon as a background job changes state rather than + waiting for the next prompt. + -e Unless contained in a ⎪⎪ or && command, or the command following an if while or until + command or in the pipeline following !, if a command has a non-zero exit status, exe‐ + cute the ERR trap, if set, and exit. This mode is disabled while reading profiles. + -f Disables file name generation. + -h Each command becomes a tracked alias when first encountered. + -k (Obsolete). All variable assignment arguments are placed in the environment for a + command, not just those that precede the command name. + -m Background jobs will run in a separate process group and a line will print upon com‐ + pletion. The exit status of background jobs is reported in a completion message. On + systems with job control, this option is turned on automatically for interactive + shells. + -n Read commands and check them for syntax errors, but do not execute them. Ignored for + interactive shells. + -o The following argument can be one of the following option names: + allexport + Same as -a. + bgnice All background jobs are run at a lower priority. This is the default mode. + braceexpand + Same as -B. + emacs Puts you in an emacs style in-line editor for command entry. + errexit Same as -e. + globstar + Same as -G. + gmacs Puts you in a gmacs style in-line editor for command entry. + histexpand + Same as -H. + ignoreeof + The shell will not exit on end-of-file. The command exit must be used. + keyword Same as -k. + letoctal + The let command allows octal constants starting with 0. + markdirs + All directory names resulting from file name generation have a trailing / ap‐ + pended. + monitor Same as -m. + multiline + The built-in editors will use multiple lines on the screen for lines that are + longer than the width of the screen. This may not work for all terminals. + noclobber + Same as -C. + noexec Same as -n. + noglob Same as -f. + nolog Do not save function definitions in the history file. + notify Same as -b. + nounset Same as -u. + pipefail + A pipeline will not complete until all components of the pipeline have com‐ + pleted, and the return value will be the value of the last non-zero command + to fail or zero if no command has failed. + privileged + Same as -p. + showme When enabled, simple commands or pipelines preceded by a semicolon (;) will + be displayed as if the xtrace option were enabled but will not be executed. + Otherwise, the leading ; will be ignored. + trackall + Same as -h. + verbose Same as -v. + vi Puts you in insert mode of a vi style in-line editor until you hit the escape + character 033. This puts you in control mode. A return sends the line. + viraw Each character is processed as it is typed in vi mode. This is now always + enabled. Disabling the option at run time has no effect. + xtrace Same as -x. + If no option name is supplied, then the current option settings are printed. + -p Disables processing of the $HOME/.profile file and uses the file /etc/suid_profile + instead of the ENV file. This mode is on whenever the effective uid (gid) is not + equal to the real uid (gid). Turning this off causes the effective uid and gid to be + set to the real uid and gid. + -r Enables the restricted shell. This option cannot be unset once set. + -s Sort the positional parameters lexicographically. When used with -A + sorts the elements of the array. + -t (Obsolete). Exit after reading and executing one command. + -u Treat unset parameters as an error when substituting. + -v Print shell input lines as they are read. + -x Print commands and their arguments as they are executed. + -- Do not change any of the options; useful in setting $1 to a value beginning with -. + If no arguments follow this option then the positional parameters are unset. + + As an obsolete feature, if the first arg is - then the -x and -v options are turned off and + the next arg is treated as the first argument. Using + rather than - causes these options to + be turned off. These options can also be used upon invocation of the shell. The current set + of options may be found in $-. Unless -A is specified, the remaining arguments are posi‐ + tional parameters and are assigned, in order, to $1 $2 .... If no arguments are given, then + the names and values of all variables are printed on the standard output. + + † shift [ n ] + The positional parameters from $n+1 ... are renamed $1 ... , default n is 1. The parameter + n can be any arithmetic expression that evaluates to a non-negative number less than or equal + to $#. + + sleep seconds + Suspends execution for the number of decimal seconds or fractions of a second given by sec‐ + onds. seconds A suffix of one of smhd can be used to indicate seconds, minutes, hours, and + days respectively. Seconds can also be specified using a date/time format. + + times Display CPU time used by the shell and all of its child processes. + + † trap [ -alp ] [ action ] [ sig ] ... + The -p option causes the trap action associated with each trap as specified by the arguments + to be printed with appropriate quoting. Otherwise, action will be processed as if it were an + argument to eval when the shell receives signal(s) sig. + The -a option causes the current trap setting to be appended to action. Each sig can be + given as a number or as the name of the signal. Trap commands are executed in order of sig‐ + nal number. Any attempt to set a trap on a signal that was ignored on entry to the current + shell is ineffective. If action is omitted and the first sig is a number, or if action is -, + then the trap(s) for each sig are reset to their original values. If action is the null + string then this signal is ignored by the shell and by the commands it invokes. + If sig is ERR then action will be executed whenever a command has a non-zero exit status. + If sig is DEBUG then action will be executed before each command. The variable .sh.command + will contain the contents of the current command line when action is running. If the exit + status of the trap is 2 the command will not be executed. If the exit status of the trap is + 255 and inside a function or a dot script, the function or dot script will return. + If sig is 0 or EXIT and the trap statement is executed inside the body of a function defined + with the function name syntax, then the command action is executed after the function com‐ + pletes. For a trap set outside any function then the command action is executed on exit from + the shell. + If sig is KEYBD, then action will be executed whenever a key is read while in emacs, gmacs, + or vi mode. The trap command with no arguments prints a list of commands associated with + each signal number. + An exit or return without an argument in a trap action will preserve the exit status of the + command that invoked the trap. action. Each sig can be given as a number or as the name of + the signal. Trap commands are executed in order of signal number. Any attempt to set a trap + on a signal that was ignored on entry to the current shell is ineffective. If action is + omitted and the first sig is a number, or if action is -, then the trap(s) for each sig are + reset to their original values. The -l option lists the signals and their numbers to stan‐ + dard output. + + true Does nothing, and exits 0. Used with while for infinite loops. + + †† typeset [ ±ACHSfblmnprstux ] [ ±EFLRXZi[n] ] [ +-M [ mapname ] ] [ -T [ tname=(assign_list) ] + ] [ -h str ] [ -a [type] ] [ vname[=value ] ] ... + Sets attributes and values for shell variables and functions. When invoked inside a function + defined with the function name syntax, a new instance of the variable vname is created, and + the variable's value and type are restored when the function completes. The following list + of attributes may be specified: + -A Declares vname to be an associative array. Subscripts are strings rather than arith‐ + metic expressions. + -C causes each vname to be a compound variable. value names a compound variable it is + copied into vname. Otherwise, it unsets each vname. + -a Declares vname to be an indexed array. If type is specified, it must be the name of + an enumeration type created with the enum command and it allows enumeration constants + to be used as subscripts. + -E Declares vname to be a double precision floating point number. If n is non-zero, it + defines the number of significant figures that are used when expanding vname. Other‐ + wise, ten significant figures will be used. + -F Declares vname to be a double precision floating point number. If n is non-zero, it + defines the number of places after the decimal point that are used when expanding + vname. Otherwise ten places after the decimal point will be used. + -H This option provides UNIX to host-name file mapping on non-UNIX machines. + -L Left justify and remove leading blanks from value. If n is non-zero, it defines the + width of the field, otherwise it is determined by the width of the value of first as‐ + signment. When the variable is assigned to, it is filled on the right with blanks or + truncated, if necessary, to fit into the field. The -R option is turned off. + -M Use the character mapping mapping defined by wctrans(3). such as tolower and toupper + when assigning a value to each of the specified operands. When mapping is specified + and there are not operands, all variables that use this mapping are written to stan‐ + dard output. When mapping is omitted and there are no operands, all mapped variables + are written to standard output. + -R Right justify and fill with leading blanks. If n is non-zero, it defines the width of + the field, otherwise it is determined by the width of the value of first assignment. + The field is left filled with blanks or truncated from the end if the variable is re‐ + assigned. The -L option is turned off. + -S When used within the assign_list of a type definition, it causes the specified sub- + variable to be shared by all instances of the type. When used inside a function de‐ + fined with the function reserved word, the specified variables will have function + static scope. Otherwise, the variable is unset prior to processing the assignment + list. + -T If followed by tname, it creates a type named by tname using the compound assignment + assign_list to tname. Otherwise, it writes all the type definitions to standard out‐ + put. + -X Declares vname to be a double precision floating point number and expands using the %a + format of ISO-C99. If n is non-zero, it defines the number of hex digits after the + radix point that is used when expanding vname. The default is 10. + -Z Right justify and fill with leading zeros if the first non-blank character is a digit + and the -L option has not been set. Remove leading zeros if the -L option is also + set. If n is non-zero, it defines the width of the field, otherwise it is determined + by the width of the value of first assignment. + -f The names refer to function names rather than variable names. No assignments can be + made and the only other valid options are -S, -t, -u and -x. The -S can be used with + discipline functions defined in a type to indicate that the function is static. For a + static function, the same method will be used by all instances of that type no matter + which instance references it. In addition, it can only use value of variables from + the original type definition. These discipline functions cannot be redefined in any + type instance. The -t option turns on execution tracing for this function. The -u + option causes this function to be marked undefined. The FPATH variable will be + searched to find the function definition when the function is referenced. If no op‐ + tions other than -f is specified, then the function definition will be displayed on + standard output. If +f is specified, then a line containing the function name fol‐ + lowed by a shell comment containing the line number and path name of the file where + this function was defined, if any, is displayed. The exit status can be used to de‐ + termine whether the function is defined so that typeset -f .sh.math.name will return 0 + when math function name is defined and non-zero otherwise. + -b The variable can hold any number of bytes of data. The data can be text or binary. + The value is represented by the base64 encoding of the data. If -Z is also specified, + the size in bytes of the data in the buffer will be determined by the size associated + with the -Z. If the base64 string assigned results in more data, it will be trun‐ + cated. Otherwise, it will be filled with bytes whose value is zero. The printf for‐ + mat %B can be used to output the actual data in this buffer instead of the base64 en‐ + coding of the data. + -h Used within type definitions to add information when generating information about the + sub-variable on the man page. It is ignored when used outside of a type definition. + When used with -f the information is associated with the corresponding discipline + function. + -i Declares vname to be represented internally as integer. The right hand side of an as‐ + signment is evaluated as an arithmetic expression when assigning to an integer. If n + is non-zero, it defines the output arithmetic base, otherwise the output base will be + ten. + -l Used with -i, -E or -F, to indicate long integer, or long double. Otherwise, all up‐ + per-case characters are converted to lower-case. The upper-case option, -u, is turned + off. Equivalent to -M tolower . + -m moves or renames the variable. The value is the name of a variable whose value will + be moved to vname. The original variable will be unset. Cannot be used with any + other options. + -n Declares vname to be a reference to the variable whose name is defined by the value of + variable vname. This is usually used to reference a variable inside a function whose + name has been passed as an argument. Cannot be used with any other options. + -p The name, attributes and values for the given vnames are written on standard output in + a form that can be used as shell input. If +p is specified, then the values are not + displayed. + -r The given vnames are marked readonly and these names cannot be changed by subsequent + assignment. + -s Used with -i, -E or -F, to indicate short integer, or float. + -t Tags the variables. Tags are user definable and have no special meaning to the shell. + -u When given along with -i, specifies unsigned integer. Otherwise, all lower-case char‐ + acters are converted to upper-case. The lower-case option, -l, is turned off. Equiv‐ + alent to -M toupper . + -x The given vnames are marked for automatic export to the environment of subsequently- + executed commands. Variables whose names contain a . cannot be exported. + + The -i attribute cannot be specified along with -R, -L, -Z, or -f. + + Using + rather than - causes these options to be turned off. If no vname arguments are + given, a list of vnames (and optionally the values) of the variables is printed. (Using + + rather than - keeps the values from being printed.) The -p option causes typeset followed by + the option letters to be printed before each name rather than the names of the options. If + any option other than -p is given, only those variables which have all of the given options + are printed. Otherwise, the vnames and attributes of all variables that have attributes are + printed. + + ulimit [ -HSacdfmnpstv ] [ limit ] + Set or display a resource limit. The available resource limits are listed below. Many sys‐ + tems do not support one or more of these limits. The limit for a specified resource is set + when limit is specified. The value of limit can be a number in the unit specified below with + each resource, or the value unlimited. The -H and -S options specify whether the hard limit + or the soft limit for the given resource is set. A hard limit cannot be increased once it is + set. A soft limit can be increased up to the value of the hard limit. If neither the H nor + S option is specified, the limit applies to both. The current resource limit is printed when + limit is omitted. In this case, the soft limit is printed unless H is specified. When more + than one resource is specified, then the limit name and unit is printed before the value. + -a Lists all of the current resource limits. + -c The number of 512-byte blocks on the size of core dumps. + -d The number of K-bytes on the size of the data area. + -f The number of 512-byte blocks on files that can be written by the current process or + by child processes (files of any size may be read). + -m The number of K-bytes on the size of physical memory. + -n The number of file descriptors plus 1. + -p The number of 512-byte blocks for pipe buffering. + -s The number of K-bytes on the size of the stack area. + -t The number of CPU seconds to be used by each process. + -v The number of K-bytes for virtual memory. + + If no option is given, -f is assumed. + + umask [ -pS ] [ mask ] + The user file-creation mask is set to mask (see umask(2)). mask can either be an octal num‐ + ber or a symbolic value as described in chmod(1). If a symbolic value is given, the new + umask value is the complement of the result of applying mask to the complement of the previ‐ + ous umask value. If mask is omitted, the current value of the mask is printed. The -S op‐ + tion causes the mode to be printed as a symbolic value. Otherwise, the mask is printed in + octal. The -p option cause the output to be in a form that can be use for reinput. + + † unalias [ -a ] name ... + The aliases given by the list of names are removed from the alias list. The -a option causes + all the aliases to be unset. + + †unset [ -fnv ] vname ... + The variables given by the list of vnames are unassigned, i.e., except for sub-variables + within a type, their values and attributes are erased. For sub-variables of a type, the val‐ + ues are reset to the default value from the type definition. Readonly variables cannot be + unset. If the -f option is set, then the names refer to function names. If the -v option is + set, then the names refer to variable names. The -f option overrides -v. If -n is set and + name is a name reference, then name will be unset rather than the variable that it refer‐ + ences. The default is equivalent to -v. Unsetting LINENO, MAILCHECK, OPTARG, OPTIND, RAN‐ + DOM, SECONDS, TMOUT, and _ removes their special meaning even if they are subsequently as‐ + signed to. + + wait [ job ... ] + Wait for the specified job and report its termination status. If job is not given, then all + currently active child processes are waited for. The exit status from this command is that + of the last process waited for if job is specified; otherwise it is zero. See Jobs for a de‐ + scription of the format of job. + + whence [ -afpv ] name ... + For each name, indicate how it would be interpreted if used as a command name. + The -v option produces a more verbose report. The -f option skips the search for functions. + The -p option does a path search for name even if name is an alias, a function, or a reserved + word. The -p option turns off the -v option. The -a option is similar to the -v option but + causes all interpretations of the given name to be reported. + + Invocation. + If the shell is invoked by exec(2), and the first character of argument zero ($0) is -, then the + shell is assumed to be a login shell and commands are read from /etc/profile and then from + $HOME/.profile, if it exists. Alternatively, the option -l causes the shell to a treated as a login + shell. Next, for interactive shells, commands are read from the file named by performing parameter + expansion, command substitution, and arithmetic substitution on the value of the environment vari‐ + able ENV if the file exists. If the -s option is not present and arg and a file by the name of arg + exists, then it reads and executes this script. Otherwise, if the first arg does not contain a /, a + path search is performed on the first arg to determine the name of the script to execute. The + script arg must have execute permission and any setuid and setgid settings will be ignored. If the + script is not found on the path, arg is processed as if it named a built-in command or function. + Commands are then read as described below; the following options are interpreted by the shell when + it is invoked: + + -D A list of all double quoted strings that are preceded by a $ will be printed on standard + output and the shell will exit. This set of strings will be subject to language translation + when the locale is not C or POSIX. No commands will be executed. + + -E Reads the file named by the ENV variable or by $HOME/.kshrc if not defined after the pro‐ + files. + + -c If the -c option is present, then commands are read from the first arg. Any remaining argu‐ + ments become positional parameters starting at 0. + + -s If the -s option is present or if no arguments remain, then commands are read from the stan‐ + dard input. Shell output, except for the output of the Special Commands listed above, is + written to file descriptor 2. + + -i If the -i option is present or if the shell input and error output are attached to a termi‐ + nal (as told by tcgetattr(2)), then this shell is interactive. In this case TERM is ignored + (so that kill 0 does not kill an interactive shell) and INTR is caught and ignored (so that + wait is interruptible). In all cases, QUIT is ignored by the shell. + + -r If the -r option is present, the shell is a restricted shell. + + -R filename + The -R filename option is used to generate a cross reference database that can be used by a + separate utility to find definitions and references for variables and commands. The file‐ + name argument specifies the generated database. A script file must be provided on the com‐ + mand line as well. + + The remaining options and arguments are described under the set command above. An optional - as the + first argument is ignored. + + Rksh Only. + Rksh is used to set up login names and execution environments whose capabilities are more controlled + than those of the standard shell. The actions of rksh are identical to those of ksh, except that + the following are disallowed: + Unsetting the restricted option. + changing directory (see cd(1)), + setting or unsetting the value or attributes of SHELL, ENV, FPATH, or PATH, + specifying path or command names containing /, + redirecting output (>, >|, <>, and >>). + adding or deleting built-in commands. + using command -p to invoke a command. + + The restrictions above are enforced after .profile and the ENV files are interpreted. + + When a command to be executed is found to be a shell procedure, rksh invokes ksh to execute it. + Thus, it is possible to provide to the end-user shell procedures that have access to the full power + of the standard shell, while imposing a limited menu of commands; this scheme assumes that the end- + user does not have write and execute permissions in the same directory. + + The net effect of these rules is that the writer of the .profile has complete control over user ac‐ + tions, by performing guaranteed setup actions and leaving the user in an appropriate directory + (probably not the login directory). + + The system administrator often sets up a directory of commands (e.g., /usr/rbin) that can be safely + invoked by rksh. + +EXIT STATUS + Errors detected by the shell, such as syntax errors, cause the shell to return a non-zero exit sta‐ + tus. If the shell is being used non-interactively, then execution of the shell file is abandoned + unless the error occurs inside a subshell in which case the subshell is abandoned. Otherwise, the + shell returns the exit status of the last command executed (see also the exit command above). Run + time errors detected by the shell are reported by printing the command or function name and the er‐ + ror condition. If the line number that the error occurred on is greater than one, then the line + number is also printed in square brackets ([]) after the command or function name. + +FILES + /etc/profile + The system wide initialization file, executed for login shells. + + $HOME/.profile + The personal initialization file, executed for login shells after /etc/profile. + + $HOME/.kshrc + Default personal initialization file, executed for interactive shells when ENV is not set. + + /etc/suid_profile + Alternative initialization file, executed instead of the personal initialization file when + the real and effective user or group id do not match. + + /dev/null + NULL device + +SEE ALSO + cat(1), cd(1), chmod(1), cut(1), date(1), egrep(1), echo(1), emacs(1), env(1), fgrep(1), gmacs(1), + grep(1), newgrp(1), stty(1), test(1), touch(1), umask(1), vi(1), dup(2), exec(2), fork(2), getpw‐ + nam(3), ioctl(2), lseek(2), paste(1), pathconf(2), pipe(2), sigsetinfo(2), sysconf(2), umask(2), + ulimit(2), wait(2), wctrans(3), rand(3), a.out(5), profile(5), environ(7). + + Morris I. Bolsky and David G. Korn, The New KornShell Command and Programming Language, Prentice + Hall, 1995. + + POSIX - Part 2: Shell and Utilities, IEEE Std 1003.2-1992, ISO/IEC 9945-2, IEEE, 1993. + +CAVEATS + If a command is executed, and then a command with the same name is installed in a directory in the + search path before the directory where the original command was found, the shell will continue to + exec the original command. Use the -t option of the alias command to correct this situation. + + Some very old shell scripts contain a ^ as a synonym for the pipe character ⎪. + + Using the hist built-in command within a compound command will cause the whole command to disappear + from the history file. + + The built-in command . file reads the whole file before any commands are executed. Therefore, alias + and unalias commands in the file will not apply to any commands defined in the file. + + Traps are not processed while a job is waiting for a foreground process. Thus, a trap on CHLD won't + be executed until the foreground job terminates. + + It is a good idea to leave a space after the comma operator in arithmetic expressions to prevent the + comma from being interpreted as the decimal point character in certain locales. + + KSH(1) diff --git a/week-04/week4.log b/week-04/week4.log new file mode 100644 index 0000000..a877d73 --- /dev/null +++ b/week-04/week4.log @@ -0,0 +1,40 @@ +Script started on 2020-09-28 05:20:05+02:00 [TERM="xterm-256color" TTY="/dev/pts/1" COLUMNS="110" LINES="24"] +Create Working Directories +Creating /home/llewellyn/Linux Programming I/1_Week1_1 +Creating /home/llewellyn/Linux Programming I/1_Week2_1 +Creating /home/llewellyn/Linux Programming I/1_Week3_1 +Creating /home/llewellyn/Linux Programming I/1_Week4_1 +Creating /home/llewellyn/Linux Programming I/1_Week5_1 +Creating /home/llewellyn/Linux Programming I/1_Week6_1 +Creating /home/llewellyn/Linux Programming I/1_Week7_1 +Creating /home/llewellyn/Linux Programming I/2_Week8_1 +Creating /home/llewellyn/Linux Programming I/2_Week9_1 +Creating /home/llewellyn/Linux Programming I/2_Week10_1 +Creating /home/llewellyn/Linux Programming I/2_Week11_1 +Creating /home/llewellyn/Linux Programming I/2_Week12_1 +Creating /home/llewellyn/Linux Programming I/2_Week13_1 +Creating /home/llewellyn/Linux Programming I/2_Week14_1 +Creating /home/llewellyn/Linux Programming I/2_Week15_1 +Change your prompt variable to display the current working directory (pwd) +Set the history to be 100 commands +Change to working directory /home/llewellyn/Linux Programming I/1_Week4_1 +Set an alias to allow typing h to list the history of commands. +Set an alias for listlong to be ls –latr. +Set an alias named dir to be ls -aF | more +Set an alias named del to be "rm -i". +Display the values of your TERM and HOME environment variables to the screen. +TERM = xterm-256color +HOME = /home/llewellyn +When the IGNOREEOF=4 the means pressing CTRL-D four times will only close my session. +Write bash man page to /home/llewellyn/Linux Programming I/1_Week4_1/bash.txt +Write csh man page to /home/llewellyn/Linux Programming I/1_Week4_1/csh.txt +Write korn/ksh man page to /home/llewellyn/Linux Programming I/1_Week4_1/korn.txt +list the number of files in /usr/local/bin +~/ls_output is in the current user directory +On my PC there is 1385 files in this directory +There is 179 prossess running right now. +My whole script demostrates the >> and > +The >> adds a new line to a file +The > replace the whole file with the new given values + +Script done on 2020-09-28 05:20:05+02:00 [COMMAND_EXIT_CODE="0"] diff --git a/week-04/week4.sh b/week-04/week4.sh new file mode 100755 index 0000000..a3d2f12 --- /dev/null +++ b/week-04/week4.sh @@ -0,0 +1,133 @@ +#!/bin/bash +#/------------------------------------------------------------------------------------------------------- +# +# @version 1.0.0 +# @build 28th Sept, 2020 +# @package SDEV-415-81: Linux/ Unix Programming I - Fall 2020 (2020FA) +# @sub-package Week 4: Assignment - Directory Structure +# @author Llewellyn van der Merwe +# @copyright Copyright (C) 2020. All Rights Reserved +# @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html +# +#/-------------------------------------------------------------------------------------------------------- + + +# 1. Create a directory structure for the work you do in this class. The directory structure should +# include a top-level directory (located in your home directory) named “Linux Programming I”. +# You then need to create sub-directories inside this directory for each week. +# (week1, week2, all the way up to week15). +# Lastly, create Assignment directories in each “weekN” directory. +# You will need to use the mkdir and cd commands to do this. +# You should also use the ls command to demonstrate the creation of the directory structure. + +echo "Create Working Directories" + +DIR="/home/llewellyn/Linux Programming I" +if [ ! -d "$DIR" ] + then + mkdir -p "$DIR" +fi +# now create the first 7 weeks directories +for w in {1..7}; +do + WEEK="${DIR}/1_Week${w}_1" + echo "Creating $WEEK" + if [ ! -d "$WEEK" ] + then + mkdir -p "$WEEK" + fi +done +# now create the last 7/8 weeks directories +for w in {8..15}; +do + WEEK="${DIR}/2_Week${w}_1" + echo "Creating $WEEK" + if [ ! -d "${DIR}/2_Week${w}_1" ] + then + mkdir -p "${DIR}/2_Week${w}_1" + fi +done + +# 2. Perform the following + +echo "Change your prompt variable to display the current working directory (pwd)" +echo "" >> /home/llewellyn/.bashrc +echo "# Set SIMPLE (pwd) prompt" >> /home/llewellyn/.bashrc +echo "PS1='\${PWD##*/}/ '" >> /home/llewellyn/.bashrc + +echo "Set the history to be 100 commands" +echo "" >> /home/llewellyn/.profile +echo "# Keep only 100 History Commands" >> /home/llewellyn/.profile +echo "export HISTSIZE=100" >> /home/llewellyn/.profile + +echo "Change to working directory ${PWD}" +cd "${PWD}" + +echo "Set an alias to allow typing h to list the history of commands." +echo "" >> /home/llewellyn/.bash_aliases +echo "# To list history of commands" >> /home/llewellyn/.bash_aliases +echo "alias h='!!'" >> /home/llewellyn/.bash_aliases + +echo "Set an alias for listlong to be ls –latr." +echo "" >> /home/llewellyn/.bash_aliases +echo "# To list long detials" >> /home/llewellyn/.bash_aliases +echo "alias listlong='ls -latr'" >> /home/llewellyn/.bash_aliases + +echo "Set an alias named dir to be ls -aF | more" +echo "" >> /home/llewellyn/.bash_aliases +echo "# To show dir listing" >> /home/llewellyn/.bash_aliases +echo "alias dir='ls -aF | more'" >> /home/llewellyn/.bash_aliases + +echo "Set an alias named del to be \"rm -i\"." +echo "" >> /home/llewellyn/.bash_aliases +echo "# To do a stupid prompt before every removal" >> /home/llewellyn/.bash_aliases +echo "alias del='rm -i'" >> /home/llewellyn/.bash_aliases + +# 3. TERM and HOME + +echo "Display the values of your TERM and HOME environment variables to the screen." +echo "TERM = ${TERM}" +echo "HOME = ${HOME}" + +# 4. Hit the CTRL-D key combination + +echo "When the IGNOREEOF=4 the means pressing CTRL-D four times will only close my session." +echo "" >> /home/llewellyn/.profile +echo "# Prevent closing a session inadvertently" >> /home/llewellyn/.profile +echo "export IGNOREEOF=4" >> /home/llewellyn/.profile + +# 5. MAN page + +echo "Write bash man page to ${PWD}/bash.txt" +man bash > "${PWD}/bash.txt" + +echo "Write csh man page to ${PWD}/csh.txt" +man csh > "${PWD}/csh.txt" + +echo "Write korn/ksh man page to ${PWD}/korn.txt" +man ksh > "${PWD}/korn.txt" + +# 6. number of files in /usr/bin + +echo "list the number of files in /usr/local/bin" +ls -1 /usr/bin | wc -l > ~/ls_output +echo "~/ls_output is in the current user directory" +echo "On my PC there is 1385 files in this directory" + +# 7. Display the current number of processes +# running on your system using any number +# of commands and a pipe. I want the number, +# not just a list of processes. + +number=$(ps aux | wc -l) +echo "There is ${number} prossess running right now." + +# 8. Explain the difference between “>” and “>>” +# when using redirection. Also, what does +# the “!” command do. +# Give me an example and its output. + +echo "My whole script demostrates the >> and >" +echo "The >> adds a new line to a file" +echo "The > replace the whole file with the new given values" +