sh(1) - NetBSD Manual Pages

Command: Section: Arch: Collection:  
SH(1)                   NetBSD General Commands Manual                   SH(1)


NAME
sh -- command interpreter (shell)
SYNOPSIS
sh [-abCEeFfhIiLmnpquVvx] [+abCEeFfhIiLmnpquVvx] [-o option_name] [+o option_name] [command_file [argument ...]] sh -c [-s] [-abCEeFfhIiLmnpquVvx] [+abCEeFfhIiLmnpquVvx] [-o option_name] [+o option_name] command_string [command_name [argument ...]] sh -s [-abCEeFfhIiLmnpquVvx] [+abCEeFfhIiLmnpquVvx] [-o option_name] [+o option_name] [argument ...]
DESCRIPTION
sh is the standard command interpreter for the system. The current ver- sion of sh is in the process of being changed to conform more closely to the POSIX 1003.2 and 1003.2a specifications for the shell. This version has many features 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 output, of the shell are connected to a terminal (or if the -i flag is set), and the -c option is not present, the shell is considered an interactive shell. An interactive shell generally prompts before each command and handles pro- gramming 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 from the files /etc/profile and .profile 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 interac- tive, or the posix option is not set, the shell next reads commands from the file named in ENV. 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 vari- able 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. -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 stan- dard 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 editor (disables -V if it has 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 considered to be explicitly tested if the com- mand is used to control an if, elif, while, or until, or if the command is the left hand oper- and of an ``&&'' or ``||'' operator, or if it is a pipeline (or simple command) preceded by the ``!'' operator. 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. (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 func- tion, 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 interactive). -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. This is not set by default to help avoid incorrect usage by setuid root programs via system(3) or popen(3). -q quietprofile If the -v or -x options have been set, do not apply them when 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 automat- ically if neither -c nor file arguments are present). If after procesing 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 interactive. -u nounset Write a message to standard error when attempt- ing to obtain a value from a variable that is not set, and if the shell is not interactive, exit immediately. 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 has 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 xtrace Write each command to standard error (preceded by the expanded value of ``$PS4'') before it is executed. Useful 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.) posix Enables closer adherence to the POSIX shell standard. This option will default set at shell startup if the environment variable POSIXLY_CORRECT is present. That can be over- ridden (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 command 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), and whether the shell treats an empty brace-list compound statement as a syntax error (expected by POSIX) or permits it. Such statements ``{ }'' can be useful when defining dummy functions. Lastly, in posix mode, only one ``!'' is permitted before a pipeline. promptcmds Allows command substitutions (as well as param- eter and arithmetic expansions, which are always performed) 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 substi- tutions 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 character 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 three types of quoting: matched single quotes, matched double quotes, and backslash. 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. 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. The following is a list of the possible redirections. The [n] is an optional number, as in `3' (not `[3]'), that refers to a file descriptor. If present it must occur immediately before the redirection operator, with no intervening white space, and becomes a part of that operator. [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 Duplicate standard input (or n1) from file descriptor n2. n2 is expanded if not a digit string, the result must be a number. [n]<&- Close standard input (or n). [n1]>&n2 Duplicate standard output (or n1) to 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-doc 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-doc 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-doc, 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 (except $0, which remains unchanged) are set to the arguments of the shell function. The variables which are explicitly placed in the envi- ronment of the command (by placing assignments to them before the func- tion name) are made local to the function and are set to the values given, and exported for the benefit of programs executed with the func- tion. 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. 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. More generally, a command is one of the following: simple command pipeline list or compound-list compound command function definition Unless otherwise stated, the exit status of a command is that of the last simple command executed by the command. Pipelines A pipeline is a sequence of one or more commands separated by the control operator `|', and optionally preceded by the ``!'' reserved word. The standard output of all but the last command is connected to the standard input of the next command. The standard output of the last command is inherited from the shell, as usual. 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 a command is considered to be assigned by the pipeline before any redirection speci- fied by redirection operators that are part of the command are performed. If the pipeline is not in the background (discussed later), the shell waits for all commands to complete. If the reserved word ! does not precede the pipeline, the exit status is the exit status of the last command specified in the pipeline. Other- wise, the exit status is the logical NOT of the exit status of the last command. That is, if the last command returns zero, the exit status is 1; if the last command returns greater than zero, the exit status is zero. 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. A ; or <newline> terminator causes the preceding AND-OR-list (described next) to be executed sequentially; a & causes asynchronous execution of the preceding AND-OR-list. The exit status of an asynchronous AND-OR- list is zero. The actual status of the commands, after they have com- pleted, can be obtained using the wait built-in command described later. 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). Background Commands -- & If a command is terminated by the control operator 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). 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. 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 command to terminate before proceeding to the next one. A new- line is equivalent 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. Short-Circuit List Operators ``&&'' and ``||'' are AND-OR list operators. ``&&'' executes the first command, and then executes the second command if and only if the exit status of the first command is zero. ``||'' is similar, but executes the second command if and only if the exit status of the first command is nonzero. ``&&'' and ``||'' both have the same priority. 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, for, case 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 no words are given, and then the list is executed repeatedly with the variable set to each word in turn. 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 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'' (which may be empty) is evaluated. If the list is terminated with ``;&'' execution then falls through to the following list, if any, without evaluating its pattern, or attempting a match. When a list terminated 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; } 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 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 charac- ters in embedded arithmetic expansions, command substitutions, and vari- able 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 following 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 parame- ter. In all cases, the final value of parameter is substituted. Only variables, not positional param- eters 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 pat- tern 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 pat- tern 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 the command is enclosed as follows: $(command) or (``backquoted'' version): `command` The shell expands the command substitution by executing command in a sub- shell environment and replacing the command substitution with the stan- dard output of the command, removing sequences of one or more <newline>s at the end of the substitution. (Embedded <newline>s before the end of the output are not removed; however, during field splitting, they may be translated into <space>s, depending on the value of IFS and any quoting that is in effect.) 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, except the unary ``++'' and ``--'' operators (in both prefix and postfix forms) and the ``,'' (comma) operator, which are currently not supported. 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 Built-ins 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 [-p] [-v] [-V] 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 [-P] [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 instructs the shell to update PWD with the specified physical directory path and change to that directory. This is the default. When the directory changes, the variable OLDPWD is set to the working directory 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, the cd command will print out the name of the directory that it actually switched to if this is different from the name that the user gave, or always if the cdprint option is set. The destination may be different either because the CDPATH mechanism was used or if the replace argument was used. 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 they point to 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 processes. This behavior is required by the POSIX stan- dard, so when the posix option is set, this shell also acts that way. 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 descriptor 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 [-npx] name ... export -p [-x] 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 readonly. That is export -x FOO; # FOO will now not be exported by default 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 by writing export name=value With no arguments the export command lists the names of all exported variables, or if -x was given, all variables marked not for export. With the -p option specified the output will be for- matted suitably for non-interactive use. The export built-in exits with status 0, unless an invalid option, or option combination, is given, or 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. Note that there is no restriction upon exporting, or un-exporting, readonly variables. The no-export flag can be reset by unsetting the variable and creating it again - provided it 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 specifying 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 [job] Print the process id's of the processes in the job. If the job argument is omitted, the current job is used. jobs This command lists out all the background processes which are children of the current shell process. 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 parameters $1, $2, ... (see Positional Parameters), and $#, $* 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 other special parameter that can 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 origi- nal values 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 at 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 ... readonly [-p] 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 read only variables. With the -p option specified the output will be formatted suitably for non-interactive use. 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 function 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 cur- rent 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. 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. 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 show or set the limit on the socket buffer size of a process (in bytes) -c show or set the limit on the largest core dump size that can be produced (in 512-byte blocks) -d show or set the limit on the data segment size of a process (in kilobytes) -f show or set the limit on the largest file that can be created (in 512-byte blocks) -l show or set the limit on how much memory a process can lock with mlock(2) (in kilobytes) -m show or set the limit on the total physical memory that can be in use by a process (in kilobytes) -n show or set the limit on the number of files a process can have open at once -p show or set the limit on the number of processes this user can have at one time -r show or set the limit on the number of threads this user can have at one time -s show or set the limit on the stack size of a process (in kilobytes) -t show or set the limit on CPU time (in seconds) -v show or set the limit on 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 [job] Wait for the specified job to complete and return the exit status of the last process in the job, or 127 if the job is not a current child of the shell. If the argument is omitted, wait for all jobs to complete and then return an exit status of zero. If the wait is interrupted by a signal, its exit status will be greater than 128. 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. 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' enables emacs-mode editing. The command `set -o vi' 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(1): pressing the <ESC> key will throw you into command VI command mode. Pressing the <return> key while in command mode will pass the line to the shell. The emacs mode uses commands similar to a subset available in the emacs(1) 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 edlitline(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 builtin command, described in Built-ins above, which are documented further above in Argument List Processing.) If unset ``$HOME/.editrc'' is used. 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. Setting it does nothing except reverse the effect of an earlier unset. IFS Input Field Separators. This is normally set to <space>, <tab>, and <newline>. See the 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. 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, a message will be output, and the unexpanded string will then be used as the prompt. 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 Output, after expansion like PS1, before each line when execu- tion trace (set -x) is enabled. PS4 defaults to ``+ ''. PSc Initialised 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. 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. SECONDS Returns the number of seconds since the current shell was started. Attempts to set this variable are ignored. If unset, it remains unset, and returns nothing, unless set again. START_TIME Initialised 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 is not 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. Setting it has no effect, other than to reverse the effect of an earlier unset. 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 (which prevents attempts to assign to it, and to unset it, but which does not change the value, that is the current line number, from being obtained when LINENO is referenced,) and can be unset. All of those act as they would with any other variable. 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 oth- erwise affect the value obtained. If unset, LINENO should not normally be set again, doing so is not portable. If LINENO is set or unset, dif- ferent 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.
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. The trap command cannot usefully be used, yet, within a command substitu- tion, to obtain the current trap values, as all command substitutions are currently executed within a sub-shell environment, and in sub-shells all non-ignored, non-default, traps are reset. As a workaround, it is possi- ble to redirect output from ``trap'' or ``trap -p'' to a file, and then read the file later using the ``.'' command. Many, many, more. (But less than there were...) NetBSD 8.0 October 6, 2017 NetBSD 8.0
Powered by man-cgi (2020-09-24). Maintained for NetBSD by Kimmo Suominen. Based on man-cgi by Panagiotis Christias.