xref: /freebsd/bin/sh/sh.1 (revision ce834215a70ff69e7e222827437116eee2f9ac6f)
1.\" Copyright (c) 1991, 1993
2.\"	The Regents of the University of California.  All rights reserved.
3.\"
4.\" This code is derived from software contributed to Berkeley by
5.\" Kenneth Almquist.
6.\"
7.\" Redistribution and use in source and binary forms, with or without
8.\" modification, are permitted provided that the following conditions
9.\" are met:
10.\" 1. Redistributions of source code must retain the above copyright
11.\"    notice, this list of conditions and the following disclaimer.
12.\" 2. Redistributions in binary form must reproduce the above copyright
13.\"    notice, this list of conditions and the following disclaimer in the
14.\"    documentation and/or other materials provided with the distribution.
15.\" 3. All advertising materials mentioning features or use of this software
16.\"    must display the following acknowledgement:
17.\"	This product includes software developed by the University of
18.\"	California, Berkeley and its contributors.
19.\" 4. Neither the name of the University nor the names of its contributors
20.\"    may be used to endorse or promote products derived from this software
21.\"    without specific prior written permission.
22.\"
23.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33.\" SUCH DAMAGE.
34.\"
35.\"	from: @(#)sh.1	8.6 (Berkeley) 5/4/95
36.\"	$Id: sh.1,v 1.13 1997/04/28 03:20:09 steve Exp $
37.\"
38.Dd May 5, 1995
39.Dt SH 1
40.Os BSD 4
41.Sh NAME
42.Nm sh
43.Nd command interpreter (shell)
44.Sh SYNOPSIS
45.Nm
46.Op Fl /+abCEefIimnpsuVvx
47.Op Fl /+o Ar longname
48.Op Ar arg ...
49.Sh DESCRIPTION
50.Nm sh
51is the standard command interpreter for the system.
52The current version of
53.Nm
54is in the process of being changed to
55conform with the
56.St -p1003.2
57specification for the shell.  This version has many features which make
58it appear
59similar in some respects to the Korn shell, but it is not a Korn
60shell clone (run GNU's bash if you want that).  Only features
61designated by POSIX, plus a few Berkeley extensions, are being
62incorporated into this shell.
63This man page is not intended to be a tutorial or a complete
64specification of the shell.
65.Ss Overview
66The shell is a command that reads lines from
67either a file or the terminal, interprets them, and
68generally executes other commands. It is the program that is running
69when a user logs into the system (although a user can select
70a different shell with the chsh(1) command).
71The shell
72implements a language that has flow control constructs,
73a macro facility that provides a variety of features in
74addition to data storage, along with built in history and line
75editing capabilities.  It incorporates many features to
76aid interactive use and has the advantage that the interpretative
77language is common to both interactive and non-interactive
78use (shell scripts).  That is, commands can be typed directly
79to the running shell or can be put into a file and the file
80can be executed directly by the shell.
81.Ss Invocation
82If no args are present and if the standard input of the shell
83is connected to a terminal (or if the -i flag is set), the shell
84is considered an interactive shell.  An interactive shell
85generally prompts before each command and handles programming
86and command errors differently (as described below).
87When first starting, the shell inspects argument 0, and
88if it begins with a dash '-', the shell is also considered
89a login shell.  This is normally done automatically by the system
90when the user first logs in.  A login shell first reads commands
91from the files
92.Pa /etc/profile
93and
94.Pa .profile
95if they exist.  If the environment variable
96.Ev ENV
97is set on entry to a shell, or is set in the
98.Pa .profile
99of a login shell, the shell next reads commands from the file named in
100.Ev ENV .
101Therefore, a user should place commands that are to be executed only
102at login time in the
103.Pa .profile
104file, and commands that are executed for every shell inside the
105.Ev ENV
106file. To set the
107.Ev ENV
108variable to some file, place the following line in your
109.Pa .profile
110of your home directory
111.sp
112.Dl ENV=$HOME/.shinit; export ENV
113.sp
114substituting for
115.Pa .shinit
116any filename you wish.
117If commandline arguments besides the options have been
118specified, then the shell treats the first argument as the
119name of a file from which to read commands (a shell script), and
120the remaining arguments are set as the positional parameters
121of the shell ($1, $2, etc).  Otherwise, the shell reads commands
122from its standard input.
123.Pp
124Unlike older versions of
125.Nm
126the
127.Ev ENV
128script is only sourced on invocation of interactive shells.  This
129closes a well-known, and sometimes easily exploitable security
130hole related to poorly thought out
131.Ev ENV
132scripts.
133.Ss Argument List Processing
134All of the single letter options to
135.Nm
136have a corresponding name that can be used as an argument to the
137.Xr set 1
138builtin (described later).  These names are provided next to the
139single letter option in the descriptions below.  Specifying a dash
140.Dq -
141enables the option, while using a plus
142.Dq +
143disables the option.
144.Bl -tag -width Ds
145.It Fl a Li allexport
146Export all variables assigned to.
147.Pq UNIMPLEMENTED
148.It Fl b Li notify
149Enable asynchronous notification of background job
150completion.
151.Pq UNIMPLEMENTED
152.It Fl C Li noclobber
153Don't overwrite existing files with
154.Dq >.
155.Pq UNIMPLEMENTED
156.It Fl E Li emacs
157Enable the built-in
158.Xr emacs 1
159commandline editor (disables
160.Fl V
161if it has been set).
162.It Fl e Li errexit
163If not interactive, exit immediately if any
164untested command fails.
165The exit status of a command is considered to be
166explicitly tested if the command is used to control
167an if, elif, while, or until; or if the command is the left
168hand operand of an
169.Dq &&
170or
171.Dq ||
172operator.
173.It Fl f Li noglob
174Disable pathname expansion.
175.It Fl I Li ignoreeof
176Ignore EOF's from input when interactive.
177.It Fl i Li interactive
178Force the shell to behave interactively.
179.It Fl m Li monitor
180Turn on job control (set automatically when interactive).
181.It Fl n Li noexec
182If not interactive, read commands but do not
183execute them.  This is useful for checking the
184syntax of shell scripts.
185.It Fl p Li privileged
186Turn on privileged mode.  This mode is enabled on startup
187if either the effective user or group id is not equal to the
188real user or group id.  Turning this mode off sets the
189effective user and group ids to the real user and group ids.
190Also on interactive shells and when enabled, this mode sources
191.Pa /etc/suid_profile
192(instead of
193.Pa ~/.profile Ns )
194after
195.Pa /etc/profile
196and ignores the contents of the
197.Ev ENV
198variable.
199.It Fl s Li stdin
200Read commands from standard input (set automatically
201if no file arguments are present).  This option has
202no effect when set after the shell has already started
203running (i.e. with
204.Xr set 1 Ns ).
205.It Fl u Li nounset
206Write a message to standard error when attempting
207to expand a variable that is not set, and if the
208shell is not interactive, exit immediately.
209.Pq UNIMPLEMENTED
210.It Fl V Li vi
211Enable the built-in
212.Xr vi 1
213commandline editor (disables
214.Fl E
215if it has been set).
216.It Fl v Li verbose
217The shell writes its input to standard error
218as it is read.  Useful for debugging.
219.It Fl x Li xtrace
220Write each command to standard error (preceded
221by a '+ ') before it is executed.  Useful for
222debugging.
223.El
224.Ss Lexical Structure
225The shell reads input in terms of lines from a file and breaks
226it up into words at whitespace (blanks and tabs), and at
227certain sequences of
228characters that are special to the shell called ``operators''.
229There are two types of operators: control operators and
230redirection operators (their meaning is discussed later).
231The following is a list of valid operators:
232.Bl -tag -width Ds
233.It No Control operators:
234&  &&  (  )  ;  ;; | ||
235.No \en
236.It No Redirection operators:
237<  >  >|  <<  >>  <&  >&  <<-  <>
238.El
239.Ss Quoting
240Quoting is used to remove the special meaning of certain characters
241or words to the shell, such as operators, whitespace, or
242keywords.  There are three types of quoting: matched single quotes,
243matched double quotes, and backslash.
244.Bl -tag -width Ds
245.It Single Quotes
246Enclosing characters in single quotes preserves the literal
247meaning of all the characters (except single quotes, making
248it impossible to put single-quotes in a single-quoted string).
249.It Double Quotes
250Enclosing characters within double quotes preserves the literal
251meaning of all characters except dollarsign ($), backquote (`),
252and backslash (\\).  The backslash inside double quotes is
253historically weird, and serves to quote only the following
254characters: $  `  "  \\
255.No \en .
256Otherwise it remains literal.
257.It Backslash
258A backslash preserves the literal meaning of the following
259character, with the exception of
260.No \en.
261A backslash preceding a
262.No \en
263is treated as a line continuation.
264.El
265.Ss Reserved Words
266Reserved words are words that have special meaning to the
267shell and are recognized at the beginning of a line and
268after a control operator.  The following are reserved words:
269.Bd -literal -offset indent
270!       {       }       case    do
271done    elif    else    esac    fi
272for     if      then    until   while
273.Ed
274.Ss Aliases
275An alias is a name and corresponding value set using the
276.Xr alias 1
277builtin command.  Whenever a reserved word may occur (see above),
278and after checking for reserved words, the shell
279checks the word to see if it matches an alias. If it does,
280it replaces it in the input stream with its value.  For example,
281if there is an alias called ``lf'' with the value ``ls -F'',
282then the input
283.Bd -literal -offset indent
284lf foobar <return>
285.Ed
286.Pp
287would become
288.Bd -literal -offset indent
289ls -F foobar <return>
290.Ed
291.Pp
292Aliases provide a convenient way for naive users to
293create shorthands for commands without having to learn how
294to create functions with arguments.  They can also be
295used to create lexically obscure code.  This use is discouraged.
296.Ss Commands
297The shell interprets the words it reads according to a
298language, the specification of which is outside the scope
299of this man page (refer to the BNF in the
300.St -p1003.2
301document).  Essentially though, a line is read and if
302the first word of the line (or after a control operator)
303is not a reserved word, then the shell has recognized a
304simple command.  Otherwise, a complex command or some
305other special construct may have been recognized.
306.Ss Simple Commands
307If a simple command has been recognized, the shell performs
308the following actions:
309.Bl -enum
310.It
311Leading words of the form ``name=value'' are
312stripped off and assigned to the environment of
313the simple command.  Redirection operators and
314their arguments (as described below) are stripped
315off and saved for processing.
316.It
317The remaining words are expanded as described in
318the section called ``Expansions'', and the
319first remaining word is considered the command
320name and the command is located.  The remaining
321words are considered the arguments of the command.
322If no command name resulted, then the ``name=value''
323variable assignments recognized in 1) affect the
324current shell.
325.It
326Redirections are performed as described in
327the next section.
328.El
329.Ss Redirections
330Redirections are used to change where a command reads its input
331or sends its output.  In general, redirections open, close, or
332duplicate an existing reference to a file.  The overall format
333used for redirection is:
334.sp
335.Dl [n] redir-op file
336.sp
337where redir-op is one of the redirection operators mentioned
338previously.  The following gives some examples of how these
339operators can be used.  NOTE: stdin and stdout are commonly
340used abbreviations for standard input and standard output,
341respectively.
342.Bl -tag -width "1234567890" -offset indent
343.It [n]> file
344redirect stdout (or n) to file
345.It [n]>| file
346same as above, but override the -C option
347.It [n]>> file
348append stdout (or n) to file
349.It [n]< file
350redirect stdin (or n) from file
351.It [n1]<&n2
352duplicate stdin (or n1) from file descriptor n2
353.It [n]<&-
354close stdin (or n)
355.It [n1]>&n2
356duplicate stdout (or n1) to n2.
357.It [n]>&-
358close stdout (or n)
359.It [n]<> file
360open file for reading and writing on stdin (or n)
361.El
362.Pp
363The following redirection is often called a ``here-document''.
364.Bd -literal -offset indent
365[n]<< delimiter
366	here-doc-text...
367delimiter
368.Ed
369.Pp
370All the text on successive lines up to the delimiter is
371saved away and made available to the command on standard
372input, or file descriptor n if it is specified.  If the delimiter
373as specified on the initial line is quoted, then the here-doc-text
374is treated literally, otherwise the text is subjected to
375parameter expansion, command substitution, and arithmetic
376expansion (as described in the section on ``Expansions'').  If
377the operator is ``<<-'' instead of ``<<'', then leading tabs
378in the here-doc-text are stripped.
379.Ss Search and Execution
380There are three types of commands: shell functions,
381builtin commands, and normal programs -- and the
382command is searched for (by name) in that order.  They
383each are executed in a different way.
384.Pp
385When a shell function is executed, all of the shell positional
386parameters (except $0, which remains unchanged) are
387set to the arguments of the shell function.
388The variables which are explicitly placed in the environment of
389the command (by placing assignments to them before the
390function name) are made local to the function and are set
391to the values given. Then the command given in the function
392definition is executed.   The positional parameters are
393restored to their original values when the command completes.
394This all occurs within the current shell.
395.Pp
396Shell builtins are executed internally to the shell, without
397spawning a new process.
398.Pp
399Otherwise, if the command name doesn't match a function
400or builtin, the command is searched for as a normal
401program in the filesystem (as described in the next section).
402When a normal program is executed, the shell runs the program,
403passing the arguments and the environment to the
404program. If the program is not a normal executable file
405(i.e., if it does not begin with the "magic number" whose
406.Tn ASCII
407representation is "#!", so
408.Fn execve
409returns
410.Er ENOEXEC
411then) the shell
412will interpret the program in a subshell.  The child shell
413will reinitialize itself in this case, so that the effect will
414be as if a new shell had been invoked to handle the ad-hoc shell
415script, except that the location of hashed commands located in
416the parent shell will be remembered by the child.
417.Pp
418Note that previous versions of this document
419and the source code itself misleadingly and sporadically
420refer to a shell script without a magic number
421as a "shell procedure".
422.Ss Path Search
423When locating a command, the shell first looks to see if
424it has a shell function by that name.  Then it looks for a
425builtin command by that name.  If a builtin command is not found,
426one of two things happen:
427.Bl -enum
428.It
429Command names containing a slash are simply executed without
430performing any searches.
431.It
432The shell searches each entry in
433.Ev PATH
434in turn for the command.  The value of the
435.Ev PATH
436variable should be a series of
437entries separated by colons.  Each entry consists of a
438directory name.
439The current directory
440may be indicated implicitly by an empty directory name,
441or explicitly by a single period.
442.El
443.Ss Command Exit Status
444Each command has an exit status that can influence the behavior
445of other shell commands.  The paradigm is that a command exits
446with zero for normal or success, and non-zero for failure,
447error, or a false indication.  The man page for each command
448should indicate the various exit codes and what they mean.
449Additionally, the builtin commands return exit codes, as does
450an executed shell function.
451.Ss Complex Commands
452Complex commands are combinations of simple commands
453with control operators or reserved words, together creating a larger complex
454command.  More generally, a command is one of the following:
455.Bl -item -offset indent
456.It
457simple command
458.It
459pipeline
460.It
461list or compound-list
462.It
463compound command
464.It
465function definition
466.El
467.Pp
468Unless otherwise stated, the exit status of a command is
469that of the last simple command executed by the command.
470.Ss Pipelines
471A pipeline is a sequence of one or more commands separated
472by the control operator |.  The standard output of all but
473the last command is connected to the standard input
474of the next command.  The standard output of the last
475command is inherited from the shell, as usual.
476.Pp
477The format for a pipeline is:
478.Bd -literal -offset indent
479[!] command1 [ | command2 ...]
480.Ed
481.Pp
482The standard output of command1 is connected to the standard
483input of command2.  The standard input, standard output, or
484both of a command is considered to be assigned by the
485pipeline before any redirection specified by redirection
486operators that are part of the command.
487.Pp
488If the pipeline is not in the background (discussed later),
489the shell waits for all commands to complete.
490.Pp
491If the reserved word ! does not precede the pipeline, the
492exit status is the exit status of the last command specified
493in the pipeline.  Otherwise, the exit status is the logical
494NOT of the exit status of the last command.  That is, if
495the last command returns zero, the exit status is 1; if
496the last command returns greater than zero, the exit status
497is zero.
498.Pp
499Because pipeline assignment of standard input or standard
500output or both takes place before redirection, it can be
501modified by redirection.  For example:
502.Bd -literal -offset indent
503$ command1 2>&1 | command2
504.Ed
505.Pp
506sends both the standard output and standard error of command1
507to the standard input of command2.
508.Pp
509A ; or <newline> terminator causes the preceding
510AND-OR-list (described next) to be executed sequentially; a & causes
511asynchronous execution of the preceding AND-OR-list.
512.Pp
513Note that unlike some other shells, each process in the
514pipeline is a child of the invoking shell (unless it
515is a shell builtin, in which case it executes in the
516current shell -- but any effect it has on the
517environment is wiped).
518.Ss Background Commands -- &
519If a command is terminated by the control operator ampersand
520(&), the shell executes the command asynchronously -- that is,
521the shell does not wait for
522the command to finish before executing the next command.
523.Pp
524The format for running a command in background is:
525.Bd -literal -offset indent
526command1 & [command2 & ...]
527.Ed
528.Pp
529If the shell is not interactive, the standard input of an
530asynchronous command is set to /dev/null.
531.Ss Lists -- Generally Speaking
532A list is a sequence of zero or more commands separated by
533newlines, semicolons, or ampersands,
534and optionally terminated by one of these three characters.
535The commands in a
536list are executed in the order they are written.
537If command is followed by an ampersand, the shell starts the
538command and immediately proceed onto the next command;
539otherwise it waits for the command to terminate before
540proceeding to the next one.
541.Ss Short-Circuit List Operators
542``&&'' and ``||'' are AND-OR list operators.  ``&&'' executes
543the first command, and then executes the second command
544iff the exit status of the first command is zero.  ``||''
545is similar, but executes the second command iff the exit
546status of the first command is nonzero.  ``&&'' and ``||''
547both have the same priority.
548.Ss Flow-Control Constructs -- if, while, for, case
549The syntax of the if command is
550.Bd -literal -offset indent
551if list
552then list
553[ elif list
554then    list ] ...
555[ else list ]
556fi
557.Ed
558.Pp
559The syntax of the while command is
560.Bd -literal -offset indent
561while list
562do   list
563done
564.Ed
565.Pp
566The two lists are executed repeatedly while the exit status of the
567first list is zero.  The until command is similar, but has the word
568until in place of while, which causes it to
569repeat until the exit status of the first list is zero.
570.Pp
571The syntax of the for command is
572.Bd -literal -offset indent
573for variable in word...
574do   list
575done
576.Ed
577.Pp
578The words are expanded, and then the list is executed
579repeatedly with the variable set to each word in turn.  do
580and done may be replaced with ``{'' and ``}''.
581.Pp
582The syntax of the break and continue command is
583.Bd -literal -offset indent
584break [ num ]
585continue [ num ]
586.Ed
587.Pp
588Break terminates the num innermost for or while loops.
589Continue continues with the next iteration of the innermost loop.
590These are implemented as builtin commands.
591.Pp
592The syntax of the case command is
593.Bd -literal -offset indent
594case word in
595pattern) list ;;
596...
597esac
598.Ed
599.Pp
600The pattern can actually be one or more patterns (see Shell
601Patterns described later), separated by ``|'' characters.
602.Ss Grouping Commands Together
603Commands may be grouped by writing either
604.Bd -literal -offset indent
605(list)
606.Ed
607.Pp
608or
609.Bd -literal -offset indent
610{ list; }
611.Ed
612.Pp
613The first of these executes the commands in a subshell.
614Builtin commands grouped into a (list) will not affect
615the current shell.
616The second form does not fork another shell so is
617slightly more efficient.
618Grouping commands together this way allows you to
619redirect their output as though they were one program:
620.Bd -literal -offset indent
621{ echo -n "hello"; echo " world" } > greeting
622.Ed
623.Ss Functions
624The syntax of a function definition is
625.Bd -literal -offset indent
626name ( ) command
627.Ed
628.Pp
629A function definition is an executable statement; when
630executed it installs a function named name and returns an
631exit status of zero.  The command is normally a list
632enclosed between ``{'' and ``}''.
633.Pp
634Variables may be declared to be local to a function by
635using a local command.  This should appear as the first
636statement of a function, and the syntax is
637.Bd -literal -offset indent
638local [ variable | - ] ...
639.Ed
640.Pp
641Local is implemented as a builtin command.
642.Pp
643When a variable is made local, it inherits the initial
644value and exported and readonly flags from the variable
645with the same name in the surrounding scope, if there is
646one.  Otherwise, the variable is initially unset.  The shell
647uses dynamic scoping, so that if you make the variable x
648local to function f, which then calls function g, references
649to the variable x made inside g will refer to the
650variable x declared inside f, not to the global variable
651named x.
652.Pp
653The only special parameter than can be made local is
654``-''.  Making ``-'' local any shell options that are
655changed via the set command inside the function to be
656restored to their original values when the function
657returns.
658.Pp
659The syntax of the return command is
660.Bd -literal -offset indent
661return [ exitstatus ]
662.Ed
663.Pp
664It terminates the currently executing function.  Return is
665implemented as a builtin command.
666.Ss Variables and Parameters
667The shell maintains a set of parameters.  A parameter
668denoted by a name is called a variable.  When starting up,
669the shell turns all the environment variables into shell
670variables.  New variables can be set using the form
671.Bd -literal -offset indent
672name=value
673.Ed
674.Pp
675Variables set by the user must have a name consisting solely
676of alphabetics, numerics, and underscores - the first of which
677must not be numeric.  A parameter can also be denoted by a number
678or a special character as explained below.
679.Ss Positional Parameters
680A positional parameter is a parameter denoted by a number (n > 0).
681The shell sets these initially to the values of its commandline
682arguments that follow the name of the shell script.  The
683.Xr set 1
684builtin can also be used to set or reset them.
685.Ss Special Parameters
686A special parameter is a parameter denoted by one of the following
687special characters.  The value of the parameter is listed
688next to its character.
689.Bl -hang
690.It *
691Expands to the positional parameters, starting from one.  When
692the expansion occurs within a double-quoted string
693it expands to a single field with the value of each parameter
694separated by the first character of the IFS variable, or by a
695<space> if IFS is unset.
696.It @
697Expands to the positional parameters, starting from one.  When
698the expansion occurs within double-quotes, each positional
699parameter expands as a separate argument.
700If there are no positional parameters, the
701expansion of @ generates zero arguments, even when @ is
702double-quoted.  What this basically means, for example, is
703if $1 is ``abc'' and $2 is ``def ghi'', then "$@" expands to
704the two arguments:
705.Bd -literal -offset indent
706"abc"   "def ghi"
707.Ed
708.It #
709Expands to the number of positional parameters.
710.It ?
711Expands to the exit status of the most recent pipeline.
712.It -
713(hyphen) Expands to the current option flags (the single-letter
714option names concatenated into a string) as specified on
715invocation, by the set builtin command, or implicitly
716by the shell.
717.It $
718Expands to the process ID of the invoked shell.  A subshell
719retains the same value of $ as its parent.
720.It !
721Expands to the process ID of the most recent background
722command executed from the current shell.  For a
723pipeline, the process ID is that of the last command in the
724pipeline.
725.It 0
726(zero) Expands to the name of the shell or shell script.
727.El
728.Ss Word Expansions
729This clause describes the various expansions that are
730performed on words.  Not all expansions are performed on
731every word, as explained later.
732.Pp
733Tilde expansions, parameter expansions, command substitutions,
734arithmetic expansions, and quote removals that occur within
735a single word expand to a single field.  It is only field
736splitting or pathname expansion that can create multiple
737fields from a single word. The single exception to this
738rule is the expansion of the special parameter @ within
739double-quotes, as was described above.
740.Pp
741The order of word expansion is:
742.Bl -enum
743.It
744Tilde Expansion, Parameter Expansion, Command Substitution,
745Arithmetic Expansion (these all occur at the same time).
746.It
747Field Splitting is performed on fields
748generated by step (1) unless the IFS variable is null.
749.It
750Pathname Expansion (unless set -f is in effect).
751.It
752Quote Removal.
753.El
754.Pp
755The $ character is used to introduce parameter expansion, command
756substitution, or arithmetic evaluation.
757.Ss Tilde Expansion (substituting a user's home directory)
758A word beginning with an unquoted tilde character (~) is
759subjected to tilde expansion.  All the characters up to
760a slash (/) or the end of the word are treated as a username
761and are replaced with the user's home directory.  If the
762username is missing (as in ~/foobar), the tilde is replaced
763with the value of the HOME variable (the current user's
764home directory).
765.Ss Parameter Expansion
766The format for parameter expansion is as follows:
767.Bd -literal -offset indent
768${expression}
769.Ed
770.Pp
771where expression consists of all characters until the matching }.  Any }
772escaped by a backslash or within a quoted string, and characters in
773embedded arithmetic expansions, command substitutions, and variable
774expansions, are not examined in determining the matching }.
775.Pp
776The simplest form for parameter expansion is:
777.Bd -literal -offset indent
778${parameter}
779.Ed
780.Pp
781The value, if any, of parameter is substituted.
782.Pp
783The parameter name or symbol can be enclosed in braces, which are
784optional except for positional parameters with more than one digit or
785when parameter is followed by a character that could be interpreted as
786part of the name.
787If a parameter expansion occurs inside double-quotes:
788.Bl -enum
789.It
790Pathname expansion is not performed on the results of the
791expansion.
792.It
793Field splitting is not performed on the results of the
794expansion, with the exception of @.
795.El
796.Pp
797In addition, a parameter expansion can be modified by using one of the
798following formats.
799.Bl -tag -width Ds
800.It Li ${parameter:-word}
801Use Default Values.  If parameter is unset or
802null, the expansion of word is
803substituted; otherwise, the value of
804parameter is substituted.
805.It Li ${parameter:=word}
806Assign Default Values.  If parameter is unset
807or null, the expansion of word is
808assigned to parameter.  In all cases, the
809final value of parameter is
810substituted.  Only variables, not positional
811parameters or special parameters, can be
812assigned in this way.
813.It Li ${parameter:?[word]}
814Indicate Error if Null or Unset.  If
815parameter is unset or null, the expansion of
816word (or a message indicating it is unset if
817word is omitted) is written to standard
818error and the shell exits with a nonzero
819exit status. Otherwise, the value of
820parameter is substituted.  An
821interactive shell need not exit.
822.It Li ${parameter:+word}
823Use Alternate Value.  If parameter is unset
824or null, null is substituted;
825otherwise, the expansion of word is
826substituted.
827.Pp
828In the parameter expansions shown previously, use of the colon in the
829format results in a test for a parameter that is unset or null; omission
830of the colon results in a test for a parameter that is only unset.
831.It Li ${#parameter}
832String Length.  The length in characters of
833the value of parameter.
834.Pp
835The following four varieties of parameter expansion provide for substring
836processing.  In each case, pattern matching notation (see Shell Patterns),
837rather
838than regular expression notation, is used to evaluate the patterns.
839If parameter is * or @, the result of the expansion is unspecified.
840Enclosing the full parameter expansion string in double-quotes does not
841cause the following four varieties of pattern characters to be quoted,
842whereas quoting characters within the braces has this effect.
843.It Li ${parameter%word}
844Remove Smallest Suffix Pattern.  The word
845is expanded to produce a pattern.  The
846parameter expansion then results in
847parameter, with the smallest portion of the
848suffix matched by the pattern deleted.
849.It Li ${parameter%%word}
850Remove Largest Suffix Pattern.  The word
851is expanded to produce a pattern.  The
852parameter expansion then results in
853parameter, with the largest portion of the
854suffix matched by the pattern deleted.
855.It Li ${parameter#word}
856Remove Smallest Prefix Pattern.  The word
857is expanded to produce a pattern.  The
858parameter expansion then results in
859parameter, with the smallest portion of the
860prefix matched by the pattern deleted.
861.It Li ${parameter##word}
862Remove Largest Prefix Pattern.  The word
863is expanded to produce a pattern.  The
864parameter expansion then results in
865parameter, with the largest portion of the
866prefix matched by the pattern deleted.
867.El
868.Ss Command Substitution
869Command substitution allows the output of a command to be substituted in
870place of the command name itself.  Command substitution occurs when
871the command is enclosed as follows:
872.Bd -literal -offset indent
873$(command)
874.Ed
875.Pp
876or (``backquoted'' version):
877.Bd -literal -offset indent
878`command`
879.Ed
880.Pp
881The shell expands the command substitution by executing command in a
882subshell environment and replacing the command substitution
883with the
884standard output of the command, removing sequences of one or more
885<newline>s at the end of the substitution.  (Embedded <newline>s before
886the end of the output are not removed; however, during field
887splitting, they may be translated into <space>s, depending on the value
888of IFS and quoting that is in effect.)
889.Ss Arithmetic Expansion
890Arithmetic expansion provides a mechanism for evaluating an arithmetic
891expression and substituting its value. The format for arithmetic
892expansion is as follows:
893.Bd -literal -offset indent
894$((expression))
895.Ed
896.Pp
897The expression is treated as if it were in double-quotes, except
898that a double-quote inside the expression is not treated specially.  The
899shell expands all tokens in the expression for parameter expansion,
900command substitution, and quote removal.
901.Pp
902Next, the shell treats this as an arithmetic expression and
903substitutes the value of the expression.
904.Ss White Space Splitting (Field Splitting)
905After parameter expansion, command substitution, and
906arithmetic expansion the shell scans the results of
907expansions and substitutions that did not occur in double-quotes for
908field splitting and multiple fields can result.
909.Pp
910The shell treats each character of the IFS as a delimiter and use
911the delimiters to split the results of parameter expansion and command
912substitution into fields.
913.Ss Pathname Expansion (File Name Generation)
914Unless the -f flag is set, file name generation is performed
915after word splitting is complete.  Each word is
916viewed as a series of patterns, separated by slashes.  The
917process of expansion replaces the word with the names of
918all existing files whose names can be formed by replacing
919each pattern with a string that matches the specified pattern.
920There are two restrictions on this: first, a pattern cannot match
921a string containing a slash, and second,
922a pattern cannot match a string starting with a period
923unless the first character of the pattern is a period.
924The next section describes the patterns used for both
925Pathname Expansion and the
926.Xr case 1
927command.
928.Ss Shell Patterns
929A pattern consists of normal characters, which match themselves,
930and meta-characters.   The meta-characters are
931``!'', ``*'', ``?'', and ``[''.  These characters lose
932their special meanings if they are quoted.  When command
933or variable substitution is performed and the dollar sign
934or back quotes are not double quoted, the value of the
935variable or the output of the command is scanned for these
936characters and they are turned into meta-characters.
937.Pp
938An asterisk (``*'') matches any string of characters.  A
939question mark matches any single character. A left
940bracket (``['') introduces a character class.  The end of
941the character class is indicated by a ``]''; if the ``]''
942is missing then the ``['' matches a ``['' rather than
943introducing a character class.  A character class matches
944any of the characters between the square brackets.  A
945range of characters may be specified using a minus sign.
946The character class may be complemented by making an
947exclamation point the first character of the character
948class.
949.Pp
950To include a ``]'' in a character class, make it the first
951character listed (after the ``!'', if any).  To include a
952minus sign, make it the first or last character listed.
953.Ss Builtins
954This section lists the builtin commands which
955are builtin because they need to perform some operation
956that can't be performed by a separate process.  In addition to
957these, there are several other commands that may be
958builtin for efficiency (e.g.
959.Xr printf 1 ,
960.Xr echo 1 ,
961.Xr test 1 ,
962etc).
963.Bl -tag -width Ds
964.It :
965A null command that returns a 0 (true) exit value.
966.It \&. file
967The commands in the specified file are read and executed by the shell.
968.It alias  [ name[=string] ...  ]
969If name=string is specified, the shell defines the
970alias ``name'' with value ``string''.  If just ``name''
971is specified, the value of the alias ``name'' is printed.
972With no arguments, the alias builtin prints the
973names and values of all defined aliases (see unalias).
974.It bg [ job ] ...
975Continue the specified jobs (or the current job if no
976jobs are given) in the background.
977.It command command arg ...
978Execute the specified builtin command.  (This is useful when you
979have a shell function with the same name
980as a builtin command.)
981.It cd [ directory ]
982Switch to the specified directory (default $HOME).
983If the an entry for CDPATH appears in the environment
984of the cd command or the shell variable CDPATH is set
985and the directory name does not begin with a slash,
986then the directories listed in CDPATH will be
987searched for the specified directory.  The format of
988CDPATH is the same as that of PATH. In an interactive shell,
989the cd command will print out the name of
990the directory that it actually switched to if this is
991different from the name that the user gave.  These
992may be different either because the CDPATH mechanism
993was used or because a symbolic link was crossed.
994.It eval string ...
995Concatenate all the arguments with spaces.  Then
996re-parse and execute the
997command.
998.It exec [ command arg ...  ]
999Unless command is omitted, the shell process is
1000replaced with the specified program (which must be a
1001real program, not a shell builtin or function).  Any
1002redirections on the exec command are marked as permanent,
1003so that they are not undone when the exec command finishes.
1004.It exit [ exitstatus ]
1005Terminate the shell process.  If exitstatus is given
1006it is used as the exit status of the shell; otherwise
1007the exit status of the preceding command is used.
1008.It export name ...
1009The specified names are exported so that they will
1010appear in the environment of subsequent commands.
1011The only way to un-export a variable is to unset it.
1012The shell allows the value of a variable to be set at the
1013same time it is exported by writing
1014.Bd -literal -offset indent
1015export name=value
1016.Ed
1017.Pp
1018With no arguments the export command lists the names
1019of all exported variables.
1020.It fc [-e editor] [first [last]]
1021.It fc -l [-nr] [first [last]]
1022.It fc -s [old=new] [first]
1023The fc builtin lists, or edits and re-executes, commands
1024previously entered to an interactive shell.
1025.Bl -tag -width Ds
1026.It -e editor
1027Use the editor named by editor to edit the commands.  The
1028editor string is a command name, subject to search via the
1029PATH variable.  The value in the FCEDIT variable
1030is used as a default when -e is not specified.  If
1031FCEDIT is null or unset, the value of the EDITOR
1032variable is used.  If EDITOR is null or unset,
1033.Xr ed 1
1034is used as the editor.
1035.It -l (ell)
1036List the commands rather than invoking
1037an editor on them.  The commands are written in the
1038sequence indicated by the first and last operands, as
1039affected by -r, with each command preceded by the command
1040number.
1041.It -n
1042Suppress command numbers when listing with -l.
1043.It -r
1044Reverse the order of the commands listed (with -l) or
1045edited (with neither -l nor -s).
1046.It -s
1047Re-execute the command without invoking an editor.
1048.It first
1049.It last
1050Select the commands to list or edit.  The number of
1051previous commands that can be accessed are determined
1052by the value of the HISTSIZE variable.  The value of first
1053or last or both are one of the following:
1054.It [+]number
1055A positive number representing a command
1056number; command numbers can be displayed
1057with the -l option.
1058.It -number
1059A negative decimal number representing the
1060command that was executed number of
1061commands previously.  For example, -1 is
1062the immediately previous command.
1063.It string
1064A string indicating the most recently
1065entered command that begins with that
1066string.  If the old=new operand is not also
1067specified with -s, the string form of the
1068first operand cannot contain an embedded
1069equal sign.
1070.El
1071.\".Pp
1072The following environment variables affect the execution of fc:
1073.Bl -tag -width Ds
1074.It Va FCEDIT
1075Name of the editor to use.
1076.It Va HISTSIZE
1077The number of previous commands that are accessable.
1078.El
1079.It fg [ job ]
1080Move the specified job or the current job to the
1081foreground.
1082.It getopts optstring var
1083The POSIX getopts command.
1084The getopts command deprecates the older getopt command.
1085The first argument should be a series of letters, each possibly
1086followed by a colon which indicates that the option takes an argument.
1087The specified variable is set to the parsed option.  The index of
1088the next argument is placed into the shell variable OPTIND.
1089If an option takes an argument, it is placed into the shell variable
1090OPTARG.  If an invalid option is encountered, var is set to '?'.
1091It returns a false value (1) when it encounters the end of the options.
1092.It hash -rv command ...
1093The shell maintains a hash table which remembers the
1094locations of commands.  With no arguments whatsoever,
1095the hash command prints out the contents of this
1096table.  Entries which have not been looked at since
1097the last cd command are marked with an asterisk; it
1098is possible for these entries to be invalid.
1099.Pp
1100With arguments, the hash command removes the specified commands
1101from the hash table (unless they are
1102functions) and then locates them.   With the -v
1103option, hash prints the locations of the commands as
1104it finds them.  The -r option causes the hash command
1105to delete all the entries in the hash table except
1106for functions.
1107.It jobid [ job ]
1108Print the process id's of the processes in the job.
1109If the job argument is omitted, use the current job.
1110.It jobs
1111This command lists out all the background processes
1112which are children of the current shell process.
1113.It pwd
1114Print the current directory.  The builtin command may
1115differ from the program of the same name because the
1116builtin command remembers what the current directory
1117is rather than recomputing it each time.  This makes
1118it faster.  However, if the current directory is
1119renamed, the builtin version of pwd will continue to
1120print the old name for the directory.
1121.It read [ -p prompt ] [ -e ] variable ...
1122The prompt is printed if the -p option is specified
1123and the standard input is a terminal.  Then a line is
1124read from the standard input.  The trailing newline
1125is deleted from the line and the line is split as
1126described in the section on word splitting above, and
1127the pieces are assigned to the variables in order.
1128If there are more pieces than variables, the remaining
1129pieces (along with the characters in IFS that
1130separated them) are assigned to the last variable.
1131If there are more variables than pieces, the remaining
1132variables are assigned the null string.
1133.Pp
1134The -e option causes any backslashes in the input to
1135be treated specially.  If a backslash is followed by
1136a newline, the backslash and the newline will be
1137deleted.   If a backslash is followed by any other
1138character, the backslash will be deleted and the following
1139character will be treated as though it were
1140not in IFS, even if it is.
1141.It readonly name ...
1142The specified names are marked as read only, so that
1143they cannot be subsequently modified or unset.  The shell
1144allows the value of a variable to be set at the same
1145time it is marked read only by writing
1146using the following form
1147.Bd -literal -offset indent
1148readonly name=value
1149.Ed
1150.Pp
1151With no arguments the readonly command lists the
1152names of all read only variables.
1153.It Li "set [ { -options | +options | -- } ] arg ...
1154The set command performs three different functions.
1155.Bl -item
1156.It
1157With no arguments, it lists the values of all shell
1158variables.
1159.It
1160If options are given, it sets the specified option
1161flags, or clears them as described in the section
1162called ``Argument List Processing''.
1163.It
1164The third use of the set command is to set the values
1165of the shell's positional parameters to the specified
1166args.  To change the positional parameters without
1167changing any options, use ``--'' as the first argument
1168to set.  If no args are present, the set command
1169will clear all the positional parameters (equivalent
1170to executing ``shift $#''.
1171.El
1172.Pp
1173.It setvar variable value
1174Assigns value to variable. (In general it is better
1175to write variable=value rather than using setvar.
1176Setvar is intended to be used in functions that
1177assign values to variables whose names are passed as
1178parameters.)
1179.It shift [ n ]
1180Shift the positional parameters n times.  A shift
1181sets the value of $1 to the value of $2, the value of
1182$2 to the value of $3, and so on, decreasing the
1183value of $# by one.  If there are zero positional
1184parameters, shifting doesn't do anything.
1185.It trap [ action ] signal ...
1186Cause the shell to parse and execute action when any
1187of the specified signals are received.  The signals
1188are specified by signal number.  Action may be null
1189or omitted; the former causes the specified signal to
1190be ignored and the latter causes the default action
1191to be taken.  When the shell forks off a subshell, it
1192resets trapped (but not ignored) signals to the
1193default action.  The trap command has no effect on
1194signals that were ignored on entry to the shell.
1195.It type [name] ...
1196Interpret each name as a command and print the
1197resolution of the command search. Possible resolutions are:
1198shell keyword, alias, shell builtin, command, tracked alias
1199and not found.  For aliases the alias expansion is printed;
1200for commands and tracked aliases the complete pathname of
1201the command is printed.
1202.It ulimit [ -HSacdflmnust ] [ limit ]
1203Set or display resource limits (see
1204.Xr getrlimit 2 ).
1205If ``limit'' is specified, the named resource will be set;
1206otherwise the current resource value will be displayed.
1207.Pp
1208If ``-H'' is specified, the hard limits will be
1209set or displayed.  While everybody is allowed to reduce a
1210hard limit, only the superuser can increase it.  Option ``-S''
1211specifies the soft limits instead.  When displaying limits,
1212only one of ``-S'' or ``-H'' can be given.  The default is
1213to display the soft limits, and to set both, the hard and
1214the soft limits.
1215.Pp
1216Option ``-a'' requests to display all resources.  The parameter
1217``limit'' is not acceptable in this mode.
1218.Pp
1219The remaining options specify which resource value is to be
1220displayed or modified.  They are mutually exclusive.
1221.Bl -tag -width Ds
1222.It -c coredumpsize
1223The maximal size of core dump files, in 512-byte blocks.
1224.It -d datasize
1225The maximal size of the data segment of a process, in kilobytes.
1226.It -f filesize
1227The maximal size of a file, in 512-byte blocks.  This is the
1228default.
1229.It -l lockedmem
1230The maximal size of memory that can be locked by a process, in
1231kilobytes.
1232.It -m memoryuse
1233The maximal resident set size of a process, in kilobytes.
1234.It -n nofiles
1235The maximal number of descriptors that could be opened by a process.
1236.It -s stacksize
1237The maximal size of the stack segment, in kilobytes.
1238.It -t time
1239The maximal amount of CPU time to be used by each process, in seconds.
1240.It -u userproc
1241The maximal number of simultaneous processes for this user ID.
1242.El
1243.It umask [ mask ]
1244Set the value of umask (see
1245.Xr umask 2 )
1246to the specified
1247octal value. If the argument is omitted, the
1248umask value is printed.
1249.It unalias [-a] [name]
1250If ``name'' is specified, the shell removes that alias.
1251If ``-a'' is specified, all aliases are removed.
1252.It unset name ...
1253The specified variables and functions are unset and
1254unexported. If a given name corresponds to both a
1255variable and a function, both the variable and the
1256function are unset.
1257.It wait [ job ]
1258Wait for the specified job to complete and return the
1259exit status of the last process in the job. If the
1260argument is omitted, wait for all jobs to complete
1261and the return an exit status of zero.
1262.El
1263.Ss Commandline Editing
1264When
1265.Nm
1266is being used interactively from a terminal, the current command
1267and the command history (see fc in Builtins) can be edited using vi-mode
1268commandline editing.  This mode uses commands similar
1269to a subset of those described in the vi man page.
1270The command 'set -o vi' enables vi-mode editing and places
1271.Nm
1272into vi insert mode.  With vi-mode enabled,
1273.Nm
1274can be switched between insert mode and command mode by typing <ESC>.
1275Hitting <return> while in command mode will pass the line to the shell.
1276.Pp
1277Similarly, the 'set -o emacs' command can be used to enable a subset of
1278emacs-style commandline editing features.
1279.Sh HISTORY
1280A
1281.Nm
1282command appeared in
1283.At V.1 .
1284