xref: /netbsd-src/bin/sh/sh.1 (revision b78992537496bc71ee3d761f9fe0be0fc0a9a001)
1.\"	$NetBSD: sh.1,v 1.87 2007/06/24 17:57:56 christos Exp $
2.\" Copyright (c) 1991, 1993
3.\"	The Regents of the University of California.  All rights reserved.
4.\"
5.\" This code is derived from software contributed to Berkeley by
6.\" Kenneth Almquist.
7.\"
8.\" Redistribution and use in source and binary forms, with or without
9.\" modification, are permitted provided that the following conditions
10.\" are met:
11.\" 1. Redistributions of source code must retain the above copyright
12.\"    notice, this list of conditions and the following disclaimer.
13.\" 2. Redistributions in binary form must reproduce the above copyright
14.\"    notice, this list of conditions and the following disclaimer in the
15.\"    documentation and/or other materials provided with the distribution.
16.\" 3. Neither the name of the University nor the names of its contributors
17.\"    may be used to endorse or promote products derived from this software
18.\"    without specific prior written permission.
19.\"
20.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30.\" SUCH DAMAGE.
31.\"
32.\"	@(#)sh.1	8.6 (Berkeley) 5/4/95
33.\"
34.Dd June 24, 2007
35.Os
36.Dt SH 1
37.Sh NAME
38.Nm sh
39.Nd command interpreter (shell)
40.Sh SYNOPSIS
41.Nm
42.Bk -words
43.Op Fl aCefnuvxIimqVEb
44.Op Cm +aCefnuvxIimqVEb
45.Ek
46.Bk -words
47.Op Fl o Ar option_name
48.Op Cm +o Ar option_name
49.Ek
50.Bk -words
51.Op Ar command_file Oo Ar argument ... Oc
52.Ek
53.Nm
54.Fl c
55.Bk -words
56.Op Fl aCefnuvxIimqVEb
57.Op Cm +aCefnuvxIimqVEb
58.Ek
59.Bk -words
60.Op Fl o Ar option_name
61.Op Cm +o Ar option_name
62.Ek
63.Bk -words
64.Ar command_string
65.Op Ar command_name Oo Ar argument ... Oc
66.Ek
67.Nm
68.Fl s
69.Bk -words
70.Op Fl aCefnuvxIimqVEb
71.Op Cm +aCefnuvxIimqVEb
72.Ek
73.Bk -words
74.Op Fl o Ar option_name
75.Op Cm +o Ar option_name
76.Ek
77.Bk -words
78.Op Ar argument ...
79.Ek
80.Sh DESCRIPTION
81.Nm
82is the standard command interpreter for the system.
83The current version of
84.Nm
85is in the process of being changed to conform with the
86.Tn POSIX
871003.2 and 1003.2a specifications for the shell.
88This version has many
89features which make it appear similar in some respects to the Korn shell,
90but it is not a Korn shell clone (see
91.Xr ksh 1 ) .
92Only features designated by
93.Tn POSIX ,
94plus a few Berkeley extensions, are being incorporated into this shell.
95.\" We expect
96.\" .Tn POSIX
97.\" conformance by the time 4.4 BSD is released.
98This man page is not intended
99to be a tutorial or a complete specification of the shell.
100.Ss Overview
101The shell is a command that reads lines from either a file or the
102terminal, interprets them, and generally executes other commands.
103It is the program that is running when a user logs into the system
104(although a user can select a different shell with the
105.Xr chsh 1
106command).
107The shell implements a language that has flow control
108constructs, a macro facility that provides a variety of features in
109addition to data storage, along with built in history and line editing
110capabilities.
111It incorporates many features to aid interactive use and
112has the advantage that the interpretative language is common to both
113interactive and non-interactive use (shell scripts).
114That is, commands
115can be typed directly to the running shell or can be put into a file and
116the file can be executed directly by the shell.
117.Ss Invocation
118If no arguments are present and if the standard input of the shell
119is connected to a terminal (or if the
120.Fl i
121flag is set),
122and the
123.Fl c
124option is not present, the shell is considered an interactive shell.
125An interactive shell generally prompts before each command and handles
126programming and command errors differently (as described below).
127When first starting,
128the shell inspects argument 0, and if it begins with a dash
129.Sq - ,
130the shell is also considered
131a login shell.
132This is normally done automatically by the system
133when the user first logs in.
134A login shell first reads commands
135from the files
136.Pa /etc/profile
137and
138.Pa .profile
139if they exist.
140If the environment variable
141.Ev ENV
142is set on entry to a shell, or is set in the
143.Pa .profile
144of a login shell, the shell next reads
145commands from the file named in
146.Ev ENV .
147Therefore, a user should place commands that are to be executed only at
148login time in the
149.Pa .profile
150file, and commands that are executed for every shell inside the
151.Ev ENV
152file.
153To set the
154.Ev ENV
155variable to some file, place the following line in your
156.Pa .profile
157of your home directory
158.Pp
159.Dl ENV=$HOME/.shinit; export ENV
160.Pp
161substituting for
162.Dq .shinit
163any filename you wish.
164Since the
165.Ev ENV
166file is read for every invocation of the shell, including shell scripts
167and non-interactive shells, the following paradigm is useful for
168restricting commands in the
169.Ev ENV
170file to interactive invocations.
171Place commands within the
172.Dq case
173and
174.Dq esac
175below (these commands are described later):
176.Pp
177.Bl -item -compact -offset indent
178.It
179.Li case $- in *i*)
180.Bl -item -compact -offset indent
181.It
182.Li # commands for interactive use only
183.It
184.Li ...
185.El
186.It
187.Li esac
188.El
189.Pp
190If command line arguments besides the options have been specified, then
191the shell treats the first argument as the name of a file from which to
192read commands (a shell script), and the remaining arguments are set as the
193positional parameters of the shell ($1, $2, etc).
194Otherwise, the shell
195reads commands from its standard input.
196.Ss Argument List Processing
197All of the single letter options have a corresponding name that can be
198used as an argument to the
199.Fl o
200option.
201The set
202.Fl o
203name is provided next to the single letter option in
204the description below.
205Specifying a dash
206.Dq -
207turns the option on, while using a plus
208.Dq +
209disables the option.
210The following options can be set from the command line or
211with the
212.Ic set
213built-in (described later).
214.Bl -tag -width aaaallexportfoo -offset indent
215.It Fl a Em allexport
216Export all variables assigned to.
217.It Fl c
218Read commands from the
219.Ar command_string
220operand instead of from the standard input.
221Special parameter 0 will be set from the
222.Ar command_name
223operand and the positional parameters ($1, $2, etc.)
224set from the remaining argument operands.
225.It Fl C Em noclobber
226Don't overwrite existing files with
227.Dq \*[Gt] .
228.It Fl e Em errexit
229If not interactive, exit immediately if any untested command fails.
230The exit status of a command is considered to be
231explicitly tested if the command is used to control an
232.Ic if ,
233.Ic elif ,
234.Ic while ,
235or
236.Ic until ;
237or if the command is the left hand operand of an
238.Dq \*[Am]\*[Am]
239or
240.Dq ||
241operator.
242.It Fl f Em noglob
243Disable pathname expansion.
244.It Fl n Em noexec
245If not interactive, read commands but do not execute them.
246This is useful for checking the syntax of shell scripts.
247.It Fl u Em nounset
248Write a message to standard error when attempting to expand a variable
249that is not set, and if the shell is not interactive, exit immediately.
250.It Fl v Em verbose
251The shell writes its input to standard error as it is read.
252Useful for debugging.
253.It Fl x Em xtrace
254Write each command to standard error (preceded by a
255.Sq +\  )
256before it is executed.
257Useful for debugging.
258.It Fl q Em quietprofile
259If the
260.Fl v
261or
262.Fl x
263options have been set, do not apply them when reading
264initialization files, these being
265.Pa /etc/profile ,
266.Pa .profile ,
267and the file specified by the
268.Ev ENV
269environment variable.
270.It Fl I Em ignoreeof
271Ignore EOFs from input when interactive.
272.It Fl i Em interactive
273Force the shell to behave interactively.
274.It Fl m Em monitor
275Turn on job control (set automatically when interactive).
276.It Fl s Em stdin
277Read commands from standard input (set automatically if no file arguments
278are present).
279This option has no effect when set after the shell has
280already started running (i.e. with
281.Ic set ) .
282.It Fl V Em vi
283Enable the built-in
284.Xr vi 1
285command line editor (disables
286.Fl E
287if it has been set).
288(See the
289.Sx Command Line Editing
290section below.)
291.It Fl E Em emacs
292Enable the built-in emacs style
293command line editor (disables
294.Fl V
295if it has been set).
296(See the
297.Sx Command Line Editing
298section below.)
299.It Fl b Em notify
300Enable asynchronous notification of background job completion.
301(UNIMPLEMENTED for 4.4alpha)
302.It "\ \ " Em cdprint
303Make an interactive shell always print the new directory name when
304changed by the
305.Ic cd
306command.
307.It "\ \ " Em tabcomplete
308Enables filename completion in the command line editor.
309Typing a tab character will extend the current input word to match a
310filename.
311If more than one filename matches it is only extended to be the common prefix.
312Typing a second tab character will list all the matching names.
313.El
314.Ss Lexical Structure
315The shell reads input in terms of lines from a file and breaks it up into
316words at whitespace (blanks and tabs), and at certain sequences of
317characters that are special to the shell called
318.Dq operators .
319There are two types of operators: control operators and redirection
320operators (their meaning is discussed later).
321Following is a list of operators:
322.Bl -ohang -offset indent
323.It "Control operators:"
324.Dl \*[Am]  \*[Am]\*[Am]  \&(  \&)  \&;  ;; | || \*[Lt]newline\*[Gt]
325.It "Redirection operators:"
326.Dl \*[Lt]  \*[Gt]  \*[Gt]|  \*[Lt]\*[Lt]  \*[Gt]\*[Gt]  \*[Lt]\*[Am]  \*[Gt]\*[Am]  \*[Lt]\*[Lt]-  \*[Lt]\*[Gt]
327.El
328.Ss Quoting
329Quoting is used to remove the special meaning of certain characters or
330words to the shell, such as operators, whitespace, or keywords.
331There are three types of quoting: matched single quotes,
332matched double quotes, and backslash.
333.Ss Backslash
334A backslash preserves the literal meaning of the following
335character, with the exception of
336.Aq newline .
337A backslash preceding a
338.Aq newline
339is treated as a line continuation.
340.Ss Single Quotes
341Enclosing characters in single quotes preserves the literal meaning of all
342the characters (except single quotes, making it impossible to put
343single-quotes in a single-quoted string).
344.Ss Double Quotes
345Enclosing characters within double quotes preserves the literal
346meaning of all characters except dollar sign
347.Pq $ ,
348backquote
349.Pq ` ,
350and backslash
351.Pq \e .
352The backslash inside double quotes is historically weird, and serves to
353quote only the following characters:
354.Dl $  `  \*q  \e  \*[Lt]newline\*[Gt] .
355Otherwise it remains literal.
356.Ss Reserved Words
357Reserved words are words that have special meaning to the
358shell and are recognized at the beginning of a line and
359after a control operator.
360The following are reserved words:
361.Bl -column while while while while while -offset indent
362.It ! Ta elif Ta fi Ta while Ta case
363.It else Ta for Ta then Ta { Ta }
364.It do Ta done Ta until Ta if Ta esac
365.El
366.Pp
367Their meaning is discussed later.
368.Ss Aliases
369An alias is a name and corresponding value set using the
370.Ic alias
371built-in command.
372Whenever a reserved word may occur (see above),
373and after checking for reserved words, the shell
374checks the word to see if it matches an alias.
375If it does, it replaces it in the input stream with its value.
376For example, if there is an alias called
377.Dq lf
378with the value
379.Dq "ls -F" ,
380then the input:
381.Pp
382.Dl lf foobar Aq return
383.Pp
384would become
385.Pp
386.Dl ls -F foobar Aq return
387.Pp
388Aliases provide a convenient way for naive users to create shorthands for
389commands without having to learn how to create functions with arguments.
390They can also be used to create lexically obscure code.
391This use is discouraged.
392.Ss Commands
393The shell interprets the words it reads according to a language, the
394specification of which is outside the scope of this man page (refer to the
395BNF in the
396.Tn POSIX
3971003.2 document).
398Essentially though, a line is read and if the first
399word of the line (or after a control operator) is not a reserved word,
400then the shell has recognized a simple command.
401Otherwise, a complex
402command or some other special construct may have been recognized.
403.Ss Simple Commands
404If a simple command has been recognized, the shell performs
405the following actions:
406.Bl -enum -offset indent
407.It
408Leading words of the form
409.Dq name=value
410are stripped off and assigned to the environment of the simple command.
411Redirection operators and their arguments (as described below) are
412stripped off and saved for processing.
413.It
414The remaining words are expanded as described in
415the section called
416.Dq Expansions ,
417and the first remaining word is considered the command name and the
418command is located.
419The remaining words are considered the arguments of the command.
420If no command name resulted, then the
421.Dq name=value
422variable assignments recognized in item 1 affect the current shell.
423.It
424Redirections are performed as described in the next section.
425.El
426.Ss Redirections
427Redirections are used to change where a command reads its input or sends
428its output.
429In general, redirections open, close, or duplicate an
430existing reference to a file.
431The overall format used for redirection is:
432.Pp
433.Dl [n] Va redir-op Ar file
434.Pp
435where
436.Va redir-op
437is one of the redirection operators mentioned previously.
438Following is a list of the possible redirections.
439The
440.Bq n
441is an optional number, as in
442.Sq 3
443(not
444.Sq Bq 3 ) ,
445that refers to a file descriptor.
446.Bl -tag -width aaabsfiles -offset indent
447.It [n] Ns \*[Gt] file
448Redirect standard output (or n) to file.
449.It [n] Ns \*[Gt]| file
450Same, but override the
451.Fl C
452option.
453.It [n] Ns \*[Gt]\*[Gt] file
454Append standard output (or n) to file.
455.It [n] Ns \*[Lt] file
456Redirect standard input (or n) from file.
457.It [n1] Ns \*[Lt]\*[Am] Ns n2
458Duplicate standard input (or n1) from file descriptor n2.
459.It [n] Ns \*[Lt]\*[Am]-
460Close standard input (or n).
461.It [n1] Ns \*[Gt]\*[Am] Ns n2
462Duplicate standard output (or n1) to n2.
463.It [n] Ns \*[Gt]\*[Am]-
464Close standard output (or n).
465.It [n] Ns \*[Lt]\*[Gt] file
466Open file for reading and writing on standard input (or n).
467.El
468.Pp
469The following redirection is often called a
470.Dq here-document .
471.Bl -item -offset indent
472.It
473.Li [n]\*[Lt]\*[Lt] delimiter
474.Dl here-doc-text ...
475.Li delimiter
476.El
477.Pp
478All the text on successive lines up to the delimiter is saved away and
479made available to the command on standard input, or file descriptor n if
480it is specified.
481If the delimiter as specified on the initial line is
482quoted, then the here-doc-text is treated literally, otherwise the text is
483subjected to parameter expansion, command substitution, and arithmetic
484expansion (as described in the section on
485.Dq Expansions ) .
486If the operator is
487.Dq \*[Lt]\*[Lt]-
488instead of
489.Dq \*[Lt]\*[Lt] ,
490then leading tabs in the here-doc-text are stripped.
491.Ss Search and Execution
492There are three types of commands: shell functions, built-in commands, and
493normal programs -- and the command is searched for (by name) in that order.
494They each are executed in a different way.
495.Pp
496When a shell function is executed, all of the shell positional parameters
497(except $0, which remains unchanged) are set to the arguments of the shell
498function.
499The variables which are explicitly placed in the environment of
500the command (by placing assignments to them before the function name) are
501made local to the function and are set to the values given.
502Then the command given in the function definition is executed.
503The positional parameters are restored to their original values
504when the command completes.
505This all occurs within the current shell.
506.Pp
507Shell built-ins are executed internally to the shell, without spawning a
508new process.
509.Pp
510Otherwise, if the command name doesn't match a function or built-in, the
511command is searched for as a normal program in the file system (as
512described in the next section).
513When a normal program is executed, the shell runs the program,
514passing the arguments and the environment to the program.
515If the program is not a normal executable file (i.e., if it does
516not begin with the "magic number" whose
517.Tn ASCII
518representation is "#!", so
519.Xr execve 2
520returns
521.Er ENOEXEC
522then) the shell will interpret the program in a subshell.
523The child shell will reinitialize itself in this case,
524so that the effect will be as if a
525new shell had been invoked to handle the ad-hoc shell script, except that
526the location of hashed commands located in the parent shell will be
527remembered by the child.
528.Pp
529Note that previous versions of this document and the source code itself
530misleadingly and sporadically refer to a shell script without a magic
531number as a "shell procedure".
532.Ss Path Search
533When locating a command, the shell first looks to see if it has a shell
534function by that name.
535Then it looks for a built-in command by that name.
536If a built-in command is not found, one of two things happen:
537.Bl -enum
538.It
539Command names containing a slash are simply executed without performing
540any searches.
541.It
542The shell searches each entry in
543.Ev PATH
544in turn for the command.
545The value of the
546.Ev PATH
547variable should be a series of entries separated by colons.
548Each entry consists of a directory name.
549The current directory may be indicated
550implicitly by an empty directory name, or explicitly by a single period.
551.El
552.Ss Command Exit Status
553Each command has an exit status that can influence the behavior
554of other shell commands.
555The paradigm is that a command exits
556with zero for normal or success, and non-zero for failure,
557error, or a false indication.
558The man page for each command
559should indicate the various exit codes and what they mean.
560Additionally, the built-in commands return exit codes, as does
561an executed shell function.
562.Pp
563If a command consists entirely of variable assignments then the
564exit status of the command is that of the last command substitution
565if any, otherwise 0.
566.Ss Complex Commands
567Complex commands are combinations of simple commands with control
568operators or reserved words, together creating a larger complex command.
569More generally, a command is one of the following:
570.Bl -bullet
571.It
572simple command
573.It
574pipeline
575.It
576list or compound-list
577.It
578compound command
579.It
580function definition
581.El
582.Pp
583Unless otherwise stated, the exit status of a command is that of the last
584simple command executed by the command.
585.Ss Pipelines
586A pipeline is a sequence of one or more commands separated
587by the control operator |.
588The standard output of all but
589the last command is connected to the standard input
590of the next command.
591The standard output of the last
592command is inherited from the shell, as usual.
593.Pp
594The format for a pipeline is:
595.Pp
596.Dl [!] command1 [ | command2 ...]
597.Pp
598The standard output of command1 is connected to the standard input of
599command2.
600The standard input, standard output, or both of a command is
601considered to be assigned by the pipeline before any redirection specified
602by redirection operators that are part of the command.
603.Pp
604If the pipeline is not in the background (discussed later), the shell
605waits for all commands to complete.
606.Pp
607If the reserved word ! does not precede the pipeline, the exit status is
608the exit status of the last command specified in the pipeline.
609Otherwise, the exit status is the logical NOT of the exit status of the
610last command.
611That is, if the last command returns zero, the exit status
612is 1; if the last command returns greater than zero, the exit status is
613zero.
614.Pp
615Because pipeline assignment of standard input or standard output or both
616takes place before redirection, it can be modified by redirection.
617For example:
618.Pp
619.Dl $ command1 2\*[Gt]\*[Am]1 | command2
620.Pp
621sends both the standard output and standard error of command1
622to the standard input of command2.
623.Pp
624A ; or
625.Aq newline
626terminator causes the preceding AND-OR-list (described
627next) to be executed sequentially; a \*[Am] causes asynchronous execution of
628the preceding AND-OR-list.
629.Pp
630Note that unlike some other shells, each process in the pipeline is a
631child of the invoking shell (unless it is a shell built-in, in which case
632it executes in the current shell -- but any effect it has on the
633environment is wiped).
634.Ss Background Commands -- \*[Am]
635If a command is terminated by the control operator ampersand (\*[Am]), the
636shell executes the command asynchronously -- that is, the shell does not
637wait for the command to finish before executing the next command.
638.Pp
639The format for running a command in background is:
640.Pp
641.Dl command1 \*[Am] [command2 \*[Am] ...]
642.Pp
643If the shell is not interactive, the standard input of an asynchronous
644command is set to
645.Pa /dev/null .
646.Ss Lists -- Generally Speaking
647A list is a sequence of zero or more commands separated by newlines,
648semicolons, or ampersands, and optionally terminated by one of these three
649characters.
650The commands in a list are executed in the order they are written.
651If command is followed by an ampersand, the shell starts the
652command and immediately proceed onto the next command; otherwise it waits
653for the command to terminate before proceeding to the next one.
654.Ss Short-Circuit List Operators
655.Dq \*[Am]\*[Am]
656and
657.Dq ||
658are AND-OR list operators.
659.Dq \*[Am]\*[Am]
660executes the first command, and then executes the second command if and only
661if the exit status of the first command is zero.
662.Dq ||
663is similar, but executes the second command if and only if the exit status
664of the first command is nonzero.
665.Dq \*[Am]\*[Am]
666and
667.Dq ||
668both have the same priority.
669Note that these operators are left-associative, so
670.Dq true || echo bar \*[Am]\*[Am] echo baz
671writes
672.Dq baz
673and nothing else.
674This is not the way it works in C.
675Also, if you forget the left-hand side (for example when continuing lines but
676forgetting to use a backslash) it defaults to a true statement.
677This behavior is not useful and should not be relied upon.
678.Ss Flow-Control Constructs -- if, while, for, case
679The syntax of the if command is
680.Bd -literal -offset indent
681if list
682then list
683[ elif list
684then    list ] ...
685[ else list ]
686fi
687.Ed
688.Pp
689The syntax of the while command is
690.Bd -literal -offset indent
691while list
692do   list
693done
694.Ed
695.Pp
696The two lists are executed repeatedly while the exit status of the
697first list is zero.
698The until command is similar, but has the word
699until in place of while, which causes it to
700repeat until the exit status of the first list is zero.
701.Pp
702The syntax of the for command is
703.Bd -literal -offset indent
704for variable in word ...
705do   list
706done
707.Ed
708.Pp
709The words are expanded, and then the list is executed repeatedly with the
710variable set to each word in turn.
711do and done may be replaced with
712.Dq {
713and
714.Dq } .
715.Pp
716The syntax of the break and continue command is
717.Bd -literal -offset indent
718break [ num ]
719continue [ num ]
720.Ed
721.Pp
722Break terminates the num innermost for or while loops.
723Continue continues with the next iteration of the innermost loop.
724These are implemented as built-in commands.
725.Pp
726The syntax of the case command is
727.Bd -literal -offset indent
728case word in
729pattern) list ;;
730\&...
731esac
732.Ed
733.Pp
734The pattern can actually be one or more patterns (see
735.Sx Shell Patterns
736described later), separated by
737.Dq \*(Ba
738characters.
739.Ss Grouping Commands Together
740Commands may be grouped by writing either
741.Pp
742.Dl (list)
743.Pp
744or
745.Pp
746.Dl { list; }
747.Pp
748The first of these executes the commands in a subshell.
749Built-in commands grouped into a (list) will not affect the current shell.
750The second form does not fork another shell so is slightly more efficient.
751Grouping commands together this way allows you to redirect
752their output as though they were one program:
753.Pp
754.Bd -literal -offset indent
755{ echo -n \*q hello \*q ; echo \*q world" ; } \*[Gt] greeting
756.Ed
757.Pp
758Note that
759.Dq }
760must follow a control operator (here,
761.Dq \&; )
762so that it is recognized as a reserved word and not as another command argument.
763.Ss Functions
764The syntax of a function definition is
765.Pp
766.Dl name ( ) command
767.Pp
768A function definition is an executable statement; when executed it
769installs a function named name and returns an exit status of zero.
770The command is normally a list enclosed between
771.Dq {
772and
773.Dq } .
774.Pp
775Variables may be declared to be local to a function by using a local
776command.
777This should appear as the first statement of a function, and the syntax is
778.Pp
779.Dl local [ variable | - ] ...
780.Pp
781.Dq Local
782is implemented as a built-in command.
783.Pp
784When a variable is made local, it inherits the initial value and exported
785and read-only flags from the variable with the same name in the surrounding
786scope, if there is one.
787Otherwise, the variable is initially unset.
788The shell uses dynamic scoping, so that if you make the variable x local to
789function f, which then calls function g, references to the variable x made
790inside g will refer to the variable x declared inside f, not to the global
791variable named x.
792.Pp
793The only special parameter that can be made local is
794.Dq - .
795Making
796.Dq -
797local causes any shell options that are changed via the set command inside the
798function to be restored to their original values when the function
799returns.
800.Pp
801The syntax of the return command is
802.Pp
803.Dl return [ exitstatus ]
804.Pp
805It terminates the currently executing function.
806Return is implemented as a built-in command.
807.Ss Variables and Parameters
808The shell maintains a set of parameters.
809A parameter denoted by a name is called a variable.
810When starting up, the shell turns all the environment
811variables into shell variables.
812New variables can be set using the form
813.Pp
814.Dl name=value
815.Pp
816Variables set by the user must have a name consisting solely of
817alphabetics, numerics, and underscores - the first of which must not be
818numeric.
819A parameter can also be denoted by a number or a special
820character as explained below.
821.Ss Positional Parameters
822A positional parameter is a parameter denoted by a number (n \*[Gt] 0).
823The shell sets these initially to the values of its command line arguments
824that follow the name of the shell script.
825The
826.Ic set
827built-in can also be used to set or reset them.
828.Ss Special Parameters
829A special parameter is a parameter denoted by one of the following special
830characters.
831The value of the parameter is listed next to its character.
832.Bl -tag -width thinhyphena
833.It *
834Expands to the positional parameters, starting from one.
835When the
836expansion occurs within a double-quoted string it expands to a single
837field with the value of each parameter separated by the first character of
838the
839.Ev IFS
840variable, or by a
841.Aq space
842if
843.Ev IFS
844is unset.
845.It @
846Expands to the positional parameters, starting from one.
847When the expansion occurs within double-quotes, each positional
848parameter expands as a separate argument.
849If there are no positional parameters, the
850expansion of @ generates zero arguments, even when @ is
851double-quoted.
852What this basically means, for example, is
853if $1 is
854.Dq abc
855and $2 is
856.Dq def ghi ,
857then
858.Qq $@
859expands to
860the two arguments:
861.Pp
862.Sm off
863.Dl \*q abc \*q \  \*q def\ ghi \*q
864.Sm on
865.It #
866Expands to the number of positional parameters.
867.It \&?
868Expands to the exit status of the most recent pipeline.
869.It - (Hyphen.)
870Expands to the current option flags (the single-letter
871option names concatenated into a string) as specified on
872invocation, by the set built-in command, or implicitly
873by the shell.
874.It $
875Expands to the process ID of the invoked shell.
876A subshell retains the same value of $ as its parent.
877.It \&!
878Expands to the process ID of the most recent background
879command executed from the current shell.
880For a pipeline, the process ID is that of the last command in the pipeline.
881.It 0 (Zero.)
882Expands to the name of the shell or shell script.
883.El
884.Ss Word Expansions
885This clause describes the various expansions that are performed on words.
886Not all expansions are performed on every word, as explained later.
887.Pp
888Tilde expansions, parameter expansions, command substitutions, arithmetic
889expansions, and quote removals that occur within a single word expand to a
890single field.
891It is only field splitting or pathname expansion that can
892create multiple fields from a single word.
893The single exception to this
894rule is the expansion of the special parameter @ within double-quotes, as
895was described above.
896.Pp
897The order of word expansion is:
898.Bl -enum
899.It
900Tilde Expansion, Parameter Expansion, Command Substitution,
901Arithmetic Expansion (these all occur at the same time).
902.It
903Field Splitting is performed on fields
904generated by step (1) unless the
905.Ev IFS
906variable is null.
907.It
908Pathname Expansion (unless set
909.Fl f
910is in effect).
911.It
912Quote Removal.
913.El
914.Pp
915The $ character is used to introduce parameter expansion, command
916substitution, or arithmetic evaluation.
917.Ss Tilde Expansion (substituting a user's home directory)
918A word beginning with an unquoted tilde character (~) is
919subjected to tilde expansion.
920All the characters up to
921a slash (/) or the end of the word are treated as a username
922and are replaced with the user's home directory.
923If the username is missing (as in
924.Pa ~/foobar ) ,
925the tilde is replaced with the value of the
926.Va HOME
927variable (the current user's home directory).
928.Ss Parameter Expansion
929The format for parameter expansion is as follows:
930.Pp
931.Dl ${expression}
932.Pp
933where expression consists of all characters until the matching
934.Dq } .
935Any
936.Dq }
937escaped by a backslash or within a quoted string, and characters in
938embedded arithmetic expansions, command substitutions, and variable
939expansions, are not examined in determining the matching
940.Dq } .
941.Pp
942The simplest form for parameter expansion is:
943.Pp
944.Dl ${parameter}
945.Pp
946The value, if any, of parameter is substituted.
947.Pp
948The parameter name or symbol can be enclosed in braces, which are
949optional except for positional parameters with more than one digit or
950when parameter is followed by a character that could be interpreted as
951part of the name.
952If a parameter expansion occurs inside double-quotes:
953.Bl -enum
954.It
955Pathname expansion is not performed on the results of the expansion.
956.It
957Field splitting is not performed on the results of the
958expansion, with the exception of the special rules for @.
959.El
960.Pp
961In addition, a parameter expansion can be modified by using one of the
962following formats.
963.Bl -tag -width aaparameterwordaaaaa
964.It ${parameter:-word}
965Use Default Values.
966If parameter is unset or null, the expansion of word
967is substituted; otherwise, the value of parameter is substituted.
968.It ${parameter:=word}
969Assign Default Values.
970If parameter is unset or null, the expansion of
971word is assigned to parameter.
972In all cases, the final value of parameter is substituted.
973Only variables, not positional parameters or special
974parameters, can be assigned in this way.
975.It ${parameter:?[word]}
976Indicate Error if Null or Unset.
977If parameter is unset or null, the
978expansion of word (or a message indicating it is unset if word is omitted)
979is written to standard error and the shell exits with a nonzero exit status.
980Otherwise, the value of parameter is substituted.
981An interactive shell need not exit.
982.It ${parameter:+word}
983Use Alternative Value.
984If parameter is unset or null, null is
985substituted; otherwise, the expansion of word is substituted.
986.El
987.Pp
988In the parameter expansions shown previously, use of the colon in the
989format results in a test for a parameter that is unset or null; omission
990of the colon results in a test for a parameter that is only unset.
991.Bl -tag -width aaparameterwordaaaaa
992.It ${#parameter}
993String Length.
994The length in characters of the value of parameter.
995.El
996.Pp
997The following four varieties of parameter expansion provide for substring
998processing.
999In each case, pattern matching notation (see
1000.Sx Shell Patterns ) ,
1001rather than regular expression notation, is used to evaluate the patterns.
1002If parameter is * or @, the result of the expansion is unspecified.
1003Enclosing the full parameter expansion string in double-quotes does not
1004cause the following four varieties of pattern characters to be quoted,
1005whereas quoting characters within the braces has this effect.
1006.Bl -tag -width aaparameterwordaaaaa
1007.It ${parameter%word}
1008Remove Smallest Suffix Pattern.
1009The word is expanded to produce a pattern.
1010The parameter expansion then results in parameter, with the
1011smallest portion of the suffix matched by the pattern deleted.
1012.It ${parameter%%word}
1013Remove Largest Suffix Pattern.
1014The word is expanded to produce a pattern.
1015The parameter expansion then results in parameter, with the largest
1016portion of the suffix matched by the pattern deleted.
1017.It ${parameter#word}
1018Remove Smallest Prefix Pattern.
1019The word is expanded to produce a pattern.
1020The parameter expansion then results in parameter, with the
1021smallest portion of the prefix matched by the pattern deleted.
1022.It ${parameter##word}
1023Remove Largest Prefix Pattern.
1024The word is expanded to produce a pattern.
1025The parameter expansion then results in parameter, with the largest
1026portion of the prefix matched by the pattern deleted.
1027.El
1028.Ss Command Substitution
1029Command substitution allows the output of a command to be substituted in
1030place of the command name itself.
1031Command substitution occurs when the command is enclosed as follows:
1032.Pp
1033.Dl $(command)
1034.Pp
1035or
1036.Po
1037.Dq backquoted
1038version
1039.Pc :
1040.Pp
1041.Dl `command`
1042.Pp
1043The shell expands the command substitution by executing command in a
1044subshell environment and replacing the command substitution with the
1045standard output of the command, removing sequences of one or more
1046.Ao newline Ac Ns s
1047at the end of the substitution.
1048(Embedded
1049.Ao newline Ac Ns s
1050before
1051the end of the output are not removed; however, during field splitting,
1052they may be translated into
1053.Ao space Ac Ns s ,
1054depending on the value of
1055.Ev IFS
1056and quoting that is in effect.)
1057.Ss Arithmetic Expansion
1058Arithmetic expansion provides a mechanism for evaluating an arithmetic
1059expression and substituting its value.
1060The format for arithmetic expansion is as follows:
1061.Pp
1062.Dl $((expression))
1063.Pp
1064The expression is treated as if it were in double-quotes, except
1065that a double-quote inside the expression is not treated specially.
1066The shell expands all tokens in the expression for parameter expansion,
1067command substitution, and quote removal.
1068.Pp
1069Next, the shell treats this as an arithmetic expression and
1070substitutes the value of the expression.
1071.Pp
1072Arithmetic expressions use a syntax similar to that
1073of the C language, and are evaluated using the
1074.Ql intmax_t
1075data type (this is an extension to
1076.Tn POSIX ,
1077which requires only
1078.Ql long
1079arithmetic).
1080Shell variables may be referenced by name inside an arithmetic
1081expression, without needing a
1082.Dq \&$
1083sign.
1084.Ss White Space Splitting (Field Splitting)
1085After parameter expansion, command substitution, and
1086arithmetic expansion the shell scans the results of
1087expansions and substitutions that did not occur in double-quotes for
1088field splitting and multiple fields can result.
1089.Pp
1090The shell treats each character of the
1091.Ev IFS
1092as a delimiter and use the delimiters to split the results of parameter
1093expansion and command substitution into fields.
1094.Pp
1095Non-whitespace characters in
1096.Ev IFS
1097are treated strictly as parameter terminators.
1098So adjacent non-whitespace
1099.Ev IFS
1100characters will produce empty parameters.
1101.Pp
1102If
1103.Ev IFS
1104is unset it is assumed to contain space, tab, and newline.
1105.Ss Pathname Expansion (File Name Generation)
1106Unless the
1107.Fl f
1108flag is set, file name generation is performed after word splitting is
1109complete.
1110Each word is viewed as a series of patterns, separated by slashes.
1111The process of expansion replaces the word with the names of all
1112existing files whose names can be formed by replacing each pattern with a
1113string that matches the specified pattern.
1114There are two restrictions on
1115this: first, a pattern cannot match a string containing a slash, and
1116second, a pattern cannot match a string starting with a period unless the
1117first character of the pattern is a period.
1118The next section describes the
1119patterns used for both Pathname Expansion and the
1120.Ic case
1121command.
1122.Ss Shell Patterns
1123A pattern consists of normal characters, which match themselves,
1124and meta-characters.
1125The meta-characters are
1126.Dq \&! ,
1127.Dq * ,
1128.Dq \&? ,
1129and
1130.Dq \&[ .
1131These characters lose their special meanings if they are quoted.
1132When command or variable substitution is performed
1133and the dollar sign or back quotes are not double quoted,
1134the value of the variable or the output of
1135the command is scanned for these characters and they are turned into
1136meta-characters.
1137.Pp
1138An asterisk
1139.Pq Dq *
1140matches any string of characters.
1141A question mark matches any single character.
1142A left bracket
1143.Pq Dq \&[
1144introduces a character class.
1145The end of the character class is indicated by a
1146.Pq Dq \&] ;
1147if the
1148.Dq \&]
1149is missing then the
1150.Dq \&[
1151matches a
1152.Dq \&[
1153rather than introducing a character class.
1154A character class matches any of the characters between the square brackets.
1155A range of characters may be specified using a minus sign.
1156The character class may be complemented
1157by making an exclamation point the first character of the character class.
1158.Pp
1159To include a
1160.Dq \&]
1161in a character class, make it the first character listed (after the
1162.Dq \&! ,
1163if any).
1164To include a minus sign, make it the first or last character listed.
1165.Ss Built-ins
1166This section lists the built-in commands which are built-in because they
1167need to perform some operation that can't be performed by a separate
1168process.
1169In addition to these, there are several other commands that may
1170be built in for efficiency (e.g.
1171.Xr printf 1 ,
1172.Xr echo 1 ,
1173.Xr test 1 ,
1174etc).
1175.Bl -tag -width 5n
1176.It :
1177A null command that returns a 0 (true) exit value.
1178.It \&. file
1179The commands in the specified file are read and executed by the shell.
1180.It alias Op Ar name Ns Op Ar "=string ..."
1181If
1182.Ar name=string
1183is specified, the shell defines the alias
1184.Ar name
1185with value
1186.Ar string .
1187If just
1188.Ar name
1189is specified, the value of the alias
1190.Ar name
1191is printed.
1192With no arguments, the
1193.Ic alias
1194built-in prints the
1195names and values of all defined aliases (see
1196.Ic unalias ) .
1197.It bg [ Ar job ] ...
1198Continue the specified jobs (or the current job if no
1199jobs are given) in the background.
1200.It Xo command
1201.Op Fl p
1202.Op Fl v
1203.Op Fl V
1204.Ar command
1205.Op Ar arg ...
1206.Xc
1207Execute the specified command but ignore shell functions when searching
1208for it.
1209(This is useful when you
1210have a shell function with the same name as a built-in command.)
1211.Bl -tag -width 5n
1212.It Fl p
1213search for command using a
1214.Ev PATH
1215that guarantees to find all the standard utilities.
1216.It Fl V
1217Do not execute the command but
1218search for the command and print the resolution of the
1219command search.
1220This is the same as the
1221.Ic type
1222built-in.
1223.It Fl v
1224Do not execute the command but
1225search for the command and print the absolute pathname
1226of utilities, the name for built-ins or the expansion of aliases.
1227.El
1228.It cd Op Ar directory Op Ar replace
1229Switch to the specified directory (default
1230.Ev $HOME ) .
1231If
1232.Ar replace
1233is specified, then the new directory name is generated by replacing
1234the first occurrence of
1235.Ar directory
1236in the current directory name with
1237.Ar replace .
1238Otherwise if an entry for
1239.Ev CDPATH
1240appears in the environment of the
1241.Ic cd
1242command or the shell variable
1243.Ev CDPATH
1244is set and the directory name does not begin with a slash,
1245or its first (or only) component isn't dot or dot dot,
1246then the directories listed in
1247.Ev CDPATH
1248will be searched for the specified directory.
1249The format of
1250.Ev CDPATH
1251is the same as that of
1252.Ev PATH .
1253.Pp
1254In an interactive shell, the
1255.Ic cd
1256command will print out the name of the
1257directory that it actually switched to if this is different from the name
1258that the user gave.
1259These may be different either because the
1260.Ev CDPATH
1261mechanism was used or because a symbolic link was crossed.
1262.It eval Ar string ...
1263Concatenate all the arguments with spaces.
1264Then re-parse and execute the command.
1265.It exec Op Ar command arg ...
1266Unless command is omitted, the shell process is replaced with the
1267specified program (which must be a real program, not a shell built-in or
1268function).
1269Any redirections on the
1270.Ic exec
1271command are marked as permanent, so that they are not undone when the
1272.Ic exec
1273command finishes.
1274.It exit Op Ar exitstatus
1275Terminate the shell process.
1276If
1277.Ar exitstatus
1278is given it is used as the exit status of the shell; otherwise the
1279exit status of the preceding command is used.
1280.It export Ar name ...
1281.It export Fl p
1282The specified names are exported so that they will appear in the
1283environment of subsequent commands.
1284The only way to un-export a variable is to unset it.
1285The shell allows the value of a variable to be set at the
1286same time it is exported by writing
1287.Pp
1288.Dl export name=value
1289.Pp
1290With no arguments the export command lists the names of all exported variables.
1291With the
1292.Fl p
1293option specified the output will be formatted suitably for non-interactive use.
1294.It Xo fc Op Fl e Ar editor
1295.Op Ar first Op Ar last
1296.Xc
1297.It Xo fc Fl l
1298.Op Fl nr
1299.Op Ar first Op Ar last
1300.Xc
1301.It Xo fc Fl s Op Ar old=new
1302.Op Ar first
1303.Xc
1304The
1305.Ic fc
1306built-in lists, or edits and re-executes, commands previously entered
1307to an interactive shell.
1308.Bl -tag -width 5n
1309.It Fl e No editor
1310Use the editor named by editor to edit the commands.
1311The editor string is a command name, subject to search via the
1312.Ev PATH
1313variable.
1314The value in the
1315.Ev FCEDIT
1316variable is used as a default when
1317.Fl e
1318is not specified.
1319If
1320.Ev FCEDIT
1321is null or unset, the value of the
1322.Ev EDITOR
1323variable is used.
1324If
1325.Ev EDITOR
1326is null or unset,
1327.Xr ed 1
1328is used as the editor.
1329.It Fl l No (ell)
1330List the commands rather than invoking an editor on them.
1331The commands are written in the sequence indicated by
1332the first and last operands, as affected by
1333.Fl r ,
1334with each command preceded by the command number.
1335.It Fl n
1336Suppress command numbers when listing with -l.
1337.It Fl r
1338Reverse the order of the commands listed (with
1339.Fl l )
1340or edited (with neither
1341.Fl l
1342nor
1343.Fl s ) .
1344.It Fl s
1345Re-execute the command without invoking an editor.
1346.It first
1347.It last
1348Select the commands to list or edit.
1349The number of previous commands that
1350can be accessed are determined by the value of the
1351.Ev HISTSIZE
1352variable.
1353The value of first or last or both are one of the following:
1354.Bl -tag -width 5n
1355.It [+]number
1356A positive number representing a command number; command numbers can be
1357displayed with the
1358.Fl l
1359option.
1360.It Fl number
1361A negative decimal number representing the command that was executed
1362number of commands previously.
1363For example, \-1 is the immediately previous command.
1364.El
1365.It string
1366A string indicating the most recently entered command that begins with
1367that string.
1368If the old=new operand is not also specified with
1369.Fl s ,
1370the string form of the first operand cannot contain an embedded equal sign.
1371.El
1372.Pp
1373The following environment variables affect the execution of fc:
1374.Bl -tag -width HISTSIZE
1375.It Ev FCEDIT
1376Name of the editor to use.
1377.It Ev HISTSIZE
1378The number of previous commands that are accessible.
1379.El
1380.It fg Op Ar job
1381Move the specified job or the current job to the foreground.
1382.It getopts Ar optstring var
1383The
1384.Tn POSIX
1385.Ic getopts
1386command, not to be confused with the
1387.Em Bell Labs
1388-derived
1389.Xr getopt 1 .
1390.Pp
1391The first argument should be a series of letters, each of which may be
1392optionally followed by a colon to indicate that the option requires an
1393argument.
1394The variable specified is set to the parsed option.
1395.Pp
1396The
1397.Ic getopts
1398command deprecates the older
1399.Xr getopt 1
1400utility due to its handling of arguments containing whitespace.
1401.Pp
1402The
1403.Ic getopts
1404built-in may be used to obtain options and their arguments
1405from a list of parameters.
1406When invoked,
1407.Ic getopts
1408places the value of the next option from the option string in the list in
1409the shell variable specified by
1410.Va var
1411and its index in the shell variable
1412.Ev OPTIND .
1413When the shell is invoked,
1414.Ev OPTIND
1415is initialized to 1.
1416For each option that requires an argument, the
1417.Ic getopts
1418built-in will place it in the shell variable
1419.Ev OPTARG .
1420If an option is not allowed for in the
1421.Va optstring ,
1422then
1423.Ev OPTARG
1424will be unset.
1425.Pp
1426.Va optstring
1427is a string of recognized option letters (see
1428.Xr getopt 3 ) .
1429If a letter is followed by a colon, the option is expected to have an
1430argument which may or may not be separated from it by whitespace.
1431If an option character is not found where expected,
1432.Ic getopts
1433will set the variable
1434.Va var
1435to a
1436.Dq \&? ;
1437.Ic getopts
1438will then unset
1439.Ev OPTARG
1440and write output to standard error.
1441By specifying a colon as the first character of
1442.Va optstring
1443all errors will be ignored.
1444.Pp
1445A nonzero value is returned when the last option is reached.
1446If there are no remaining arguments,
1447.Ic getopts
1448will set
1449.Va var
1450to the special option,
1451.Dq -- ,
1452otherwise, it will set
1453.Va var
1454to
1455.Dq \&? .
1456.Pp
1457The following code fragment shows how one might process the arguments
1458for a command that can take the options
1459.Op a
1460and
1461.Op b ,
1462and the option
1463.Op c ,
1464which requires an argument.
1465.Pp
1466.Bd -literal -offset indent
1467while getopts abc: f
1468do
1469	case $f in
1470	a | b)	flag=$f;;
1471	c)	carg=$OPTARG;;
1472	\\?)	echo $USAGE; exit 1;;
1473	esac
1474done
1475shift `expr $OPTIND - 1`
1476.Ed
1477.Pp
1478This code will accept any of the following as equivalent:
1479.Pp
1480.Bd -literal -offset indent
1481cmd \-acarg file file
1482cmd \-a \-c arg file file
1483cmd \-carg -a file file
1484cmd \-a \-carg \-\- file file
1485.Ed
1486.It hash Fl rv Ar command ...
1487The shell maintains a hash table which remembers the
1488locations of commands.
1489With no arguments whatsoever,
1490the
1491.Ic hash
1492command prints out the contents of this table.
1493Entries which have not been looked at since the last
1494.Ic cd
1495command are marked with an asterisk; it is possible for these entries
1496to be invalid.
1497.Pp
1498With arguments, the
1499.Ic hash
1500command removes the specified commands from the hash table (unless
1501they are functions) and then locates them.
1502With the
1503.Fl v
1504option, hash prints the locations of the commands as it finds them.
1505The
1506.Fl r
1507option causes the hash command to delete all the entries in the hash table
1508except for functions.
1509.It inputrc Ar file
1510Read the
1511.Va file
1512to set keybindings as defined by
1513.Xr editrc 5 .
1514.It jobid Op Ar job
1515Print the process id's of the processes in the job.
1516If the
1517.Ar job
1518argument is omitted, the current job is used.
1519.It jobs
1520This command lists out all the background processes
1521which are children of the current shell process.
1522.It pwd Op Fl LP
1523Print the current directory.
1524If
1525.Fl L
1526is specified the cached value (initially set from
1527.Ev PWD )
1528is checked to see if it refers to the current directory, if it does
1529the value is printed.
1530Otherwise the current directory name is found using
1531.Xr getcwd 3 .
1532The environment variable
1533.Ev PWD
1534is set to printed value.
1535.Pp
1536The default is
1537.Ic pwd
1538.Fl L ,
1539but note that the built-in
1540.Ic cd
1541command doesn't currently support
1542.Fl L
1543or
1544.Fl P
1545and will cache (almost) the absolute path.
1546If
1547.Ic cd
1548is changed,
1549.Ic pwd
1550may be changed to default to
1551.Ic pwd
1552.Fl P .
1553.Pp
1554If the current directory is renamed and replaced by a symlink to the
1555same directory, or the initial
1556.Ev PWD
1557value followed a symbolic link, then the cached value may not
1558be the absolute path.
1559.Pp
1560The built-in command may differ from the program of the same name because
1561the program will use
1562.Ev PWD
1563and the built-in uses a separately cached value.
1564.It Xo read Op Fl p Ar prompt
1565.Op Fl r
1566.Ar variable
1567.Op Ar ...
1568.Xc
1569The prompt is printed if the
1570.Fl p
1571option is specified and the standard input is a terminal.
1572Then a line is read from the standard input.
1573The trailing newline is deleted from the
1574line and the line is split as described in the section on word splitting
1575above, and the pieces are assigned to the variables in order.
1576If there are more pieces than variables, the remaining pieces
1577(along with the characters in
1578.Ev IFS
1579that separated them) are assigned to the last variable.
1580If there are more variables than pieces,
1581the remaining variables are assigned the null string.
1582The
1583.Ic read
1584built-in will indicate success unless EOF is encountered on input, in
1585which case failure is returned.
1586.Pp
1587By default, unless the
1588.Fl r
1589option is specified, the backslash
1590.Dq \e
1591acts as an escape character, causing the following character to be treated
1592literally.
1593If a backslash is followed by a newline, the backslash and the
1594newline will be deleted.
1595.It readonly Ar name ...
1596.It readonly Fl p
1597The specified names are marked as read only, so that they cannot be
1598subsequently modified or unset.
1599The shell allows the value of a variable
1600to be set at the same time it is marked read only by writing
1601.Pp
1602.Dl readonly name=value
1603.Pp
1604With no arguments the readonly command lists the names of all read only
1605variables.
1606With the
1607.Fl p
1608option specified the output will be formatted suitably for non-interactive use.
1609.Pp
1610.It Xo set
1611.Oo {
1612.Fl options | Cm +options | Cm -- }
1613.Oc Ar arg ...
1614.Xc
1615The
1616.Ic set
1617command performs three different functions.
1618.Pp
1619With no arguments, it lists the values of all shell variables.
1620.Pp
1621If options are given, it sets the specified option
1622flags, or clears them as described in the section called
1623.Sx Argument List Processing .
1624.Pp
1625The third use of the set command is to set the values of the shell's
1626positional parameters to the specified arguments.
1627To change the positional
1628parameters without changing any options, use
1629.Dq --
1630as the first argument to set.
1631If no arguments are present, the set command
1632will clear all the positional parameters (equivalent to executing
1633.Dq shift $# . )
1634.It setvar Ar variable Ar value
1635Assigns value to variable.
1636(In general it is better to write
1637variable=value rather than using
1638.Ic setvar .
1639.Ic setvar
1640is intended to be used in
1641functions that assign values to variables whose names are passed as
1642parameters.)
1643.It shift Op Ar n
1644Shift the positional parameters n times.
1645A
1646.Ic shift
1647sets the value of
1648.Va $1
1649to the value of
1650.Va $2 ,
1651the value of
1652.Va $2
1653to the value of
1654.Va $3 ,
1655and so on, decreasing
1656the value of
1657.Va $#
1658by one.
1659If there are zero positional parameters,
1660.Ic shift
1661does nothing.
1662.It Xo trap
1663.Op Fl l
1664.Xc
1665.It Xo trap
1666.Op Ar action
1667.Ar signal ...
1668.Xc
1669Cause the shell to parse and execute action when any of the specified
1670signals are received.
1671The signals are specified by signal number or as the name of the signal.
1672If
1673.Ar signal
1674is
1675.Li 0 ,
1676the action is executed when the shell exits.
1677.Ar action
1678may be null, which cause the specified signals to be ignored.
1679With
1680.Ar action
1681omitted or set to `-' the specified signals are set to their default action.
1682When the shell forks off a subshell, it resets trapped (but not ignored)
1683signals to the default action.
1684On non-interactive shells, the
1685.Ic trap
1686command has no effect on signals that were
1687ignored on entry to the shell.
1688On interactive shells, the
1689.Ic trap
1690command will catch or reset signals ignored on entry.
1691Issuing
1692.Ic trap
1693with option
1694.Ar -l
1695will print a list of valid signal names.
1696.Ic trap
1697without any arguments cause it to write a list of signals and their
1698associated action to the standard output in a format that is suitable
1699as an input to the shell that achieves the same trapping results.
1700.Pp
1701Examples:
1702.Pp
1703.Dl trap
1704.Pp
1705List trapped signals and their corresponding action
1706.Pp
1707.Dl trap -l
1708.Pp
1709Print a list of valid signals
1710.Pp
1711.Dl trap '' INT QUIT tstp 30
1712.Pp
1713Ignore signals INT QUIT TSTP USR1
1714.Pp
1715.Dl trap date INT
1716.Pp
1717Print date upon receiving signal INT
1718.It type Op Ar name ...
1719Interpret each name as a command and print the resolution of the command
1720search.
1721Possible resolutions are:
1722shell keyword, alias, shell built-in,
1723command, tracked alias and not found.
1724For aliases the alias expansion is
1725printed; for commands and tracked aliases the complete pathname of the
1726command is printed.
1727.It ulimit Xo
1728.Op Fl H \*(Ba Fl S
1729.Op Fl a \*(Ba Fl tfdscmlpn Op Ar value
1730.Xc
1731Inquire about or set the hard or soft limits on processes or set new
1732limits.
1733The choice between hard limit (which no process is allowed to
1734violate, and which may not be raised once it has been lowered) and soft
1735limit (which causes processes to be signaled but not necessarily killed,
1736and which may be raised) is made with these flags:
1737.Bl -tag -width Fl
1738.It Fl H
1739set or inquire about hard limits
1740.It Fl S
1741set or inquire about soft limits.
1742If neither
1743.Fl H
1744nor
1745.Fl S
1746is specified, the soft limit is displayed or both limits are set.
1747If both are specified, the last one wins.
1748.El
1749.Pp
1750.Bl -tag -width Fl
1751The limit to be interrogated or set, then, is chosen by specifying
1752any one of these flags:
1753.It Fl a
1754show all the current limits
1755.It Fl b
1756show or set the limit on the socket buffer size of a process (in bytes)
1757.It Fl t
1758show or set the limit on CPU time (in seconds)
1759.It Fl f
1760show or set the limit on the largest file that can be created
1761(in 512-byte blocks)
1762.It Fl d
1763show or set the limit on the data segment size of a process (in kilobytes)
1764.It Fl s
1765show or set the limit on the stack size of a process (in kilobytes)
1766.It Fl c
1767show or set the limit on the largest core dump size that can be produced
1768(in 512-byte blocks)
1769.It Fl m
1770show or set the limit on the total physical memory that can be
1771in use by a process (in kilobytes)
1772.It Fl l
1773show or set the limit on how much memory a process can lock with
1774.Xr mlock 2
1775(in kilobytes)
1776.It Fl p
1777show or set the limit on the number of processes this user can
1778have at one time
1779.It Fl n
1780show or set the limit on the number of files a process can have open at once
1781.El
1782.Pp
1783If none of these is specified, it is the limit on file size that is shown
1784or set.
1785If value is specified, the limit is set to that number; otherwise
1786the current limit is displayed.
1787.Pp
1788Limits of an arbitrary process can be displayed or set using the
1789.Xr sysctl 8
1790utility.
1791.Pp
1792.It umask Op Ar mask
1793Set the value of umask (see
1794.Xr umask 2 )
1795to the specified octal value.
1796If the argument is omitted, the umask value is printed.
1797.It unalias Xo
1798.Op Fl a
1799.Op Ar name
1800.Xc
1801If
1802.Ar name
1803is specified, the shell removes that alias.
1804If
1805.Fl a
1806is specified, all aliases are removed.
1807.It unset Ar name ...
1808The specified variables and functions are unset and unexported.
1809If a given name corresponds to both a variable and a function, both
1810the variable and the function are unset.
1811.It wait Op Ar job
1812Wait for the specified job to complete and return the exit status of the
1813last process in the job.
1814If the argument is omitted, wait for all jobs to
1815complete and then return an exit status of zero.
1816.El
1817.Ss Command Line Editing
1818When
1819.Nm
1820is being used interactively from a terminal, the current command
1821and the command history (see
1822.Ic fc
1823in
1824.Sx Built-ins )
1825can be edited using emacs-mode or vi-mode command-line editing.
1826The command
1827.Ql set -o emacs
1828enables emacs-mode editing.
1829The command
1830.Ql set -o vi
1831enables vi-mode editing and places the current shell process into
1832.Ar vi
1833insert mode.
1834(See the
1835.Sx Argument List Processing
1836section above.)
1837.Pp
1838The
1839.Ar vi
1840mode uses commands similar to a subset of those described in the
1841.Xr vi 1
1842man page.
1843With vi-mode
1844enabled,
1845.Nm sh
1846can be switched between insert mode and command mode.
1847It's similar to
1848.Xr vi 1 :
1849pressing the
1850.Aq ESC
1851key will throw you into command VI command mode.
1852Pressing the
1853.Aq return
1854key while in command mode will pass the line to the shell.
1855.Pp
1856The
1857.Ar emacs
1858mode uses commands similar to a subset available in
1859the
1860.Xr emacs 1
1861editor.
1862With emacs-mode enabled, special keys can be used to modify the text
1863in the buffer using the control key.
1864.Pp
1865.Nm
1866uses the
1867.Xr editline 3
1868library.
1869.Sh EXIT STATUS
1870Errors that are detected by the shell, such as a syntax error, will cause the
1871shell to exit with a non-zero exit status.
1872If the shell is not an
1873interactive shell, the execution of the shell file will be aborted.
1874Otherwise
1875the shell will return the exit status of the last command executed, or
1876if the exit built-in is used with a numeric argument, it will return the
1877argument.
1878.Sh ENVIRONMENT
1879.Bl -tag -width MAILCHECK
1880.It Ev HOME
1881Set automatically by
1882.Xr login 1
1883from the user's login directory in the password file
1884.Pq Xr passwd 5 .
1885This environment variable also functions as the default argument for the
1886.Ic cd
1887built-in.
1888.It Ev PATH
1889The default search path for executables.
1890See the above section
1891.Sx Path Search .
1892.It Ev CDPATH
1893The search path used with the
1894.Ic cd
1895built-in.
1896.It Ev LANG
1897The string used to specify localization information that allows users
1898to work with different culture-specific and language conventions.
1899See
1900.Xr nls 7 .
1901.It Ev MAIL
1902The name of a mail file, that will be checked for the arrival of new mail.
1903Overridden by
1904.Ev MAILPATH .
1905.It Ev MAILCHECK
1906The frequency in seconds that the shell checks for the arrival of mail
1907in the files specified by the
1908.Ev MAILPATH
1909or the
1910.Ev MAIL
1911file.
1912If set to 0, the check will occur at each prompt.
1913.It Ev MAILPATH
1914A colon
1915.Dq \&:
1916separated list of file names, for the shell to check for incoming mail.
1917This environment setting overrides the
1918.Ev MAIL
1919setting.
1920There is a maximum of 10 mailboxes that can be monitored at once.
1921.It Ev PS1
1922The primary prompt string, which defaults to
1923.Dq $ \  ,
1924unless you are the superuser, in which case it defaults to
1925.Dq # \  .
1926.It Ev PS2
1927The secondary prompt string, which defaults to
1928.Dq \*[Gt] \  .
1929.It Ev PS4
1930Output before each line when execution trace (set -x) is enabled,
1931defaults to
1932.Dq + \  .
1933.It Ev IFS
1934Input Field Separators.
1935This is normally set to
1936.Aq space ,
1937.Aq tab ,
1938and
1939.Aq newline .
1940See the
1941.Sx White Space Splitting
1942section for more details.
1943.It Ev TERM
1944The default terminal setting for the shell.
1945This is inherited by
1946children of the shell, and is used in the history editing modes.
1947.It Ev HISTSIZE
1948The number of lines in the history buffer for the shell.
1949.El
1950.Sh FILES
1951.Bl -item -width HOMEprofilexxxx
1952.It
1953.Pa $HOME/.profile
1954.It
1955.Pa /etc/profile
1956.El
1957.Sh SEE ALSO
1958.Xr csh 1 ,
1959.Xr echo 1 ,
1960.Xr getopt 1 ,
1961.Xr ksh 1 ,
1962.Xr login 1 ,
1963.Xr printf 1 ,
1964.Xr test 1 ,
1965.Xr editline 3 ,
1966.Xr getopt 3 ,
1967.\" .Xr profile 4 ,
1968.Xr editrc 5 ,
1969.Xr passwd 5 ,
1970.Xr environ 7 ,
1971.Xr nls 7 ,
1972.Xr sysctl 8
1973.Sh HISTORY
1974A
1975.Nm
1976command appeared in
1977.At v1 .
1978It was, however, unmaintainable so we wrote this one.
1979.Sh BUGS
1980Setuid shell scripts should be avoided at all costs, as they are a
1981significant security risk.
1982.Pp
1983PS1, PS2, and PS4 should be subject to parameter expansion before
1984being displayed.
1985.Pp
1986The characters generated by filename completion should probably be quoted
1987to ensure that the filename is still valid after the input line has been
1988processed.
1989