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