sh(1) - NetBSD Manual Pages

SH(1)                   NetBSD General Commands Manual                   SH(1)


NAME
sh -- command interpreter (shell)
SYNOPSIS
sh [-abCEeFfhIiLmnpquVvXx] [+abCEeFfhIiLmnpquVvXx] [-o option_name] [+o option_name] [command_file [argument ...]] sh -c [-s] [-abCEeFfhIiLmnpquVvXx] [+abCEeFfhIiLmnpquVvXx] [-o option_name] [+o option_name] command_string [command_name [argument ...]] sh -s [-abCEeFfhIiLmnpquVvXx] [+abCEeFfhIiLmnpquVvXx] [-o option_name] [+o option_name] [argument ...]
DESCRIPTION
sh is the standard command interpreter for the system. It is a re-imple- mentation and extension of the Bourne shell. This version has many fea- tures which make it appear similar in some respects to the Korn shell, but it is not a Korn shell clone (see ksh(1)). This man page is not intended to be a tutorial or a complete specification of the shell. Overview The shell is a command that reads lines from either a file or the termi- nal, interprets them, and generally executes other commands. A shell is the program that is running when a user logs into the system. (Users can select which shell is executed for them at login with the chsh(1) com- mand). The shell implements a language that has flow control constructs, a macro facility that provides a variety of features in addition to data storage, along with built in history and line editing capabilities. It incorporates many features to aid interactive use and has the advantage that the interpretative language is common to both interactive and non- interactive use (shell scripts). That is, commands can be typed directly to the running shell or can be put into a file and the file can be exe- cuted directly by the shell. Invocation If no arguments are present and if the standard input, and standard error output, of the shell are connected to a terminal (or terminals, or if the -i flag is set), and the -c option is not present, the shell is consid- ered an interactive shell. An interactive shell generally prompts before each command and handles programming and command errors differently (as described below). When first starting, the shell inspects argument 0, and if it begins with a dash `-', the shell is also considered a login shell. This is normally done automatically by the system when the user first logs in. A login shell first reads commands (as if by using the ``.'' command) from the files /etc/profile and .profile in the user's home directory ($HOME), if they exist. If the environment variable ENV is set on entry to a shell, or is set in the .profile of a login shell, and either the shell is interactive, or the posix option is not set, the shell then performs parameter and arithmetic expansion on the value of ENV, (these are described later) and if no errors occurred, then reads commands from the file name that results. Note that no error messages result from these expansions, to verify that ENV is correct, as desired, use: eval printf '%s\\n' ``${ENV}'' Otherwise if ENV appears to contain a command substitution, which is not performed here, or if there were no expansions to expand, the value of ENV is used as the file name. Therefore, a user should place commands that are to be executed only at login time in the .profile file, and commands that are executed for every shell inside the ENV file. To set the ENV variable to some file, place the following line in your .profile of your home directory ENV=$HOME/.shinit; export ENV substituting for ``.shinit'' any filename you wish. Since the ENV file can be read for every invocation of the shell, including shell scripts and non-interactive shells, the following paradigm is useful for restricting commands in the ENV file to interactive invocations. Place commands within the ``case'' and ``esac'' below (these commands are described later): case $- in *i*) # commands for interactive use only ... esac If command line arguments besides the options have been specified, and neither -c nor -s was given, then the shell treats the first argument as the name of a file from which to read commands (a shell script). This also becomes $0 and the remaining arguments are set as the positional parameters of the shell ($1, $2, etc). Otherwise, if -c was given, then the first argument, which must exist, is taken to be a string of sh com- mands to execute. Then if any additional arguments follow the command string, those arguments become $0, $1, ... Otherwise, if additional arguments were given (which implies that -s was set) those arguments become $1, $2, ... If $0 has not been set by the preceding processing, it will be set to argv[0] as passed to the shell, which will usually be the name of the shell itself. If -s was given, or if neither -c nor any additional (non-option) arguments were present, the shell reads commands from its standard input. Argument List Processing Currently, all of the single letter options that can meaningfully be set using the set built-in, have a corresponding name that can be used as an argument to the -o option. The set -o name is provided next to the sin- gle letter option in the description below. Some options have only a long name, they are described after the flag options, they are used with -o or +o only, either on the command line, or with the set built-in com- mand. Other options described are for the command line only. Specifying a dash ``-'' turns the option on, while using a plus ``+'' disables the option. The following options can be set from the command line and, unless otherwise stated, with the set built-in (described later). -a allexport Automatically export any variable to which a value is assigned while this flag is set, unless the variable has been marked as not for export. -b notify Enable asynchronous notification of background job completion. (Not implemented.) -C noclobber Don't overwrite existing files with ``>''. -c Read commands from the command_string operand instead of, or in addition to, from the standard input. Special parameter 0 will be set from the command_name operand if given, and the positional parameters (1, 2, etc.) set from the remaining argument operands, if any. -c is only available at invocation, it cannot be set, and there is no form using ``+''. -E emacs Enable the built-in emacs style command line edi- tor (disables -V if it had been set). (See the Command Line Editing section below.) -e errexit If not interactive, exit immediately if any untested command fails. If interactive, and an untested command fails, cease all processing of the current command and return to prompt for a new command. The exit status of a command is consid- ered to be explicitly tested if the command is used to control an if, elif, while, or until, or if the command is the left hand operand of an ``&&'' or ``||'' operator, or if it is a pipeline (or simple command) preceded by the ``!'' opera- tor. With pipelines, only the status of the entire pipeline (indicated by the last command it contains) is tested when -e is set to determine if the shell should exit. -F fork Cause the shell to always use fork(2) instead of attempting vfork(2) when it needs to create a new process. This should normally have no visible effect, but can slow execution. The sh can be compiled to always use fork(2) in which case altering the -F flag has no effect. -f noglob Disable pathname expansion. -h trackall Functions defined while this option is set will have paths bound to commands to be executed by the function at the time of the definition. When off when a function is defined, the file system is searched for commands each time the function is invoked. (Obsolete and not implemented.) -I ignoreeof Ignore EOFs from input when interactive. (After a large number of consecutive EOFs the shell will exit anyway.) -i interactive Force the shell to behave interactively. -L local_lineno When set, before a function is defined, causes the variable LINENO when used within the function, to refer to the line number defined such that first line of the function is line 1. When reset, LINENO in a function refers to the line number within the file within which the definition of the function occurs. This option defaults to ``on'' in this shell. For more details see the section LINENO below. -m monitor Turn on job control (set automatically when inter- active). -n noexec Read and parse commands, but do not execute them. This is useful for checking the syntax of shell scripts. If -n becomes set in an interactive shell, it will automatically be cleared just before the next time the command line prompt (PS1) is written. -p nopriv Do not attempt to reset effective UID if it does not match UID. The same applies to effective and real GIDs. This is not set by default to help avoid incorrect usage by setuid root programs via system(3) or popen(3). This option is effective only when set on the command line, but can be reset to drop privileges, once, at any time. If -p is cleared, those privileges can never be regained, however much the -p option is manipu- lated. -q quietprofile If the -v or -x options have been set, temporarily disable them before reading initialization files, these being /etc/profile, .profile, and the file specified by the ENV environment variable. -s stdin Read commands from standard input (set automati- cally if neither -c nor file arguments are present). If after processing a command_string with the -c option, the shell has not exited, and the -s option is set, it will continue reading more commands from standard input. This option has no effect when set or reset after the shell has already started reading from the command_file, or from standard input. Note that the -s flag being set does not cause the shell to be interac- tive. -u nounset Write a message to standard error when attempting to obtain a value from a variable that is not set, and if the shell is not interactive, exit immedi- ately. For interactive shells, instead return immediately to the command prompt and read the next command. Note that expansions (described later, see Word Expansions below) using the `+', `-', `=', or `?' operators test if the variable is set, before attempting to obtain its value, and hence are unaffected by -u. -V vi Enable the built-in vi(1) command line editor (disables -E if it had been set). (See the Command Line Editing section below.) -v verbose The shell writes its input to standard error as it is read. Useful for debugging. -X xlock Cause output from the xtrace (-x) option to be sent to standard error as it exists when the -X option is enabled (regardless of its previous state.) For example: set -X 2>/tmp/trace-file will arrange for tracing output to be sent to the file named, instead of wherever it was previously being sent, until the X option is set again, or cleared. Each change (set or clear) to -X is also performed upon -x, but not the converse. -x xtrace Write each command to standard error (preceded by the expanded value of $PS4) before it is executed. Unless -X is set, ``standard error'' means that which existed immediately before any redirections to be applied to the command are performed. Use- ful for debugging. cdprint Make an interactive shell always print the new directory name when changed by the cd command. In a non-interactive shell this option has no effect. nolog Prevent the entry of function definitions into the command history (see fc in the Built-ins section.) (Not implemented.) pipefail If set when a pipeline is created, the way the exit status of the pipeline is determined is altered. See Pipelines below for the details. posix Enables closer adherence to the POSIX shell stan- dard. This option will default set at shell startup if the environment variable POSIXLY_CORRECT is present. That can be overrid- den (set or reset) by the -o option on the command line. Currently this option controls whether (!posix) or not (posix) the file given by the ENV variable is read at startup by a non-interactive shell. It also controls whether file descriptors greater than 2 opened using the exec built-in com- mand are passed on to utilities executed (``yes'' in posix mode), whether a colon (:) terminates the user name in tilde (~) expansions other than in assignment statements (``no'' in posix mode), the format of the output of the kill -l command, where posix mode causes the names of the signals be sep- arated by either a single space or newline, and where otherwise sufficient spaces are inserted to generate nice looking columns, and whether the shell treats an empty brace-list compound state- ment as a syntax error (expected by POSIX) or per- mits it. Such statements ``{ }'' can be useful when defining dummy functions. Lastly, in posix mode, only one ``!'' is permitted before a pipe- line. promptcmds Allows command substitutions (as well as parameter and arithmetic expansions, which are always per- formed) upon the prompt strings PS1, PS2, and PS4 each time, before they are output. This option should not be set until after the prompts have been set (or verified) to avoid accidentally importing unwanted command substitutions from the environment. tabcomplete Enables filename completion in the command line editor. Typing a tab character will extend the current input word to match a filename. If more than one filename matches it is only extended to be the common prefix. Typing a second tab charac- ter will list all the matching names. One of the editing modes, either -E or -V, must be enabled for this to work. Lexical Structure The shell reads input in terms of lines from a file and breaks it up into words at whitespace (blanks and tabs), and at certain sequences of char- acters that are special to the shell called ``operators''. There are two types of operators: control operators and redirection operators (their meaning is discussed later). The following is a list of operators: Control operators: & && ( ) ; ;; ;& | || <newline> Redirection operators: < > >| << >> <& >& <<- <> Quoting Quoting is used to remove the special meaning of certain characters or words to the shell, such as operators, whitespace, or keywords. There are four types of quoting: matched single quotes, matched double quotes, backslash, and dollar preceding matched single quotes (enhanced C style strings.) Backslash An unquoted backslash preserves the literal meaning of the following character, with the exception of <newline>. An unquoted backslash pre- ceding a <newline> is treated as a line continuation, the two characters are simply removed. Single Quotes Enclosing characters in single quotes preserves the literal meaning of all the characters (except single quotes, making it impossible to put single quotes in a single-quoted string). Double Quotes Enclosing characters within double quotes preserves the literal meaning of all characters except dollar sign ($), backquote (`), and backslash (\). The backslash inside double quotes is historically weird, and serves to quote only the following characters (and these not in all con- texts): $ ` " \ <newline>, where a backslash newline is a line continuation as above. Otherwise it remains literal. Dollar Single Quotes ($'...') Note: this form of quoting is still somewhat experimental, and yet to be included in the POSIX standard. This implementation is based upon the current proposals for standardization, and is subject to change should the eventual adopted text differ. Enclosing characters in a matched pair of single quotes, with the first immediately preceded by an unquoted dollar sign ($) provides a quoting mechanism similar to single quotes, except that within the sequence of characters, any backslash (\), is an escape character, which causes the following character to be treated specially. Only a subset of the char- acters that can occur in the string are defined after a backslash, others are reserved for future definition, and currently generate a syntax error if used. The escape sequences are modeled after the similar sequences in strings in the C programming language, with some extensions. The following characters are treated literally when following the escape character (backslash): \ ' " The sequence ``\\'' allows the escape character (backslash) to appear in the string literally. ``\''' allows a single quote character into the string, such an escaped single quote does not terminate the quoted string. ``\"'' is for compatibility with C strings, the double quote has no special meaning in a shell C-style string, and does not need to be escaped, but may be. A newline following the escape character is treated as a line continua- tion, like the same sequence in a double quoted string, or when not quoted - the two characters, the backslash escape and the newline, are removed from the input string. The following characters, when escaped, are converted in a manner similar to the way they would be in a string in the C language: a b e f n r t v An escaped `a' generates an alert (or `BEL') character, that is, control- G, or 0x07. In a similar way, `b' is backspace (0x08), `e' (an extension to C) is escape (0x1B), `f' is form feed (0x0C), `n' is newline (or line feed, 0x0A), `r' is return (0x0D), `t' is horizontal tab (0x09), and `v' is vertical tab (0x13). In addition to those there are 5 forms that need additional data, which is obtained from the subsequent characters. An escape (\) followed by one, two or three, octal digits (`0'..`7') is processed to form an 8 bit character value. If only one or two digits are present, the following character must be something other than an octal digit. It is safest to always use all 3 digits, with leading zeros if needed. If all three dig- its are present, the first must be one of `0'..`3'. An escape followed by `x' (lower case only) can be followed by one or two hexadecimal digits (`0'..`9', `A'..`F', or `a'..`f'.) As with octal, if only one hex digit is present, the following character must be something other than a hex digit, so always giving 2 hex digits is best. However, unlike octal, it is unspecified in the standard how many hex digits can be consumed. This sh takes at most two, but other shells will continue consuming characters as long as they remain valid hex digits. Conse- quently, users should ensure that the character following the hex escape sequence is something other than a hex digit. One way to achieve this is to end the $'...' string immediately after the final hex digit, and then, immediately start another, so $'\x33'$'4...' always gives the character with value 0x33 (`3'), followed by the charac- ter `4', whereas $'\x334' in some other shells would be the hex value 0x334 (10, or more, bits). There are two escape sequences beginning with `\u' or `\U'. The former is followed by from 1 to 4 hex digits, the latter by from 1 to 8 hex dig- its. Leading zeros can be used to pad the sequences to the maximum per- mitted length, to avoid any possible ambiguity problem with the following character, and because there are some shells that insist on exactly 4 (or 8) hex digits. These sequences are evaluated to form the value of a Uni- code code point, which is then encoded into UTF-8 form, and entered into the string. (The code point should be converted to the appropriate code point value for the corresponding character in the character set given by the current locale, or perhaps the locale in use when the shell was started, but is not... currently.) Not all values that are possible to write are valid, values that specify (known) invalid Unicode code points will be rejected, or simply produce `?'. Lastly, as another addition to what is available in C, the escape charac- ter (backslash), followed by `c' (lower case only) followed by one addi- tional character, which must be an alphabetic character (a letter), or one of the following: @ [ \ ] ^ _ ? Other than `\c?' the value obtained is the least significant 5 bits of the ASCII value of the character following the `\c' escape sequence. That is what is commonly known as the ``control'' character obtained from the given character. The escape sequence `\c?' yields the ASCII DEL character (0x7F). Note that to obtain the ASCII FS character (0x1C) this way, (that is control-\) the trailing `\' must be escaped itself, and so for this one case, the full escape sequence is ``\c\\''. The sequence ``\c\X'' where `X' is some character other than `\' is reserved for future use, its meaning is unspecified. In this sh an error is gener- ated. If any of the preceding escape sequences generate the value `\0' (a NUL character) that character, and all that follow in the same $'...' string, are omitted from the resulting word. After the $'...' string has had any included escape sequences converted, it is treated as if it had been a single quoted string. Reserved Words Reserved words are words that have special meaning to the shell and are recognized at the beginning of a line and after a control operator. The following are reserved words: ! { } case do done elif else esac fi for if in then until while Their meanings are discussed later. Aliases An alias is a name and corresponding value set using the alias built-in command. Whenever a reserved word (see above) may occur, and after checking for reserved words, the shell checks the word to see if it matches an alias. If it does, it replaces it in the input stream with its value. For example, if there is an alias called ``lf'' with the value ``ls -F'', then the input: lf foobar <return> would become ls -F foobar <return> Aliases provide a convenient way for naive users to create shorthands for commands without having to learn how to create functions with arguments. They can also be used to create lexically obscure code. This use is strongly discouraged. Commands The shell interprets the words it reads according to a language, the specification of which is outside the scope of this man page (refer to the BNF in the POSIX 1003.2 document). Essentially though, a line is read and if the first word of the line (or after a control operator) is not a reserved word, then the shell has recognized a simple command. Otherwise, a complex command or some other special construct may have been recognized. Simple Commands If a simple command has been recognized, the shell performs the following actions: 1. Leading words of the form ``name=value'' are stripped off, the value is expanded, as described below, and the results are assigned to the environment of the simple command. Redirect- ion operators and their arguments (as described below) are stripped off and saved for processing in step 3 below. 2. The remaining words are expanded as described in the Word Expansions section below. The first remaining word is consid- ered the command name and the command is located. Any remain- ing words are considered the arguments of the command. If no command name resulted, then the ``name=value'' variable assignments recognized in item 1 affect the current shell. 3. Redirections are performed, from first to last, in the order given, as described in the next section. Redirections Redirections are used to change where a command reads its input or sends its output. In general, redirections open, close, or duplicate an exist- ing reference to a file. The overall format used for redirection is: [n]redir-op file where redir-op is one of the redirection operators mentioned previously. A list of the possible redirections, and their meanings, follows. The [n] is an optional number, as in `3' (not `[3]'), that refers to a file descriptor. If present it must occur unquoted, immediately before the redirection operator, with no intervening white space, and becomes a part of that operator. If file descriptor n was open prior to the redi- rection, its previous use is closed. All redirections have a single word file argument following the operator (white space is allowed between the redirection operator and file), though it is sometimes expressed as n2. That argument is expanded (see Word Expansions below) using tilde expansion, parameter expansion, arith- metic expansion, command substitution and quote removal to produce the path name (or file descriptor) to be used. No field splitting or path- name expansion takes place. In the list below, where the file is given as n2 the result of the expansions must be a number which refers to a suitable open file descriptor. [n]> file Redirect standard output (or n) to file. [n]>| file The same, but override the -C option. [n]>> file Append standard output (or n) to file. [n]< file Redirect standard input (or n) from file. [n1]<& n2 Redirect standard input (or n1) from a duplicate of file descriptor n2. [n]<& - Close standard input (or n). Note that the `-' is minus sign (or hyphen) given literally or resulting from the expansion of file (or n2) for this format. When given literally there is usually no space between the redirection operator and the `-', though that is just a convention. [n1]>& n2 Redirect standard output (or n1) to be a duplicate of n2. [n]>& - Close standard output (or n). [n]<> file Open file for reading and writing on standard input (or n). The following redirection is often called a ``here-document''. [n]<< delimiter ... here-doc-text ... delimiter The ``here-doc-text'' starts immediately after the next unquoted newline character following the here-document redirection operator. If there is more than one here-document redirection on the same line, then the text for the first (from left to right) is read first, and subsequent here- doc-text for later here-document redirections follows immediately after, until all such redirections have been processed. All the text on successive lines up to the delimiter, which must appear on a line by itself, with nothing other than an immediately following newline, is saved away and made available to the command on standard input, or file descriptor n if it is specified. If the delimiter as specified on the initial line is quoted, then the here-doc-text is treated literally; otherwise, the text is treated much like a double quoted string, except that `"' characters have no special meaning, and are not escaped by `\', and is subjected to parameter expansion, command substitution, and arithmetic expansion as described in the Word Expansions section below. If the operator is <<- instead of <<, then leading tabs in all lines in the here-doc-text, including before the end delimiter, are stripped. If the delimiter is not quoted, lines in here- doc-text that end with an unquoted \ are joined to the following line, the \ and following newline are simply removed while reading the here- document, which thus guarantees that neither of those lines can be the end delimiter. It is a syntax error for the end of the input file (or string) to be reached before the delimiter is encountered. Search and Execution There are three types of commands: shell functions, built-in commands, and normal programs -- and the command is searched for (by name) in that order. A command that contains a slash `/' in its name is always a nor- mal program. They each are executed in a different way. When a shell function is executed, all of the shell positional parameters (note: excluding 0, which is a special, not positional, parameter, and remains unchanged) are set to the arguments of the shell function. The variables which are explicitly placed in the environment of the command (by placing assignments to them before the function name) are made local to the function and are set to the values given, and exported for the benefit of programs executed with the function. Then the command given in the function definition is executed. The positional parameters, and local variables, are restored to their original values when the command completes. This all occurs within the current shell, and the function can alter variables, or other settings, of the shell, but not the posi- tional parameters nor their related special parameters. Shell built-ins are executed internally to the shell, without spawning a new process. Otherwise, if the command name doesn't match a function or built-in, the command is searched for as a normal program in the file system (as described in the next section). When a normal program is executed, the shell runs the program, passing the arguments and the environment to the program. If the program is not a normal executable file, and if it does not begin with the ``magic number'' whose ASCII representation is ``#!'', so execve(2) returns ENOEXEC then) the shell will interpret the program in a sub-shell. The child shell will reinitialize itself in this case, so that the effect will be as if a new shell had been invoked to handle the ad-hoc shell script, except that the location of hashed commands located in the parent shell will be remembered by the child. Note that previous versions of this document and the source code itself misleadingly and sporadically refer to a shell script without a magic number as a ``shell procedure''. Path Search When locating a command, the shell first looks to see if it has a shell function by that name. Then it looks for a built-in command by that name. If a built-in command is not found, one of two things happen: 1. Command names containing a slash are simply executed without per- forming any searches. 2. Otherwise, the shell searches each entry in PATH in turn for the command. The value of the PATH variable should be a series of entries separated by colons. Each entry consists of a directory name. The current directory may be indicated implicitly by an empty directory name, or explicitly by a single period. If a directory searched contains an executable file with the same name as the com- mand given, the search terminates, and that program is executed. Command Exit Status Each command has an exit status that can influence the behavior of other shell commands. The paradigm is that a command exits with zero in normal cases, or to indicate success, and non-zero for failure, error, or a false indication. The man page for each command should indicate the var- ious exit codes and what they mean. Additionally, the built-in commands return exit codes, as does an executed shell function. If a command consists entirely of variable assignments then the exit sta- tus of the command is that of the last command substitution if any, oth- erwise 0. If redirections are present, and any fail to be correctly performed, any command present is not executed, and an exit status of 2 is returned. Complex Commands Complex commands are combinations of simple commands with control opera- tors or reserved words, together creating a larger complex command. Overall, a shell program is a: list Which is a sequence of one or more AND-OR lists. AND-OR list is a sequence of one or more pipelines. pipeline is a sequence of one or more commands. command is one of a simple command, a compound command, or a function definition. simple command has been explained above, and is the basic building block. compound command provides mechanisms to group lists to achieve different effects. function definition allows new simple commands to be created as groupings of existing commands. Unless otherwise stated, the exit status of a list is that of the last simple command executed by the list. Pipelines A pipeline is a sequence of one or more commands separated by the control operator `|', and optionally preceded by the ``!'' reserved word. Note that `|' is an operator, and so is recognized anywhere it appears unquoted, it does not require surrounding white space or other syntax elements. On the other hand ``!'' being a reserved word, must be sepa- rated from adjacent words by white space (or other operators, perhaps redirects) and is only recognized as the reserved word when it appears in a command word position (such as at the beginning of a pipeline.) The standard output of all but the last command in the sequence is con- nected to the standard input of the next command. The standard output of the last command is inherited from the shell, as usual, as is the stan- dard input of the first command. The format for a pipeline is: [!] command1 [| command2 ...] The standard output of command1 is connected to the standard input of command2. The standard input, standard output, or both of each command is considered to be assigned by the pipeline before any redirection spec- ified by redirection operators that are part of the command are per- formed. If the pipeline is not in the background (discussed later), the shell waits for all commands to complete. The commands in a pipeline can either be simple commands, or one of the compound commands described below. The simplest case of a pipeline is a single simple command. If the pipefail option was set when a pipeline was started, the pipeline status is the status of the last (lexically last, i.e.: rightmost) com- mand in the pipeline to exit with non-zero exit status, or zero, if, and only if, all commands in the pipeline exited with a status of zero. If the pipefail option was not set, which is the default state, the pipeline status is the exit status of the last (rightmost) command in the pipe- line, and the exit status of any other commands in the pipeline is ignored. If the reserved word ``!'' precedes the pipeline, the exit status becomes the logical NOT of the pipeline status as determined above. That is, if the pipeline status is zero, the exit status is 1; if the pipeline status is other than zero, the exit status is zero. If there is no ``!'' reserved word, the pipeline status becomes the exit status. Because pipeline assignment of standard input or standard output or both takes place before redirection, it can be modified by redirection. For example: $ command1 2>&1 | command2 sends both the standard output and standard error of command1 to the standard input of command2. Note that unlike some other shells, each process in the pipeline is a child of the invoking shell (unless it is a shell built-in, in which case it executes in the current shell -- but any effect it has on the environ- ment is wiped). A pipeline is a simple case of an AND-OR-list (described below.) A ; or <newline> terminator causes the preceding pipeline, or more generally, the preceding AND-OR-list to be executed sequentially; that is, the shell executes the commands, and waits for them to finish before proceeding to following commands. An & terminator causes asynchronous (background) execution of the preceding AND-OR-list (see the next paragraph below). The exit status of an asynchronous AND-OR-list is zero. The actual sta- tus of the commands, after they have completed, can be obtained using the wait built-in command described later. Background Commands -- & If a command, pipeline, or AND-OR-list is terminated by the control oper- ator ampersand (&), the shell executes the command asynchronously -- that is, the shell does not wait for the command to finish before executing the next command. The format for running a command in background is: command1 & [command2 & ...] If the shell is not interactive, the standard input of an asynchronous command is set to /dev/null. The process identifier of the most recent command started in the background can be obtained from the value of the special parameter ``!'' (see Special Parameters) provided it is accessed before the next asynchronous command is started. Lists -- Generally Speaking A list is a sequence of one or more commands separated by newlines, semi- colons, or ampersands, and optionally terminated by one of these three characters. A shell program, which includes the commands given to an interactive shell, is a list. Each command in such a list is executed when it is fully parsed. Another use of a list is as a complete-command, which is parsed in its entirety, and then later the commands in the list are executed only if there were no parsing errors. The commands in a list are executed in the order they are written. If command is followed by an ampersand, the shell starts the command and immediately proceeds to the next command; otherwise it waits for the com- mand to terminate before proceeding to the next one. A newline is equiv- alent to a `;' when no other operator is present, and the command being input could syntactically correctly be terminated at the point where the newline is encountered, otherwise it is just whitespace. AND-OR Lists (Short-Circuit List Operators) ``&&'' and ``||'' are AND-OR list operators. After executing the com- mands that precede the ``&&'' the subsequent command is executed if and only if the exit status of the preceding command(s) is zero. ``||'' is similar, but executes the subsequent command if and only if the exit sta- tus of the preceding command is nonzero. If a command is not executed, the exit status remains unchanged and the following AND-OR list operator (if any) uses that status. ``&&'' and ``||'' both have the same prior- ity. Note that these operators are left-associative, so true || echo bar && echo baz writes ``baz'' and nothing else. This is not the way it works in C. Flow-Control Constructs -- if, while, until, for, case These commands are instances of compound commands. The syntax of the if command is if list then list [elif list then list] ... [else list] fi The first list is executed, and if the exit status of that list is zero, the list following the then is executed. Otherwise the list after an elif (if any) is executed and the process repeats. When no more elif reserved words, and accompanying lists, appear, the list after the else reserved word, if any, is executed. The syntax of the while command is while list do list done The two lists are executed repeatedly while the exit status of the first list is zero. The until command is similar, but has the word until in place of while, which causes it to repeat until the exit status of the first list is zero. The syntax of the for command is for variable [in word ...] do list done The words are expanded, or "$@" if in (and the following words) is not present, and then the list is executed repeatedly with the variable set to each word in turn. If in appears after the variable, but no words are present, the list is not executed, and the exit status is zero. do and done may be replaced with `{' and `}', but doing so is non-standard and not recommended. The syntax of the break and continue commands is break [num] continue [num] break terminates the num innermost for, while, or until loops. continue breaks execution of the num-1 innermost for, while, or until loops, and then continues with the next iteration of the enclosing loop. These are implemented as special built-in commands. The parameter num, if given, must be an unsigned positive integer (greater than zero). If not given, 1 is used. The syntax of the case command is case word in [(] pattern) [list] ;& [(] pattern) [list] ;; ... esac The pattern can actually be one or more patterns (see Shell Patterns described later), separated by ``|'' characters. word is expanded and matched against each pattern in turn, from first to last, with each pattern being expanded just before the match is attempted. When a match is found, pattern comparisons cease, and the associated list, if given, is evaluated. If the list is terminated with ``;&'' execution then falls through to the following list, if any, with- out evaluating its pattern, or attempting a match. When a list termi- nated with ``;;'' has been executed, or when esac is reached, execution of the case statement is complete. The exit status is that of the last command executed from the last list evaluated, if any, or zero otherwise. Grouping Commands Together Commands may be grouped by writing either (list) or { list; } These also form compound commands. Note that while parentheses are operators, and do not require any extra syntax, braces are reserved words, so the opening brace must be followed by white space (or some other operator), and the closing brace must occur in a position where a new command word might otherwise appear. The first of these executes the commands in a sub-shell. Built-in com- mands grouped into a (list) will not affect the current shell. The sec- ond form does not fork another shell so is slightly more efficient, and allows for commands which do affect the current shell. Grouping commands together this way allows you to redirect their output as though they were one program: { echo -n "hello " ; echo "world" ; } > greeting Note that ``}'' must follow a control operator (here, ``;'') so that it is recognized as a reserved word and not as another command argument. Functions The syntax of a function definition is name() command [redirect ...] A function definition is an executable statement; when executed it installs a function named name and returns an exit status of zero. The command is normally a list enclosed between ``{'' and ``}''. The stan- dard syntax also allows the command to be any of the other compound com- mands, including a sub-shell, all of which are supported. As an exten- sion, this shell also allows a simple command (or even another function definition) to be used, though users should be aware this is non-standard syntax. This means that l() ls "$@" works to make ``l'' an alternative name for the ls command. If the optional redirect, (see Redirections), which may be of any of the normal forms, is given, it is applied each time the function is called. This means that a simple ``Hello World'' function might be written (in the extended syntax) as: hello() cat <<EOF Hello World! EOF To be correctly standards conforming this should be re-written as: hello() { cat; } <<EOF Hello World! EOF Note the distinction between those forms, and hello() { cat <<EOF Hello World! EOF } which reads and processes the here-document each time the shell executes the function, and which applies that input only to the cat command, not to any other commands that might appear in the function. Variables may be declared to be local to a function by using the local command. This should usually appear as the first statement of a func- tion, though local is an executable command which can be used anywhere in a function. See Built-ins below for its definition. The function completes after having executed command with exit status set to the status returned by command. If command is a compound-command it can use the return command (see Built-ins below) to finish before com- pleting all of command. Variables and Parameters The shell maintains a set of parameters. A parameter denoted by a name is called a variable. When starting up, the shell turns all the environ- ment variables into shell variables, and exports them. New variables can be set using the form name=value Variables set by the user must have a name consisting solely of alphabet- ics, numerics, and underscores -- the first of which must not be numeric. A parameter can also be denoted by a number or a special character as explained below. Positional Parameters A positional parameter is a parameter denoted by a number (n > 0). The shell sets these initially to the values of its command line arguments that follow the name of the shell script. The set built-in can also be used to set or reset them, and shift can be used to manipulate the list. To refer to the 10th (and later) positional parameters, the form ${n} must be used. Without the braces, a digit following ``$'' can only refer to one of the first 9 positional parameters, or the special parameter 0. The word ``$10'' is treated identically to ``${1}0''. Special Parameters A special parameter is a parameter denoted by one of the following spe- cial characters. The value of the parameter is listed next to its char- acter. * Expands to the positional parameters, starting from one. When the expansion occurs within a double-quoted string it expands to a single field with the value of each parameter separated by the first character of the IFS variable, or by a <space> if IFS is unset. @ Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, each posi- tional parameter expands as a separate argument. If there are no positional parameters, the expansion of @ generates zero arguments, even when $@ is double-quoted. What this basically means, for example, is if $1 is ``abc'' and $2 is ``def ghi'', then "$@" expands to the two arguments: "abc" "def ghi" # Expands to the number of positional parameters. ? Expands to the exit status of the most recent pipeline. - (hyphen, or minus) Expands to the current option flags (the single-letter option names concatenated into a string) as specified on invocation, by the set built-in command, or implicitly by the shell. $ Expands to the process ID of the invoked shell. A sub-shell retains the same value of $ as its parent. ! Expands to the process ID of the most recent background com- mand executed from the current shell. For a pipeline, the process ID is that of the last command in the pipeline. If no background commands have yet been started by the shell, then ``!'' will be unset. Once set, the value of ``!'' will be retained until another background command is started. 0 (zero) Expands to the name of the shell or shell script. Word Expansions This section describes the various expansions that are performed on words. Not all expansions are performed on every word, as explained later. Tilde expansions, parameter expansions, command substitutions, arithmetic expansions, and quote removals that occur within a single word expand to a single field. It is only field splitting or pathname expansion that can create multiple fields from a single word. The single exception to this rule is the expansion of the special parameter @ within double quotes, as was described above. The order of word expansion is: 1. Tilde Expansion, Parameter Expansion, Command Substitution, Arith- metic Expansion (these all occur at the same time). 2. Field Splitting is performed on fields generated by step (1) unless the IFS variable is null. 3. Pathname Expansion (unless set -f is in effect). 4. Quote Removal. The $ character is used to introduce parameter expansion, command substi- tution, or arithmetic evaluation. Tilde Expansion (substituting a user's home directory) A word beginning with an unquoted tilde character (~) is subjected to tilde expansion. Provided all of the subsequent characters in the word are unquoted up to an unquoted slash (/) or when in an assignment or not in posix mode, an unquoted colon (:), or if neither of those appear, the end of the word, they are treated as a user name and are replaced with the pathname of the named user's home directory. If the user name is missing (as in ~/foobar), the tilde is replaced with the value of the HOME variable (the current user's home directory). In variable assignments, an unquoted tilde immediately after the assign- ment operator (=), and each unquoted tilde immediately after an unquoted colon in the value to be assigned is also subject to tilde expansion as just stated. Parameter Expansion The format for parameter expansion is as follows: ${expression} where expression consists of all characters until the matching `}'. Any `}' escaped by a backslash or within a quoted string, and characters in embedded arithmetic expansions, command substitutions, and variable expansions, are not examined in determining the matching `}'. The simplest form for parameter expansion is: ${parameter} The value, if any, of parameter is substituted. The parameter name or symbol can be enclosed in braces, which are optional in this simple case, except for positional parameters with more than one digit or when parameter is followed by a character that could be interpreted as part of the name. If a parameter expansion occurs inside double quotes: 1. pathname expansion is not performed on the results of the expansion; 2. field splitting is not performed on the results of the expansion, with the exception of the special rules for @. In addition, a parameter expansion where braces are used, can be modified by using one of the following formats. If the `:' is omitted in the fol- lowing modifiers, then the test in the expansion applies only to unset parameters, not null ones. ${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. In all cases, the final value of parameter is substituted. Only variables, not positional parameters or special parameters, can be assigned in this way. ${parameter:?[word]} Indicate Error if Null or Unset. If parameter is unset or null, the expansion of word (or a message indicating it is unset if word is omitted) is writ- ten to standard error and a non-interactive shell exits with a nonzero exit status. An interactive shell will not exit, but any associated command(s) will not be executed. If the parameter is set, its value is substituted. ${parameter:+word} Use Alternative Value. If parameter is unset or null, null is substituted; otherwise, the expansion of word is substituted. The value of parameter is not used in this expansion. ${#parameter} String Length. The length in characters of the value of parameter. The following four varieties of parameter expansion provide for substring processing. In each case, pattern matching notation (see Shell Patterns), rather than regular expression notation, is used to evaluate the patterns. If parameter is * or @, the result of the expansion is unspecified. Enclosing the full parameter expansion string in double quotes does not cause the following four varieties of pattern characters to be quoted, whereas quoting characters within the braces has this effect. ${parameter%word} Remove Smallest Suffix Pattern. The word is expanded to produce a pattern. The parameter expansion then results in parameter, with the smallest portion of the suffix matched by the pat- tern deleted. If the word is to start with a `%' character, it must be quoted. ${parameter%%word} Remove Largest Suffix Pattern. The word is expanded to produce a pattern. The parameter expansion then results in parameter, with the largest portion of the suffix matched by the pattern deleted. The ``%%'' pattern operator only produces different results from the ``%'' operator when the pattern contains at least one unquoted `*'. ${parameter#word} Remove Smallest Prefix Pattern. The word is expanded to produce a pattern. The parameter expansion then results in parameter, with the smallest portion of the prefix matched by the pat- tern deleted. If the word is to start with a `#' character, it must be quoted. ${parameter##word} Remove Largest Prefix Pattern. The word is expanded to produce a pattern. The parameter expansion then results in parameter, with the largest portion of the prefix matched by the pattern deleted. This has the same relationship with the ``#'' pattern operator as ``%%'' has with ``%''. Command Substitution Command substitution allows the output of a command to be substituted in place of the command (and surrounding syntax). Command substitution occurs when a word contains a command list enclosed as follows: $(list) or the older (``backquoted'') version, which is best avoided: `list` See the section Complex Commands above for the definition of list. The shell expands the command substitution by executing the list in a sub-shell environment and replacing the command substitution with the standard output of the list after removing any sequence of one or more <newline>s from the end of the substitution. (Embedded <newline>s before the end of the output are not removed; however, during field splitting, they may be used to separate fields (as spaces usually are) depending on the value of IFS and any quoting that is in effect.) Note that if a command substitution includes commands to be run in the background, the sub-shell running those commands will only wait for them to complete if an appropriate wait command is included in the command list. However, the shell in which the result of the command substitution will be used will wait for both the sub-shell to exit and for the file descriptor that was initially standard output for the command substitu- tion sub-shell to be closed. In some circumstances this might not happen until all processes started by the command substitution have finished. Arithmetic Expansion Arithmetic expansion provides a mechanism for evaluating an arithmetic expression and substituting its value. The format for arithmetic expan- sion is as follows: $((expression)) The expression in an arithmetic expansion is treated as if it were in double quotes, except that a double quote character inside the expression is just a normal character (it quotes nothing.) The shell expands all tokens in the expression for parameter expansion, command substitution, and quote removal (the only quoting character is the backslash `\', and only when followed by another `\', a dollar sign `$', a backquote ``' or a newline.) Next, the shell evaluates the expanded result as an arithmetic expression and substitutes the calculated value of that expression. Arithmetic expressions use a syntax similar to that of the C language, and are evaluated using the `intmax_t' data type (this is an extension to POSIX, which requires only `long' arithmetic.) Shell variables may be referenced by name inside an arithmetic expression, without needing a ``$'' sign. Variables that are not set, or which have an empty (null string) value, used this way evaluate as zero (that is, ``x'' in arith- metic, as an R-Value, is evaluated as ``${x:-0}'') unless the sh -u flag is set, in which case a reference to an unset variable is an error. Note that unset variables used in the ${var} form expand to a null string, which might result in syntax errors. Referencing the value of a variable which is not numeric is an error. All of the C expression operators applicable to integers are supported, and operate as they would in a C expression. Use white space, or paren- theses, to disambiguate confusing syntax, otherwise, as in C, the longest sequence of consecutive characters which make a valid token (operator, variable name, or number) is taken to be that token, even if the token designated cannot be used and a different interpretation could produce a successful parse. This means, as an example, that ``a+++++b'' is parsed as the gibberish sequence ``a ++ ++ + b'', rather than as the valid alternative ``a ++ + ++ b''. Similarly, separate the `,' operator from numbers with white space to avoid the possibility of confusion with the decimal indicator in some locales (though fractional, or floating-point, numbers are not supported in this implementation.) It should not be necessary to state that the C operators which operate on, or produce, pointer types, are not supported. Those include unary ``*'' and ``&'' and the struct and array referencing binary operators: ``.'', ``->'' and ``[''. White Space Splitting (Field Splitting) After parameter expansion, command substitution, and arithmetic expansion the shell scans the results of expansions and substitutions that did not occur in double quotes, and ``$@'' even if it did, for field splitting and multiple fields can result. The shell treats each character of the IFS as a delimiter and uses the delimiters to split the results of parameter expansion and command sub- stitution into fields. Non-whitespace characters in IFS are treated strictly as parameter sepa- rators. So adjacent non-whitespace IFS characters will produce empty parameters. On the other hand, any sequence of whitespace characters that occur in IFS (known as IFS whitespace) can occur, leading and trail- ing IFS whitespace, and any IFS whitespace surrounding a non whitespace IFS delimiter, is removed. Any sequence of IFS whitespace characters without a non-whitespace IFS delimiter acts as a single field separator. If IFS is unset it is assumed to contain space, tab, and newline, all of which are IFS whitespace characters. If IFS is set to a null string, there are no delimiters, and no field splitting occurs. Pathname Expansion (File Name Generation) Unless the -f flag is set, file name generation is performed after word splitting is complete. Each word is viewed as a series of patterns, sep- arated by slashes. The process of expansion replaces the word with the names of all existing files whose names can be formed by replacing each pattern with a string that matches the specified pattern. There are two restrictions on this: first, a pattern cannot match a string containing a slash, and second, a pattern cannot match a string starting with a period unless the first character of the pattern is a period. The next section describes the patterns used for both Pathname Expansion and the case com- mand. Shell Patterns A pattern consists of normal characters, which match themselves, and meta-characters. The meta-characters are ``!'', ``*'', ``?'', and ``[''. These characters lose their special meanings if they are quoted. When command or variable substitution is performed and the dollar sign or backquotes are not double-quoted, the value of the variable or the output of the command is scanned for these characters and they are turned into meta-characters. An asterisk (``*'') matches any string of characters. A question mark (``?'') matches any single character. A left bracket (``['') introduces a character class. The end of the character class is indicated by a right bracket (``]''); if this ``]'' is missing then the ``['' matches a ``['' rather than introducing a character class. A character class matches any of the characters between the square brackets. A named class of characters (see wctype(3)) may be specified by surrounding the name with (``[:'') and (``:]''). For example, (``[[:alpha:]]'') is a shell pattern that matches a single letter. A range of characters may be spec- ified using a minus sign (``-''). The character class may be comple- mented by making an exclamation mark (``!'') the first character of the character class. To include a ``]'' in a character class, make it the first character listed (after the ``!'', if any). To include a ``-'', make it the first (after !) or last character listed. If both ``]'' and ``-'' are to be included, the ``]'' must be first (after !) and the ``-'' last, in the character class. Built-ins This section lists the built-in commands which are built-in because they need to perform some operation that can't be performed by a separate process. Or just because they traditionally are. In addition to these, there are several other commands that may be built in for efficiency (e.g. printf(1), echo(1), test(1), etc). : [arg ...] A null command that returns a 0 (true) exit value. Any arguments or redirects are evaluated, then ignored. . file The dot command reads and executes the commands from the specified file in the current shell environment. The file does not need to be executable and is looked up from the directories listed in the PATH variable if its name does not contain a directory separator (`/'). The return command (see below) can be used for a premature return from the sourced file. The POSIX standard has been unclear on how loop control keywords (break and continue) behave across a dot command boundary. This implementation allows them to control loops surrounding the dot command, but obviously such behavior should not be relied on. It is now permitted by the standard, but not required. alias [name[=string ...]] If name=string is specified, the shell defines the alias name with value string. If just name is specified, the value of the alias name is printed. With no arguments, the alias built-in prints the names and values of all defined aliases (see unalias). bg [job ...] Continue the specified jobs (or the current job if no jobs are given) in the background. command [-pVv] command [arg ...] Execute the specified command but ignore shell functions when searching for it. (This is useful when you have a shell function with the same name as a command.) -p search for command using a PATH that guarantees to find all the standard utilities. -V Do not execute the command but search for the command and print the resolution of the command search. This is the same as the type built-in. -v Do not execute the command but search for the command and print the absolute pathname of utilities, the name for built-ins or the expansion of aliases. cd [-Pe] [directory [replace]] Switch to the specified directory (default $HOME). If replace is specified, then the new directory name is generated by replacing the first occurrence of the string directory in the current direc- tory name with replace. Otherwise if directory is `-', then the current working directory is changed to the previous current work- ing directory as set in OLDPWD. Otherwise if an entry for CDPATH appears in the environment of the cd command or the shell variable CDPATH is set and the directory name does not begin with a slash, and its first (or only) component isn't dot or dot dot, then the directories listed in CDPATH will be searched for the specified directory. The format of CDPATH is the same as that of PATH. The -P option (which is the unalterable default in this sh) instructs the shell to change to the directory specified (or determined) and if successful update PWD with the new physical directory path. That is the path name, not traversing any sym- bolic links, of the altered working directory of the shell. The -e option alters the interpretation of the exit status. cd will exit with status 0 if successful. If the directory was suc- cessfully changed, but PWD was unable to be updated, cd will exit with status 1 if the -e option was given, and status 0 otherwise. Upon any other error, including usage errors, and failing to suc- cessfully change directory, cd will exit with status 2. When the directory changes, and PWD is updated, the variable OLDPWD is set to the working directory (Ns PWD) as it was before the change. Some shells also support a -L option, which instructs the shell to update PWD with the logical path and to change the current direc- tory accordingly. This is not supported. In an interactive shell, or if the posix option is set, the cd command will print out the name of the directory that it actually switched to (that is, the pathname passed to the successful chdir(2) system call) if this is different from the name that the user gave, or if the cdprint option is set. The destination may be different because a non-empty element of the CDPATH mechanism was used, or because the replace argument was used, or because the directory parameter was specified as ``-''. eval string ... Concatenate all the arguments with spaces. Then re-parse and exe- cute the command. exec [command [arg ...]] Unless command is omitted, the shell process is replaced with the specified program (which must be a real program, not a shell built-in or function). Any redirections on the exec command are marked as permanent, so that they are not undone when the exec command finishes. When the posix option is not set, file descrip- tors created via such redirections are marked close-on-exec (see open(2) O_CLOEXEC or fcntl(2) F_SETFD / FD_CLOEXEC), unless the descriptors refer to the standard input, output, or error (file descriptors 0, 1, 2). Traditionally Bourne-like shells (except ksh(1)), made those file descriptors available to exec'ed pro- cesses. To be assured the close-on-exec setting is off, redirect the descriptor to (or from) itself, either when invoking a command for which the descriptor is wanted open, or by using exec (perhaps the same exec as opened it, after the open) to leave the descrip- tor open in the shell and pass it to all commands invoked subse- quently. Alternatively, see the fdflags command below, which can set, or clear, this, and other, file descriptor flags. exit [exitstatus] Terminate the shell process. If exitstatus is given it is used as the exit status of the shell; otherwise the exit status of the preceding command (the current value of $?) is used. export [-nx] name[=value] ... export [-x] [-p [name ...]] export -q [-x] name ... With no options, but one or more names, the specified names are exported so that they will appear in the environment of subsequent commands. With -n the specified names are un-exported. Variables can also be un-exported using the unset built in command. With -x (exclude) the specified names are marked not to be exported, and any that had been exported, will be un-exported. Later attempts to export the variable will be refused. Note this does not pre- vent explicitly exporting a variable to a single command, script or function by preceding that command invocation by a variable assignment to that variable, provided the variable is not also read-only. That is export -x FOO # FOO will now not be exported by default export FOO # this command will fail (non-fatally) FOO=some_value my_command still passes the value (FOO=some_value) to my_command through the environment. The shell allows the value of a variable to be set at the same time it is exported (or unexported, etc) by writing export [-nx] name=value With no arguments the export command lists the names of all set exported variables, or if -x was given, all set variables marked not for export. With the -p option specified, the output will be formatted suitably for non-interactive use, and unset variables are included. When -p is given, variable names, but not values, may also be given, in which case output is limited to the vari- ables named. With -q and a list of variable names, the export command will exit with status 0 if all the named variables have been marked for export, or 1 if any are not so marked. If -x is also given, the test is instead for variables marked not to be exported. Other than with -q, the export built-in exits with status 0, unless an attempt is made to export a variable which has been marked as unavailable for export, in which cases it exits with status 1. In all cases if an invalid option, or option combina- tion, is given, or an invalid variable name is present, export will write a message to the standard error output, and exit with a non-zero status. A non-interactive shell will terminate. Note that there is no restriction upon exporting, or un-exporting, read-only variables. The no-export flag can be reset by unsetting the variable and creating it again - provided the variable is not also read-only. fc [-e editor] [first [last]] fc -l [-nr] [first [last]] fc -s [old=new] [first] The fc built-in lists, or edits and re-executes, commands previ- ously entered to an interactive shell. -e editor Use the editor named by editor to edit the commands. The editor string is a command name, subject to search via the PATH variable. The value in the FCEDIT variable is used as a default when -e is not specified. If FCEDIT is null or unset, the value of the EDITOR variable is used. If EDITOR is null or unset, ed(1) is used as the editor. -l (ell) List the commands rather than invoking an editor on them. The commands are written in the sequence indicated by the first and last operands, as affected by -r, with each com- mand preceded by the command number. -n Suppress command numbers when listing with -l. -r Reverse the order of the commands listed (with -l) or edited (with neither -l nor -s). -s Re-execute the command without invoking an editor. first last Select the commands to list or edit. The number of previ- ous commands that can be accessed are determined by the value of the HISTSIZE variable. The value of first or last or both are one of the following: [+]number A positive number representing a command number; command numbers can be displayed with the -l option. -number A negative decimal number representing the command that was executed number of commands previously. For example, -1 is the immediately previous command. string A string indicating the most recently entered command that begins with that string. If the old=new operand is not also specified with -s, the string form of the first oper- and cannot contain an embedded equal sign. The following environment variables affect the execution of fc: FCEDIT Name of the editor to use. HISTSIZE The number of previous commands that are accessible. fg [job] Move the specified job or the current job to the foreground. A foreground job can interact with the user via standard input, and receive signals from the terminal. fdflags [-v] [fd ...] fdflags [-v] -s flags fd [...] Get or set file descriptor flags. The -v argument enables verbose printing, printing flags that are also off, and the flags of the file descriptor being set after setting. The -s flag interprets the flags argument as a comma separated list of file descriptor flags, each preceded with a ``+'' or a ``-'' indicating to set or clear the respective flag. Valid flags are: append, async, sync, nonblock, fsync, dsync, rsync, direct, nosigpipe, and cloexec. Unique abbreviations of these names, of at least 2 characters, may be used on input. See fcntl(2) and open(2) for more information. getopts optstring var The POSIX getopts command, not to be confused with the Bell Labs-derived getopt(1). The first argument should be a series of letters, each of which may be optionally followed by a colon to indicate that the option requires an argument. The variable specified is set to the parsed option. The getopts command deprecates the older getopt(1) utility due to its handling of arguments containing whitespace. The getopts built-in may be used to obtain options and their argu- ments from a list of parameters. When invoked, getopts places the value of the next option from the option string in the list in the shell variable specified by var and its index in the shell vari- able OPTIND. When the shell is invoked, OPTIND is initialized to 1. For each option that requires an argument, the getopts built- in will place it in the shell variable OPTARG. If an option is not allowed for in the optstring, then OPTARG will be unset. optstring is a string of recognized option letters (see getopt(3)). If a letter is followed by a colon, the option is expected to have an argument which may or may not be separated from it by whitespace. If an option character is not found where expected, getopts will set the variable var to a `?'; getopts will then unset OPTARG and write output to standard error. By specify- ing a colon as the first character of optstring all errors will be ignored. A nonzero value is returned when the last option is reached. If there are no remaining arguments, getopts will set var to the spe- cial option, ``--'', otherwise, it will set var to `?'. The following code fragment shows how one might process the argu- ments for a command that can take the options -a and -b, and the option -c, which requires an argument. while getopts abc: f do case $f in a | b) flag=$f;; c) carg=$OPTARG;; \?) echo $USAGE; exit 1;; esac done shift $((OPTIND - 1)) This code will accept any of the following as equivalent: cmd -acarg file file cmd -a -c arg file file cmd -carg -a file file cmd -a -carg -- file file hash [-rv] [command ...] The shell maintains a hash table which remembers the locations of commands. With no arguments whatsoever, the hash command prints out the contents of this table. Entries which have not been looked at since the last cd command are marked with an asterisk; it is possible for these entries to be invalid. With arguments, the hash command removes the specified commands from the hash table (unless they are functions) and then locates them. With the -v option, hash prints the locations of the com- mands as it finds them. The -r option causes the hash command to delete all the entries in the hash table except for functions. inputrc file Read the file to set key bindings as defined by editrc(5). jobid [-g|-j|-p] [job] With no flags, print the process identifiers of the processes in the job. If the job argument is omitted, the current job is used. Any of the ways to select a job may be used for job, including the `%' forms, or the process id of the job leader (``$!'' if the job was created in the background.) If one of the flags is given, then instead of the list of process identifiers, the jobid command prints: -g the process group, if one was created for this job, or nothing otherwise (the job is in the same process group as the shell.) -j the job identifier (using ``%n'' notation, where n is a num- ber) is printed. -p only the process id of the process group leader is printed. These flags are mutually exclusive. jobid exits with status 2 if there is an argument error, status 1, if with -g the job had no separate process group, or with -p there is no process group leader (should not happen), and otherwise exits with status 0. jobs [-l|-p] [job ...] Without job arguments, this command lists out all the background processes which are children of the current shell process. With job arguments, the listed jobs are shown instead. Without flags, the output contains the job identifier (see Job Control below), an indicator character if the job is the current or previous job, the current status of the job (running, suspended, or terminated suc- cessfully, unsuccessfully, or by a signal) and a (usually abbrevi- ated) command string. With the -l flag the output is in a longer form, with the process identifiers of each process (run from the top level, as in a pipe- line), and the status of each process, rather than the job status. With the -p flag, the output contains only the process identifier of the lead process. In an interactive shell, each job shown as completed in the output from the jobs command is implicitly waited for, and is removed from the jobs table, never to be seen again. In an interactive shell, when a background job terminates, the jobs command (with that job as an argument) is implicitly run just before outputting the next PS1 command prompt, after the job terminated. This indi- cates that the job finished, shows its status, and cleans up the job table entry for that job. Non-interactive shells need to exe- cute wait commands to clean up terminated background jobs. local [-INx] [variable | -] ... Define local variables for a function. Local variables have their attributes, and values, as they were before the local declaration, restored when the function terminates. With the -N flag, variables made local, are unset initially inside the function. Unless the -x flag is also given, such variables are also unexported. The -I flag, which is the default in this shell, causes the initial value and exported attribute of local variables to be inherited from the variable with the same name in the surrounding scope, if there is one. If there is not, the variable is initially unset, and not exported. The -N and -I flags are mutually exclusive, if both are given, the last speci- fied applies. The read-only and unexportable attributes are always inherited, if a variable with the same name already exists. The -x flag (lower case) causes the local variable to be exported, while the function runs, unless it has the unexportable attribute. This can also be accomplished by using the export command, giving the same variable names, after the local command. Making an existing read-only variable local is possible, but pointless. If an attempt is made to assign an initial value to such a variable, the local command fails, as does any later attempted assignment. If the readonly command is applied to a variable that has been declared local, the variable cannot be (further) modified within the function, or any other functions it calls, however when the function returns, the previous status (and value) of the variable is returned. Values may be given to local variables on the local command line in a similar fashion as used for export and readonly. These val- ues are assigned immediately after the initialization described above. Note that any variable references on the command line will have been expanded before local is executed, so expressions like local -N X=${X} are well defined, first $X is expanded, and then the command run is local -N X=old-value-of-X After arranging to preserve the old value and attributes, of X (``old-value-of X'') local unsets X, unexports it, and then assigns the ``old-value-of-X'' to X. The shell uses dynamic scoping, so that if you make the variable x local to function f, which then calls function g, references to the variable x made inside g will refer to the variable x declared inside f, not to the global variable named x. Another way to view this, is as if the shell just has one flat, global, namespace, in which all variables exist. The local com- mand conceptually copies the variable(s) named to unnamed tempo- rary variables, and when the function ends, copies them back again. All references to the variables reference the same global variables, but while the function is active, after the local com- mand has run, the values and attributes of the variables might be altered, and later, when the function completes, be restored. Note that the positional parameters 1, 2, ... (see Positional Parameters), and the special parameters #, * and @ (see Special Parameters), are always made local in all functions, and are reset inside the function to represent the options and arguments passed to the function. Note that $0 however retains the value it had outside the function, as do all the other special parameters. The only special parameter that can optionally be made local is ``-''. Making ``-'' local causes any shell options that are changed via the set command inside the function to be restored to their original values when the function returns. If -X option is altered after ``-'' has been made local, then when the function returns, the previous destination for xtrace output (as of the time of the local command) will also be restored. If any of the shell's magic variables (those which return a value which may vary without the variable being explicitly altered, e.g.: SECONDS or HOSTNAME) are made local in a function, they will lose their spe- cial properties when set within the function, including by the local command itself (if not to be set in the function, there is little point in making a variable local) but those properties will be restored when the function returns. It is an error to use local outside the scope of a function defi- nition. When used inside a function, it exits with status 0, unless an undefined option is used, or an attempt is made to assign a value to a read-only variable. Note that either -I or -N should always be used, or variables made local should always be given a value, or explicitly unset, as the default behavior (inheriting the earlier value, or starting unset after local) differs amongst shell implementations. Using ``local -'' is an extension not implemented by most shells. See the section LINENO below for details of the effects of making the variable LINENO local. pwd [-LP] Print the current directory. If -L is specified the cached value (initially set from PWD) is checked to see if it refers to the current directory; if it does the value is printed. Otherwise the current directory name is found using getcwd(3). The environment variable PWD is set to the printed value. The default is pwd -L, but note that the built-in cd command doesn't support the -L option and will cache (almost) the absolute path. If cd is changed (as unlikely as that is), pwd may be changed to default to pwd -P. If the current directory is renamed and replaced by a symlink to the same directory, or the initial PWD value followed a symbolic link, then the cached value may not be the absolute path. The built-in command may differ from the program of the same name because the program will use PWD and the built-in uses a sepa- rately cached value. read [-p prompt] [-r] variable [...] The prompt is printed if the -p option is specified and the stan- dard input is a terminal. Then a line is read from the standard input. The trailing newline is deleted from the line and the line is split as described in the field splitting section of the Word Expansions section above, and the pieces are assigned to the vari- ables in order. If there are more pieces than variables, the remaining pieces (along with the characters in IFS that separated them) are assigned to the last variable. If there are more vari- ables than pieces, the remaining variables are assigned the null string. The read built-in will indicate success unless EOF is encountered on input, in which case failure is returned. By default, unless the -r option is specified, the backslash ``\'' acts as an escape character, causing the following character to be treated literally. If a backslash is followed by a newline, the backslash and the newline will be deleted. readonly name[=value] ... readonly [-p [name ...]] readonly -q name ... With no options, the specified names are marked as read only, so that they cannot be subsequently modified or unset. The shell allows the value of a variable to be set at the same time it is marked read only by writing readonly name=value With no arguments the readonly command lists the names of all set read only variables. With the -p option specified, the output will be formatted suitably for non-interactive use, and unset variables are included. When the -p option is given, a list of variable names (without values) may also be specified, in which case output is limited to the named variables. With the -q option, the readonly command tests the read-only sta- tus of the variables listed and exits with status 0 if all named variables are read-only, or with status 1 if any are not read- only. Other than as specified for -q the readonly command normally exits with status 0. In all cases, if an unknown option, or an invalid option combination, or an invalid variable name, is given; or a variable which was already read-only is attempted to be set; the exit status will not be zero, a diagnostic message will be written to the standard error output, and a non-interactive shell will terminate. return [n] Stop executing the current function or a dot command with return value of n or the value of the last executed command, if not spec- ified. For portability, n should be in the range from 0 to 255. The POSIX standard says that the results of return outside a func- tion or a dot command are unspecified. This implementation treats such a return as a no-op with a return value of 0 (success, true). Use the exit command instead, if you want to return from a script or exit your shell. set [{ -options | +options | -- }] arg ... The set command performs four different functions. With no arguments, it lists the values of all shell variables. With a single option of either ``-o'' or ``+o'' set outputs the current values of the options. In the -o form, all options are listed, with their current values. In the +o form, the shell out- puts a string that can later be used as a command to reset all options to their current values. If options are given, it sets the specified option flags, or clears them as described in the Argument List Processing section. In addition to the options listed there, when the ``option name'' given to set -o is default all of the options are reset to the values they had immediately after sh initialization, before any startup scripts, or other input, had been processed. While this may be of use to users or scripts, its primary purpose is for use in the output of ``set +o'', to avoid that command needing to list every available option. There is no +o default. The fourth use of the set command is to set the values of the shell's positional parameters to the specified arguments. To change the positional parameters without changing any options, use ``--'' as the first argument to set. If no following arguments are present, the set command will clear all the positional parame- ters (equivalent to executing ``shift $#''.) Otherwise the fol- lowing arguments become $1, $2, ..., and $# is set to the number of arguments present. setvar variable value Assigns value to variable. (In general it is better to write variable=value rather than using setvar. setvar is intended to be used in functions that assign values to variables whose names are passed as parameters.) shift [n] Shift the positional parameters n times. If n is omitted, 1 is assumed. Each shift sets the value of $1 to the previous value of $2, the value of $2 to the previous value of $3, and so on, decreasing the value of $# by one. The shift count must be less than or equal to the number of positional parameters ( ``$#'') before the shift. specialvar variable ... For each variable name given, if the variable named is one which, in this sh, could be treated as a special variable, then cause that variable to be made special, undoing any effects of an ear- lier unset or assignment to the variable. If all variables given are recognized special variables in this sh the specialvar command will exit with status 0, otherwise 1. Invalid usage will result in an exit status of 2. Note that all variables capable of being special are created that way, this command is not required to cause that to happen. How- ever should such a variable be imported from the environment, that will cause (for those special variables so designated) the special effects for that variable to be lost. Consequently, as the con- tents of the environment cannot be controlled, any script which desires to make use of the properties of most of the special vari- ables should use this command, naming the variables required, to ensure that their special properties are available. times Prints two lines to standard output. Each line contains two accu- mulated time values, expressed in minutes and seconds (including fractions of a second.) The first value gives the user time con- sumed, the second the system time. The first output line gives the CPU and system times consumed by the shell itself. The second line gives the accumulated times for children of this shell (and their descendants) which have exited, and then been successfully waited for by the relevant parent. See times(3) for more information. times has no parameters, and exits with an exit status of 0 unless an attempt is made to give it an option. trap action signal ... trap - trap [-l] trap [-p] signal ... trap N signal ... Cause the shell to parse and execute action when any of the speci- fied signals are received. The signals are specified by signal number or as the name of the signal. If signal is 0 or its equiv- alent, EXIT, the action is executed when the shell exits. The action may be a null (empty) string, which causes the specified signals to be ignored. With action set to `-' the specified sig- nals are set to their default actions. If the first signal is specified in its numeric form, then action can be omitted to achieve the same effect. This archaic, but still standard, form should not be relied upon, use the explicit `-' action. If no signals are specified with an action of `-', all signals are reset. When the shell forks off a sub-shell, it resets trapped (but not ignored) signals to the default action. On non-interactive shells, the trap command has no effect on signals that were ignored on entry to the shell. On interactive shells, the trap command will catch or reset signals ignored on entry. Issuing trap with option -l will print a list of valid signal names. trap without any arguments causes it to write a list of signals and their associated non-default actions to the standard output in a format that is suitable as an input to the shell that achieves the same trapping results. With the -p flag, trap prints the same information for the signals specified, or if none are given, for all signals, including those where the action is the default. These variants of the trap command may be executed in a sub-shell (such as in a command substitution), provided they appear as the sole, or first, command in that sub-shell, in which case the state of traps from the parent of that sub-shell is reported. Examples: trap List trapped signals and their corresponding actions. trap -l Print a list of valid signals. trap '' INT QUIT tstp 30 Ignore signals INT QUIT TSTP USR1. trap date INT Run the ``date'' command (print the date) upon receiving signal INT. trap HUP INT Run the ``HUP'' command, or function, upon receiving signal INT. trap 1 2 Reset the actions for signals 1 (HUP) and 2 (INT) to their defaults. traps=$(trap -p) # more commands ... trap 'action' SIG # more commands ... eval "$traps" Save the trap status, execute commands, changing some traps, and then reset all traps to their values at the start of the sequence. The -p option is required in the first command here, or any sig- nals that were previously untrapped (in their default states) and which were altered during the intermediate code, would not be reset by the final eval. type [name ...] Interpret each name as a command and print the resolution of the command search. Possible resolutions are: shell keyword, alias, shell built-in, command, tracked alias and not found. For aliases the alias expansion is printed; for commands and tracked aliases the complete pathname of the command is printed. ulimit [-H|-S] [-a | -btfdscmlrpnv [value]] Inquire about or set the hard or soft limits on processes or set new limits. The choice between hard limit (which no process is allowed to violate, and which may not be raised once it has been lowered) and soft limit (which causes processes to be signaled but not necessarily killed, and which may be raised) is made with these flags: -H set or inquire about hard limits -S set or inquire about soft limits. If neither -H nor -S is specified, the soft limit is displayed or both limits are set. If both are specified, the last one wins. The limit to be interrogated or set, then, is chosen by specifying any one of these flags: -a show all the current limits -b the socket buffer size of a process (bytes) -c the largest core dump size that can be produced (512-byte blocks) -d the data segment size of a process (kilobytes) -f the largest file that can be created (512-byte blocks) -l how much memory a process can lock with mlock(2) (kilobytes) -m the total physical memory that can be in use by a process (kilobytes) -n the number of files a process can have open at once -p the number of processes this user can have at one time -r the number of threads this user can have at one time -s the stack size of a process (kilobytes) -t CPU time (seconds) -v how large a process address space can be If none of these is specified, it is the limit on file size that is shown or set. If value is specified, the limit is set to that number; otherwise the current limit is displayed. Limits of an arbitrary process can be displayed or set using the sysctl(8) utility. umask [-S] [mask] Set the value of umask (see umask(2)) to the specified octal value. If the argument is omitted, the umask value is printed. With -S a symbolic form is used instead of an octal number. unalias [-a] [name] If name is specified, the shell removes that alias. If -a is specified, all aliases are removed. unset [-efvx] name ... If -v is specified, the specified variables are unset and unex- ported. Readonly variables cannot be unset. If -f is specified, the specified functions are undefined. If -e is given, the speci- fied variables are unexported, but otherwise unchanged, alterna- tively, if -x is given, the exported status of the variable will be retained, even after it is unset. If no flags are provided -v is assumed. If -f is given with one of the other flags, then the named variables will be unset, or unexported, and functions of the same names will be undefined. The -e and -x flags both imply -v. If -e is given, the -x flag is ignored. The exit status is 0, unless an attempt was made to unset a read- only variable, in which case the exit status is 1. It is not an error to unset (or undefine) a variable (or function) that is not currently set (or defined.) wait [-n] [-p var] [job ...] Wait for the specified jobs to complete and return the exit status of the last job in the parameter list, or 127 if that job is not a current child of the shell. If no job arguments are given, wait for all jobs to complete and then return an exit status of zero (including when there were no jobs, and so nothing exited.) With the -n option, wait instead for any one of the given jobs, or if none are given, any job, to complete, and return the exit sta- tus of that job. If none of the given job arguments is a current child of the shell, or if no job arguments are given and the shell has no unwaited for children, then the exit status will be 127. The -p var option allows the process (or job) identifier of the job for which the exit status is returned to be obtained. The variable named (which must not be readonly) will be unset ini- tially, then if a job has exited and its status is being returned, set to the identifier from the arg list (if given) of that job, or the lead process identifier of the job to exit when used with -n and no job arguments. Note that -p with neither -n nor job argu- ments is useless, as in that case no job status is returned, the variable named is simply unset. If the wait is interrupted by a signal, its exit status will be greater than 128, and var, if given, will remain unset. Once waited upon, by specific process number or job-id, or by a wait with no arguments, knowledge of the child is removed from the system, and it cannot be waited upon again. Note than when a list of jobs are given, more that one argument might refer to the same job. In that case, if the final argument represents a job that is also given earlier in the list, it is not defined whether the status returned will be the exit status of the job, or 127 indicating that the child no longer existed when the wait command reached the later argument in the list. In this sh the exit status will be that from the job. sh waits for each job exactly once, regardless of how many times (or how many different ways) it is listed in the arguments to wait. That is wait 100 100 100 is identical to wait 100 Job Control Each process (or set of processes) started by sh is created as a ``job'' and added to the jobs table. When enabled by the -m option (aka -o monitor) when the job is created, sh places each job (if run from the top level shell) into a process group of its own, which allows control of the process(es), and its/their descendants, as a unit. When the -m option is off, or when started from a sub-shell environment, jobs share the same process group as the parent shell. The -m option is enabled by default in interactive shells with a terminal as standard input and standard error. Jobs with separate process groups may be stopped, and then later resumed in the foreground (with access to the terminal) or in the background (where attempting to read from the terminal will result in the job stop- ping.) A list of current jobs can be obtained using the jobs built-in command. Jobs are identified using either the process identifier of the lead process of the job (the value available in the special parameter ``!'' if the job is started in the background), or using percent nota- tion. Each job is given a ``job number'' which is a small integer, starting from 1, and can be referenced as ``%n'' where n is that number. Note that this applies to jobs both with and without their own process groups. Job numbers are shown in the output from the jobs command enclosed in brackets (`[' and `]'). Whenever the job table becomes empty, the numbers begin at one again. In addition, there is the concept of a current, and a previous job, identified by ``%+'' (or ``%%'' or even just ``%''), and a previous job, identified by ``%-''. Whenever a back- ground job is started, or a job is resumed in the background, it becomes the current job. The job that was the current job (prepare for a big surprise here, drum roll..., wait for it...) becomes the previous job. When the current job terminates, the previous job is promoted to be the current job. In addition the form ``%string'' finds the job for which the command starts with string and the form ``%?string'' finds the job which contains the string in its command somewhere. Both forms require the result to be unambiguous. For this purpose the ``command'' is that shown in the output from the jobs command, not the original command line. The bg, fg, jobid, jobs, kill, and wait commands all accept job identi- fiers as arguments, in addition to process identifiers (larger integers). See the Built-ins section above, and kill(1), for more details of those commands. In addition, a job identifier (using one of the ``% forms'') issued as a command, without arguments, is interpreted as if it had been given as the argument to the fg command. To cause a foreground process to stop, enter the terminal's stop charac- ter (usually control-Z). To cause a background process to stop, send it a STOP signal, using the kill command. A useful function to define is stop() { kill -s STOP "${@:-%%}"; } The fg command resumes a stopped job, placing it in the foreground, and bg resumes a stopped job in the background. The jobid command provides information about process identifiers, job identifiers, and the process group identifier, for a job. Whenever a sub-shell is created, the jobs table becomes invalid (the sub- shell has no children.) However, to enable uses like PID=$(jobid -p %1) the table is only actually cleared in a sub-shell when needed to create the first job there (built-in commands run in the foreground do not cre- ate jobs.) Note that in this environment, there is no useful current job (``%%'' actually refers to the sub-shell itself, but is not accessible) but the job which is the current job in the parent can be accessed as ``%-''. Command Line Editing When sh is being used interactively from a terminal, the current command and the command history (see fc in the Built-ins section) can be edited using emacs-mode or vi-mode command-line editing. The command `set -o emacs' (or -E option) enables emacs-mode editing. The command `set -o vi' (or -V option) enables vi-mode editing and places the current shell process into vi insert mode. (See the Argument List Processing section above.) The vi-mode uses commands similar to a subset of those described in the vi(1) man page. With vi-mode enabled, sh can be switched between insert mode and command mode. It's similar to vi: pressing the <ESC> key will throw you into vi command mode. Pressing the <return> key while in com- mand mode will pass the line to the shell. The emacs-mode uses commands similar to a subset available in the emacs editor. With emacs-mode enabled, special keys can be used to modify the text in the buffer using the control key. sh uses the editline(3) library. See editline(7) for a list of the pos- sible command bindings, and the default settings in emacs and vi modes. Also see editrc(5) for the commands that can be given to configure editline(7) in the file named by the EDITRC parameter, or a file used with the inputrc built-in command, or using editline(7)'s configuration command line. When command line editing is enabled, the editline(7) functions control printing of the PS1 and PS2 prompts when required. As, in this mode, the command line editor needs to keep track of what characters are in what position on the command line, care needs to be taken when setting the prompts. Normal printing characters are handled automatically, however mode setting sequences, which do not actually display on the terminal, need to be identified to editline(7). This is done, when needed, by choosing a character that is not needed anywhere in the prompt, including in the mode setting sequences, any single character is acceptable, and assigning it to the shell parameter PSlit. Then that character should be used, in pairs, in the prompt string. Between each pair of PSlit charac- ters are mode setting sequences, which affect the printing attributes of the following (normal) characters of the prompt, but do not themselves appear visibly, nor change the terminal's cursor position. Each such sequence, that is PSlit character, mode setting character sequence, and another PSlit character, must currently be followed by at least one following normal prompt character, or it will be ignored. That is, a PSlit character cannot be the final character of PS1 or PS2, nor may two PSlit delimited sequences appear adjacent to each other. Each sequence can contain as many mode altering sequences as are required how- ever. Only the first character from PSlit will be used. When set PSlit should usually be set to a string containing just one character, then it can simply be embedded in PS1 (or PS2) as in PS1="${PSlit}mset${PSlit}XYZ${PSlit}mclr${PSlit}ABC" The prompt visible will be ``XYZABC'' with the ``XYZ'' part shown accord- ing as defined by the mode setting characters mset, and then cleared again by mclr. See tput(1) for one method to generate appropriate mode sequences. Note that both parts, XYZ and ABC, must each contain at least one character. If PSlit is unset, which is its initial state, or set to a null string, no literal character will be defined, and all characters of the prompt strings will be assumed to be visible characters (which includes spaces etc.) To allow smooth use of prompts, without needing redefinition, when editline(7) is disabled, the character chosen should be one which will be ignored by the terminal if received, as when editline(7) is not in use, the prompt strings are simply written to the terminal. For example, set- ting: PSlit="$(printf '\1')" PS1="${PSlit}$(tput bold blink)${PSlit}\$${PSlit}$(tput sgr0)${PSlit} " will arrange for the primary prompt to be a bold blinking dollar sign, if supported by the current terminal, followed by an (ordinary) space, and, as the SOH (control-A) character (`\1') will not normally affect a termi- nal, this same prompt will usually work with editline(7) enabled or dis- abled.
ENVIRONMENT
CDPATH The search path used with the cd built-in. EDITRC Gives the name of the file containing commands for editline(7). See editrc(5) for possible content and format. The file is processed, when in interactive mode with command line editing enabled, whenever EDITRC is set (even with no actual value change,) and if command line editing changes from disabled to enabled, or the editor style used is changed. (See the -E and -V options of the set built-in command, described in Built-ins above, which are documented further above in Argument List Processing.) If unset ``$HOME/.editrc'' is used. ENV Names the file sourced at startup by the shell. Unused by this shell after initialization, but is usually passed through the environment to descendant shells. See the Invocation sec- tion above for details of how ENV is processed and used. EUSER Set to the login name of the effective user id running the shell, as returned by getpwuid(geteuid())->pw_name (See getpwuid(3) and geteuid(2) for more details.) This is obtained each time EUSER is expanded, so changes to the shell's execution identity cause updates without further action. If unset, it returns nothing. If set it loses its special properties, and is simply a variable. See the specialvar built-in command for remedial action. HISTSIZE The number of lines in the history buffer for the shell. HOME Set automatically by login(1) from the user's login directory in the password file (passwd(5)). This environment variable also functions as the default argument for the cd built-in. HOSTNAME Set to the current hostname of the system, as returned by gethostname(3). This is obtained each time HOSTNAME is expanded, so changes to the system's name are reflected with- out further action. If unset, it returns nothing. If set it loses its special properties, and is simply a variable. See the specialvar built-in command for remedial action. IFS Input Field Separators. This is normally set to <space>, <tab>, and <newline>. White Space Splitting section for more details. LANG The string used to specify localization information that allows users to work with different culture-specific and lan- guage conventions. See nls(7). LINENO The current line number in the script or function. See the section LINENO below for more details. MAIL The name of a mail file, that will be checked for the arrival of new mail. Overridden by MAILPATH. The check occurs just before PS1 is written, immediately after reporting jobs which have changed status, in interactive shells only. New mail is considered to have arrived if the monitored file has increased in size since the last check. MAILPATH A colon ``:'' separated list of file names, for the shell to check for incoming mail. This environment setting overrides the MAIL setting. There is a maximum of 10 mailboxes that can be monitored at once. PATH The default search path for executables. See the Path Search section above. POSIXLY_CORRECT If set in the environment upon initialization of the shell, then the shell option posix will be set. (See the description of the set command in the Built-ins section.) After initial- ization it is unused by the shell, but is usually passed through the environment to descendant processes, including other instances of the shell, which may interpret it in a sim- ilar way. PPID The process identified of the parent process of the current shell. This value is set at shell startup, ignoring any value in the environment, and then made readonly. PS1 The primary prompt string, which defaults to ``$ '', unless you are the superuser, in which case it defaults to ``# ''. This string is subject to parameter, arithmetic, and if enabled by setting the promptcmds option, command substitution before being output. During execution of commands used by command substitution, execution tracing, the xtrace (set -x) option is temporarily disabled. If promptcmds is not set and the prompt string uses command substitution, the prompt used will be an appropriate error string. For other expansion errors, the prompt will become an empty string, without an error message. To verify parsing of PS1, the method suggested for ENV can be used. PS2 The secondary prompt string, which defaults to ``> ''. After expansion (as for PS1) it is written whenever more input is required to complete the current command. PS4 is output, after expansion as described for PS1, as a prefix for each line when execution trace (set -x) is enabled. PS4 defaults to ``+ ''. PSc Initialized by the shell, ignoring any value from the environ- ment, to a single character string, either `#' or `$', depend- ing upon whether the current user is the superuser or not. This is intended for use when building a custom PS1. If a privileged shell has its privileges removed by clearing the -p option, an attempt will be made to be reset PSc to ``#'' or ``$'', as appropriate for its new privilege level. PSlit Defines the character which may be embedded in pairs, in PS1 or PS2 to indicate to editline(7) that the characters between each pair of occurrences of the PSlit character will not appear in the visible prompt, and will not cause the termi- nal's cursor to change position, but rather set terminal attributes for the following prompt character(s) at least one of which must be present. See Command Line Editing above for more information. RANDOM Returns a different pseudo-random integer, in the range [0,32767] each time it is accessed. RANDOM can be assigned an integer value to seed the PRNG. If the value assigned is a constant, then the sequence of values produces on subsequent references of RANDOM will repeat after the next time the same constant is assigned. Note, this is not guaranteed to remain constant from one version of the shell to another - the PRNG algorithm, or seeding method is subject to change. If RANDOM is assigned an empty value (null string) then the next time RANDOM is accessed, it will be seeded from a more genuinely random source. The sequence of pseudo-random numbers gener- ated will not be able to be generated again (except by luck, whether good or bad, depends!) This is also how the initial seed is generated, if none has been assigned before RANDOM is first accessed after shell initialization. Should the error message ``RANDOM initialisation failed'' appear on standard error, it indicates that the source of good random numbers was not available, and RANDOM has instead been seeded with a more predictable value. The following sequence of random numbers will not be as unpredictable as they otherwise would be. SECONDS Returns the number of seconds since the current shell was started. If unset, it remains unset, and returns nothing, unless set again. If set, it loses its special properties, and becomes a normal variable. See the specialvar built-in command for remedial action. START_TIME Initialized by the shell to the number of seconds since the Epoch (see localtime(3)) when the shell was started. The value of $((START_TIME + SECONDS)) represents the current time, if START_TIME has not been modi- fied, and SECONDS has not been set or unset. TERM The default terminal setting for the shell. This is inherited by children of the shell, and is used in the history editing modes. ToD When referenced, uses the value of ToD_FORMAT (or ``%T'' if ToD_FORMAT is unset) as the format argument to strftime(3) to encode the current time of day, in the time zone defined by TZ if set, or current local time if not, and returns the result. If unset ToD returns nothing. If set, it loses its special properties, and becomes a normal variable. See the specialvar built-in command for remedial action. ToD_FORMAT Can be set to the strftime(3) format string to be used when expanding ToD. Initially unset. TZ If set, gives the time zone (see localtime(3), environ(7)) to use when formatting ToD and if exported, other utilities that deal with times. If unset, the system's local wall clock time zone is used. NETBSD_SHELL Unlike the variables previously mentioned, this variable is somewhat strange, in that it cannot be set, inherited from the environment, modified, or exported from the shell. If set, by the shell, it indicates that the shell is the sh defined by this manual page, and gives its version information. It can also give information in additional space separated words, after the version string. If the shell was built as part of a reproducible build, the relevant date that was used for that build will be included. Finally, any non-standard compilation options, which may affect features available, that were used when building the shell will be listed. NETBSD_SHELL behaves like any other variable that has the read-only and un- exportable attributes set. LINENO LINENO is in many respects a normal shell variable, containing an integer value. and can be expanded using any of the forms mentioned above which can be used for any other variable. LINENO can be exported, made readonly, or unset, as with any other vari- able, with similar effects. Note that while being readonly prevents later attempts to set, or unset, LINENO, it does not prevent its value changing. References to LINENO (when not unset) always obtain the cur- rent line number. However, LINENO should normally not ever be set or unset. In this shell setting LINENO reverses the effect of an earlier unset, but does not otherwise affect the value obtained. If unset, LINENO should not normally be set again, doing so is not portable. If LINENO is set or unset, different shells act differently. The value of LINENO is never imported from the environment when the shell is started, though if present there, as with any other variable, LINENO will be exported by this shell. LINENO is set automatically by the shell to be the number of the source line on which it occurs. When exported, LINENO is exported with its value set to the line number it would have had had it been referenced on the command line of the command to which it is exported. Line numbers are counted from 1, which is the first line the shell reads from any par- ticular file. For this shell, standard input, including in an interac- tive shell, the user's terminal, is just another file and lines are counted there as well. However note that not all shells count interac- tive lines this way, it is not wise to rely upon LINENO having a useful value, except in a script, or a function. The role of LINENO in functions is less clear. In some shells, LINENO continues to refer to the line number in the script which defines the function, in others lines count from one within the function, always (and resume counting normally once the function definition is complete) and others count in functions from one if the function is defined interac- tively, but otherwise just reference the line number in the script in which the function is defined. This shell gives the user the option to choose. If the -L flag (the local_lineno option, see Argument List Processing) is set, when the function is defined, then the function defaults to counting lines with one being the first line of the function. When the -L flag is not set, the shell counts lines in a function defini- tion in the same continuous sequence as the lines that surround the func- tion definition. Further, if LINENO is made local (see Built-ins above) inside the function, the function can decide which behavior it prefers. If LINENO is made local and inherited, and not given a value, as in local -I LINENO then from that point in the function, LINENO will give the line number as if lines are counted in sequence with the lines that surround the func- tion definition (and any other function definitions in which this is nested.) If LINENO is made local, and in that same command, given a value, as local [-I|-N] LINENO=value then LINENO will give the line number as if lines are counted from one from the beginning of the function. The value nominally assigned in this case is irrelevant, and ignored. For completeness, if lineno is made local and unset, as in local -N LINENO then LINENO is simply unset inside the function, and gives no value at all. Now for some technical details. The line on which LINENO occurs in a parameter expansion, is the line that contains the `$' that begins the expansion of LINENO. In the case of nested expansions, that `$' is the one that actually has LINENO as its parameter. In an arithmetic expan- sion, where no `$' is used to evaluate LINENO but LINENO is simply refer- enced as a variable, then the value is the line number of the line that contains the `L' of LINENO. For functions line one of the function defi- nition (when relevant) is the line that contains the first character of the function name in the definition. When exported, the line number of the command is the line number where the first character of the word which becomes the command name occurs. When the shell opens a new file, for any reason, it counts lines from one in that file, and then resumes its original counting once it resumes reading the previous input stream. When handling a string passed to eval the line number starts at the line on which the string starts, and then if the string contains internal newline characters, those characters increase the line number. This means that references to LINENO in such a case can produce values larger than would be produced by a reference on the line after the eval.
FILES
$HOME/.profile /etc/profile
EXIT STATUS
Errors that are detected by the shell, such as a syntax error, will cause the shell to exit with a non-zero exit status. If the shell is not an interactive shell, the execution of the shell file will be aborted. Oth- erwise the shell will return the exit status of the last command exe- cuted, or if the exit built-in is used with a numeric argument, it will return the argument.
SEE ALSO
csh(1), echo(1), getopt(1), ksh(1), login(1), printf(1), test(1), editline(3), getopt(3), editrc(5), passwd(5), editline(7), environ(7), nls(7), sysctl(8)
HISTORY
A sh command appeared in Version 1 AT&T UNIX. It was replaced in Version 7 AT&T UNIX with a version that introduced the basis of the cur- rent syntax. That was, however, unmaintainable so we wrote this one. This NetBSD sh is a much modified descendant of the ash shell written by Ken Almquist.
BUGS
Setuid shell scripts should be avoided at all costs, as they are a sig- nificant security risk. The characters generated by filename completion should probably be quoted to ensure that the filename is still valid after the input line has been processed. Job control of compound statements (loops, etc) is a complete mess. Many, many, more. (But less than there were...) NetBSD 9.4_STABLE October 31, 2021 NetBSD 9.4_STABLE

Powered by man-cgi (2024-08-26). Maintained for NetBSD by Kimmo Suominen. Based on man-cgi by Panagiotis Christias.