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