xref: /freebsd/bin/sh/sh.1 (revision 4f1f4356f3012928b463f9ef1710fb908e48b1e2)
1.\"-
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.\" 4. 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.\"	from: @(#)sh.1	8.6 (Berkeley) 5/4/95
33.\" $FreeBSD$
34.\"
35.Dd August 22, 2010
36.Dt SH 1
37.Os
38.Sh NAME
39.Nm sh
40.Nd command interpreter (shell)
41.Sh SYNOPSIS
42.Nm
43.Op Fl /+abCEefIimnPpsTuVvx
44.Op Fl /+o Ar longname
45.Op Fl c Ar string
46.Op Ar arg ...
47.Sh DESCRIPTION
48The
49.Nm
50utility is the standard command interpreter for the system.
51The current version of
52.Nm
53is in the process of being changed to
54conform with the
55.St -p1003.2
56specification for the shell.
57This version has many features which make
58it appear
59similar in some respects to the Korn shell, but it is not a Korn
60shell clone like
61.Nm pdksh .
62Only features
63designated by
64.Tn POSIX ,
65plus a few Berkeley extensions, are being
66incorporated into this shell.
67This man page is not intended to be a tutorial nor a complete
68specification of the shell.
69.Ss Overview
70The shell is a command that reads lines from
71either a file or the terminal, interprets them, and
72generally executes other commands.
73It is the program that is started when a user logs into the system,
74although a user can select a different shell with the
75.Xr chsh 1
76command.
77The shell
78implements a language that has flow control constructs,
79a macro facility that provides a variety of features in
80addition to data storage, along with built-in history and line
81editing capabilities.
82It incorporates many features to
83aid interactive use and has the advantage that the interpretative
84language is common to both interactive and non-interactive
85use (shell scripts).
86That is, commands can be typed directly
87to the running shell or can be put into a file,
88which can be executed directly by the shell.
89.Ss Invocation
90.\"
91.\" XXX This next sentence is incredibly confusing.
92.\"
93If no arguments are present and if the standard input of the shell
94is connected to a terminal
95(or if the
96.Fl i
97option is set),
98the shell is considered an interactive shell.
99An interactive shell
100generally prompts before each command and handles programming
101and command errors differently (as described below).
102When first starting, the shell inspects argument 0, and
103if it begins with a dash
104.Pq Ql - ,
105the shell is also considered a login shell.
106This is normally done automatically by the system
107when the user first logs in.
108A login shell first reads commands
109from the files
110.Pa /etc/profile
111and then
112.Pa .profile
113in a user's home directory,
114if they exist.
115If the environment variable
116.Ev ENV
117is set on entry to a shell, or is set in the
118.Pa .profile
119of a login shell, the shell then reads commands from the file named in
120.Ev ENV .
121Therefore, a user should place commands that are to be executed only
122at login time in the
123.Pa .profile
124file, and commands that are executed for every shell inside the
125.Ev ENV
126file.
127The user can set the
128.Ev ENV
129variable to some file by placing the following line in the file
130.Pa .profile
131in the home directory,
132substituting for
133.Pa .shinit
134the filename desired:
135.Pp
136.Dl "ENV=$HOME/.shinit; export ENV"
137.Pp
138The first non-option argument specified on the command line
139will be treated as the
140name of a file from which to read commands (a shell script), and
141the remaining arguments are set as the positional parameters
142of the shell
143.Li ( $1 , $2 ,
144etc.).
145Otherwise, the shell reads commands
146from its standard input.
147.Pp
148Unlike older versions of
149.Nm
150the
151.Ev ENV
152script is only sourced on invocation of interactive shells.
153This
154closes a well-known, and sometimes easily exploitable security
155hole related to poorly thought out
156.Ev ENV
157scripts.
158.Ss Argument List Processing
159All of the single letter options to
160.Nm
161have a corresponding long name,
162with the exception of
163.Fl c
164and
165.Fl /+o .
166These long names are provided next to the single letter options
167in the descriptions below.
168The long name for an option may be specified as an argument to the
169.Fl /+o
170option of
171.Nm .
172Once the shell is running,
173the long name for an option may be specified as an argument to the
174.Fl /+o
175option of the
176.Ic set
177built-in command
178(described later in the section called
179.Sx Built-in Commands ) .
180Introducing an option with a dash
181.Pq Ql -
182enables the option,
183while using a plus
184.Pq Ql +
185disables the option.
186A
187.Dq Li --
188or plain
189.Ql -
190will stop option processing and will force the remaining
191words on the command line to be treated as arguments.
192The
193.Fl /+o
194and
195.Fl c
196options do not have long names.
197They take arguments and are described after the single letter options.
198.Bl -tag -width indent
199.It Fl a Li allexport
200Flag variables for export when assignments are made to them.
201.It Fl b Li notify
202Enable asynchronous notification of background job
203completion.
204(UNIMPLEMENTED)
205.It Fl C Li noclobber
206Do not overwrite existing files with
207.Ql > .
208.It Fl E Li emacs
209Enable the built-in
210.Xr emacs 1
211command line editor (disables the
212.Fl V
213option if it has been set;
214set automatically when interactive on terminals).
215.It Fl e Li errexit
216Exit immediately if any untested command fails in non-interactive mode.
217The exit status of a command is considered to be
218explicitly tested if the command is part of the list used to control
219an
220.Ic if , elif , while ,
221or
222.Ic until ;
223if the command is the left
224hand operand of an
225.Dq Li &&
226or
227.Dq Li ||
228operator; or if the command is a pipeline preceded by the
229.Ic !\&
230operator.
231If a shell function is executed and its exit status is explicitly
232tested, all commands of the function are considered to be tested as
233well.
234.It Fl f Li noglob
235Disable pathname expansion.
236.It Fl I Li ignoreeof
237Ignore
238.Dv EOF Ap s
239from input when in interactive mode.
240.It Fl i Li interactive
241Force the shell to behave interactively.
242.It Fl m Li monitor
243Turn on job control (set automatically when interactive).
244.It Fl n Li noexec
245If not interactive, read commands but do not
246execute them.
247This is useful for checking the
248syntax of shell scripts.
249.It Fl P Li physical
250Change the default for the
251.Ic cd
252and
253.Ic pwd
254commands from
255.Fl L
256(logical directory layout)
257to
258.Fl P
259(physical directory layout).
260.It Fl p Li privileged
261Turn on privileged mode.
262This mode is enabled on startup
263if either the effective user or group ID is not equal to the
264real user or group ID.
265Turning this mode off sets the
266effective user and group IDs to the real user and group IDs.
267When this mode is enabled for interactive shells, the file
268.Pa /etc/suid_profile
269is sourced instead of
270.Pa ~/.profile
271after
272.Pa /etc/profile
273is sourced, and the contents of the
274.Ev ENV
275variable are ignored.
276.It Fl s Li stdin
277Read commands from standard input (set automatically
278if no file arguments are present).
279This option has
280no effect when set after the shell has already started
281running (i.e., when set with the
282.Ic set
283command).
284.It Fl T Li trapsasync
285When waiting for a child, execute traps immediately.
286If this option is not set,
287traps are executed after the child exits,
288as specified in
289.St -p1003.2 .
290This nonstandard option is useful for putting guarding shells around
291children that block signals.
292The surrounding shell may kill the child
293or it may just return control to the tty and leave the child alone,
294like this:
295.Bd -literal -offset indent
296sh -T -c "trap 'exit 1' 2 ; some-blocking-program"
297.Ed
298.It Fl u Li nounset
299Write a message to standard error when attempting
300to expand a variable, a positional parameter or
301the special parameter
302.Va \&!
303that is not set, and if the
304shell is not interactive, exit immediately.
305.It Fl V Li vi
306Enable the built-in
307.Xr vi 1
308command line editor (disables
309.Fl E
310if it has been set).
311.It Fl v Li verbose
312The shell writes its input to standard error
313as it is read.
314Useful for debugging.
315.It Fl x Li xtrace
316Write each command
317(preceded by the value of the
318.Va PS4
319variable)
320to standard error before it is executed.
321Useful for debugging.
322.El
323.Pp
324The
325.Fl c
326option causes the commands to be read from the
327.Ar string
328operand instead of from the standard input.
329Keep in mind that this option only accepts a single string as its
330argument, hence multi-word strings must be quoted.
331.Pp
332The
333.Fl /+o
334option takes as its only argument the long name of an option
335to be enabled or disabled.
336For example, the following two invocations of
337.Nm
338both enable the built-in
339.Xr emacs 1
340command line editor:
341.Bd -literal -offset indent
342set -E
343set -o emacs
344.Ed
345.Pp
346If used without an argument, the
347.Fl o
348option displays the current option settings in a human-readable format.
349If
350.Cm +o
351is used without an argument, the current option settings are output
352in a format suitable for re-input into the shell.
353.Ss Lexical Structure
354The shell reads input in terms of lines from a file and breaks
355it up into words at whitespace (blanks and tabs), and at
356certain sequences of
357characters called
358.Dq operators ,
359which are special to the shell.
360There are two types of operators: control operators and
361redirection operators (their meaning is discussed later).
362The following is a list of valid operators:
363.Bl -tag -width indent
364.It Control operators:
365.Bl -column "XXX" "XXX" "XXX" "XXX" "XXX" -offset center -compact
366.It Li & Ta Li && Ta Li ( Ta Li ) Ta Li \en
367.It Li ;; Ta Li ; Ta Li | Ta Li ||
368.El
369.It Redirection operators:
370.Bl -column "XXX" "XXX" "XXX" "XXX" "XXX" -offset center -compact
371.It Li < Ta Li > Ta Li << Ta Li >> Ta Li <>
372.It Li <& Ta Li >& Ta Li <<- Ta Li >|
373.El
374.El
375.Pp
376The character
377.Ql #
378introduces a comment if used at the beginning of a word.
379The word starting with
380.Ql #
381and the rest of the line are ignored.
382.Pp
383.Tn ASCII
384.Dv NUL
385characters (character code 0) are not allowed in shell input.
386.Ss Quoting
387Quoting is used to remove the special meaning of certain characters
388or words to the shell, such as operators, whitespace, keywords,
389or alias names.
390.Pp
391There are three types of quoting: matched single quotes,
392matched double quotes, and backslash.
393.Bl -tag -width indent
394.It Single Quotes
395Enclosing characters in single quotes preserves the literal
396meaning of all the characters (except single quotes, making
397it impossible to put single-quotes in a single-quoted string).
398.It Double Quotes
399Enclosing characters within double quotes preserves the literal
400meaning of all characters except dollar sign
401.Pq Ql $ ,
402backquote
403.Pq Ql ` ,
404and backslash
405.Pq Ql \e .
406The backslash inside double quotes is historically weird.
407It remains literal unless it precedes the following characters,
408which it serves to quote:
409.Bl -column "XXX" "XXX" "XXX" "XXX" "XXX" -offset center -compact
410.It Li $ Ta Li ` Ta Li \&" Ta Li \e\  Ta Li \en
411.El
412.It Backslash
413A backslash preserves the literal meaning of the following
414character, with the exception of the newline character
415.Pq Ql \en .
416A backslash preceding a newline is treated as a line continuation.
417.El
418.Ss Keywords
419Keywords or reserved words are words that have special meaning to the
420shell and are recognized at the beginning of a line and
421after a control operator.
422The following are keywords:
423.Bl -column "doneXX" "elifXX" "elseXX" "untilXX" "whileX" -offset center
424.It Li \&! Ta { Ta } Ta Ic case Ta Ic do
425.It Ic done Ta Ic elif Ta Ic else Ta Ic esac Ta Ic fi
426.It Ic for Ta Ic if Ta Ic then Ta Ic until Ta Ic while
427.El
428.Ss Aliases
429An alias is a name and corresponding value set using the
430.Ic alias
431built-in command.
432Whenever a keyword may occur (see above),
433and after checking for keywords, the shell
434checks the word to see if it matches an alias.
435If it does, it replaces it in the input stream with its value.
436For example, if there is an alias called
437.Dq Li lf
438with the value
439.Dq Li "ls -F" ,
440then the input
441.Pp
442.Dl "lf foobar"
443.Pp
444would become
445.Pp
446.Dl "ls -F foobar"
447.Pp
448Aliases provide a convenient way for naive users to
449create shorthands for commands without having to learn how
450to create functions with arguments.
451They can also be
452used to create lexically obscure code.
453This use is discouraged.
454.Pp
455An alias name may be escaped in a command line, so that it is not
456replaced by its alias value, by using quoting characters within or
457adjacent to the alias name.
458This is most often done by prefixing
459an alias name with a backslash to execute a function, built-in, or
460normal program with the same name.
461See the
462.Sx Quoting
463subsection.
464.Ss Commands
465The shell interprets the words it reads according to a
466language, the specification of which is outside the scope
467of this man page (refer to the BNF in the
468.St -p1003.2
469document).
470Essentially though, a line is read and if
471the first word of the line (or after a control operator)
472is not a keyword, then the shell has recognized a
473simple command.
474Otherwise, a complex command or some
475other special construct may have been recognized.
476.Ss Simple Commands
477If a simple command has been recognized, the shell performs
478the following actions:
479.Bl -enum
480.It
481Leading words of the form
482.Dq Li name=value
483are stripped off and assigned to the environment of
484the simple command.
485Redirection operators and
486their arguments (as described below) are stripped
487off and saved for processing.
488.It
489The remaining words are expanded as described in
490the section called
491.Sx Word Expansions ,
492and the first remaining word is considered the command
493name and the command is located.
494The remaining
495words are considered the arguments of the command.
496If no command name resulted, then the
497.Dq Li name=value
498variable assignments recognized in 1) affect the
499current shell.
500.It
501Redirections are performed as described in
502the next section.
503.El
504.Ss Redirections
505Redirections are used to change where a command reads its input
506or sends its output.
507In general, redirections open, close, or
508duplicate an existing reference to a file.
509The overall format
510used for redirection is:
511.Pp
512.D1 Oo Ar n Oc Ar redir-op file
513.Pp
514The
515.Ar redir-op
516is one of the redirection operators mentioned
517previously.
518The following gives some examples of how these
519operators can be used.
520Note that stdin and stdout are commonly used abbreviations
521for standard input and standard output respectively.
522.Bl -tag -width "1234567890XX" -offset indent
523.It Oo Ar n Oc Ns Li > Ar file
524redirect stdout (or file descriptor
525.Ar n )
526to
527.Ar file
528.It Oo Ar n Oc Ns Li >| Ar file
529same as above, but override the
530.Fl C
531option
532.It Oo Ar n Oc Ns Li >> Ar file
533append stdout (or file descriptor
534.Ar n )
535to
536.Ar file
537.It Oo Ar n Oc Ns Li < Ar file
538redirect stdin (or file descriptor
539.Ar n )
540from
541.Ar file
542.It Oo Ar n Oc Ns Li <> Ar file
543redirect stdin (or file descriptor
544.Ar n )
545to and from
546.Ar file
547.It Oo Ar n1 Oc Ns Li <& Ns Ar n2
548duplicate stdin (or file descriptor
549.Ar n1 )
550from file descriptor
551.Ar n2
552.It Oo Ar n Oc Ns Li <&-
553close stdin (or file descriptor
554.Ar n )
555.It Oo Ar n1 Oc Ns Li >& Ns Ar n2
556duplicate stdout (or file descriptor
557.Ar n1 )
558to file descriptor
559.Ar n2
560.It Oo Ar n Oc Ns Li >&-
561close stdout (or file descriptor
562.Ar n )
563.El
564.Pp
565The following redirection is often called a
566.Dq here-document .
567.Bd -unfilled -offset indent
568.Oo Ar n Oc Ns Li << Ar delimiter
569.D1 Ar here-doc-text
570.D1 ...
571.Ar delimiter
572.Ed
573.Pp
574All the text on successive lines up to the delimiter is
575saved away and made available to the command on standard
576input, or file descriptor
577.Ar n
578if it is specified.
579If the
580.Ar delimiter
581as specified on the initial line is quoted, then the
582.Ar here-doc-text
583is treated literally, otherwise the text is subjected to
584parameter expansion, command substitution, and arithmetic
585expansion (as described in the section on
586.Sx Word Expansions ) .
587If the operator is
588.Dq Li <<-
589instead of
590.Dq Li << ,
591then leading tabs
592in the
593.Ar here-doc-text
594are stripped.
595.Ss Search and Execution
596There are three types of commands: shell functions,
597built-in commands, and normal programs.
598The command is searched for (by name) in that order.
599The three types of commands are all executed in a different way.
600.Pp
601When a shell function is executed, all of the shell positional
602parameters (except
603.Li $0 ,
604which remains unchanged) are
605set to the arguments of the shell function.
606The variables which are explicitly placed in the environment of
607the command (by placing assignments to them before the
608function name) are made local to the function and are set
609to the values given.
610Then the command given in the function definition is executed.
611The positional parameters are restored to their original values
612when the command completes.
613This all occurs within the current shell.
614.Pp
615Shell built-in commands are executed internally to the shell, without
616spawning a new process.
617There are two kinds of built-in commands: regular and special.
618Assignments before special builtins persist after they finish
619executing and assignment errors, redirection errors and certain
620operand errors cause a script to be aborted.
621Both regular and special builtins can affect the shell in ways
622normal programs cannot.
623.Pp
624Otherwise, if the command name does not match a function
625or built-in command, the command is searched for as a normal
626program in the file system (as described in the next section).
627When a normal program is executed, the shell runs the program,
628passing the arguments and the environment to the program.
629If the program is not a normal executable file
630(i.e., if it does not begin with the
631.Dq "magic number"
632whose
633.Tn ASCII
634representation is
635.Dq Li #! ,
636resulting in an
637.Er ENOEXEC
638return value from
639.Xr execve 2 )
640the shell will interpret the program in a subshell.
641The child shell will reinitialize itself in this case,
642so that the effect will be
643as if a new shell had been invoked to handle the ad-hoc shell script,
644except that the location of hashed commands located in
645the parent shell will be remembered by the child
646(see the description of the
647.Ic hash
648built-in command below).
649.Pp
650Note that previous versions of this document
651and the source code itself misleadingly and sporadically
652refer to a shell script without a magic number
653as a
654.Dq "shell procedure" .
655.Ss Path Search
656When locating a command, the shell first looks to see if
657it has a shell function by that name.
658Then it looks for a
659built-in command by that name.
660If a built-in command is not found,
661one of two things happen:
662.Bl -enum
663.It
664Command names containing a slash are simply executed without
665performing any searches.
666.It
667The shell searches each entry in the
668.Va PATH
669variable
670in turn for the command.
671The value of the
672.Va PATH
673variable should be a series of
674entries separated by colons.
675Each entry consists of a
676directory name.
677The current directory
678may be indicated implicitly by an empty directory name,
679or explicitly by a single period.
680.El
681.Ss Command Exit Status
682Each command has an exit status that can influence the behavior
683of other shell commands.
684The paradigm is that a command exits
685with zero for normal or success, and non-zero for failure,
686error, or a false indication.
687The man page for each command
688should indicate the various exit codes and what they mean.
689Additionally, the built-in commands return exit codes, as does
690an executed shell function.
691.Pp
692If a command is terminated by a signal, its exit status is 128 plus
693the signal number.
694Signal numbers are defined in the header file
695.In sys/signal.h .
696.Ss Complex Commands
697Complex commands are combinations of simple commands
698with control operators or keywords, together creating a larger complex
699command.
700More generally, a command is one of the following:
701.Bl -item -offset indent
702.It
703simple command
704.It
705pipeline
706.It
707list or compound-list
708.It
709compound command
710.It
711function definition
712.El
713.Pp
714Unless otherwise stated, the exit status of a command is
715that of the last simple command executed by the command.
716.Ss Pipelines
717A pipeline is a sequence of one or more commands separated
718by the control operator
719.Ql \&| .
720The standard output of all but
721the last command is connected to the standard input
722of the next command.
723The standard output of the last
724command is inherited from the shell, as usual.
725.Pp
726The format for a pipeline is:
727.Pp
728.D1 Oo Li \&! Oc Ar command1 Op Li \&| Ar command2 ...
729.Pp
730The standard output of
731.Ar command1
732is connected to the standard input of
733.Ar command2 .
734The standard input, standard output, or
735both of a command is considered to be assigned by the
736pipeline before any redirection specified by redirection
737operators that are part of the command.
738.Pp
739If the pipeline is not in the background (discussed later),
740the shell waits for all commands to complete.
741.Pp
742If the keyword
743.Ic !\&
744does not precede the pipeline, the
745exit status is the exit status of the last command specified
746in the pipeline.
747Otherwise, the exit status is the logical
748NOT of the exit status of the last command.
749That is, if
750the last command returns zero, the exit status is 1; if
751the last command returns greater than zero, the exit status
752is zero.
753.Pp
754Because pipeline assignment of standard input or standard
755output or both takes place before redirection, it can be
756modified by redirection.
757For example:
758.Pp
759.Dl "command1 2>&1 | command2"
760.Pp
761sends both the standard output and standard error of
762.Ar command1
763to the standard input of
764.Ar command2 .
765.Pp
766A
767.Ql \&;
768or newline terminator causes the preceding
769AND-OR-list
770(described below in the section called
771.Sx Short-Circuit List Operators )
772to be executed sequentially;
773an
774.Ql &
775causes asynchronous execution of the preceding AND-OR-list.
776.Pp
777Note that unlike some other shells,
778.Nm
779executes each process in the pipeline as a child of the
780.Nm
781process.
782Shell built-in commands are the exception to this rule.
783They are executed in the current shell, although they do not affect its
784environment when used in pipelines.
785.Ss Background Commands (&)
786If a command is terminated by the control operator ampersand
787.Pq Ql & ,
788the shell executes the command asynchronously;
789the shell does not wait for the command to finish
790before executing the next command.
791.Pp
792The format for running a command in background is:
793.Pp
794.D1 Ar command1 Li & Op Ar command2 Li & Ar ...
795.Pp
796If the shell is not interactive, the standard input of an
797asynchronous command is set to
798.Pa /dev/null .
799.Ss Lists (Generally Speaking)
800A list is a sequence of zero or more commands separated by
801newlines, semicolons, or ampersands,
802and optionally terminated by one of these three characters.
803The commands in a
804list are executed in the order they are written.
805If command is followed by an ampersand, the shell starts the
806command and immediately proceeds onto the next command;
807otherwise it waits for the command to terminate before
808proceeding to the next one.
809.Ss Short-Circuit List Operators
810.Dq Li &&
811and
812.Dq Li ||
813are AND-OR list operators.
814.Dq Li &&
815executes the first command, and then executes the second command
816if the exit status of the first command is zero.
817.Dq Li ||
818is similar, but executes the second command if the exit
819status of the first command is nonzero.
820.Dq Li &&
821and
822.Dq Li ||
823both have the same priority.
824.Ss Flow-Control Constructs (if, while, for, case)
825The syntax of the
826.Ic if
827command is:
828.Bd -unfilled -offset indent -compact
829.Ic if Ar list
830.Ic then Ar list
831.Oo Ic elif Ar list
832.Ic then Ar list Oc Ar ...
833.Op Ic else Ar list
834.Ic fi
835.Ed
836.Pp
837The syntax of the
838.Ic while
839command is:
840.Bd -unfilled -offset indent -compact
841.Ic while Ar list
842.Ic do Ar list
843.Ic done
844.Ed
845.Pp
846The two lists are executed repeatedly while the exit status of the
847first list is zero.
848The
849.Ic until
850command is similar, but has the word
851.Ic until
852in place of
853.Ic while ,
854which causes it to
855repeat until the exit status of the first list is zero.
856.Pp
857The syntax of the
858.Ic for
859command is:
860.Bd -unfilled -offset indent -compact
861.Ic for Ar variable Op Ic in Ar word ...
862.Ic do Ar list
863.Ic done
864.Ed
865.Pp
866If
867.Ic in
868and the following words are omitted,
869.Ic in Li \&"$@\&"
870is used instead.
871The words are expanded, and then the list is executed
872repeatedly with the variable set to each word in turn.
873The
874.Ic do
875and
876.Ic done
877commands may be replaced with
878.Ql {
879and
880.Ql } .
881.Pp
882The syntax of the
883.Ic break
884and
885.Ic continue
886commands is:
887.D1 Ic break Op Ar num
888.D1 Ic continue Op Ar num
889.Pp
890The
891.Ic break
892command terminates the
893.Ar num
894innermost
895.Ic for
896or
897.Ic while
898loops.
899The
900.Ic continue
901command continues with the next iteration of the innermost loop.
902These are implemented as special built-in commands.
903.Pp
904The syntax of the
905.Ic case
906command is:
907.Bd -unfilled -offset indent -compact
908.Ic case Ar word Ic in
909.Ar pattern Ns Li ) Ar list Li ;;
910.Ar ...
911.Ic esac
912.Ed
913.Pp
914The pattern can actually be one or more patterns
915(see
916.Sx Shell Patterns
917described later),
918separated by
919.Ql \&|
920characters.
921The exit code of the
922.Ic case
923command is the exit code of the last command executed in the list or
924zero if no patterns were matched.
925.Ss Grouping Commands Together
926Commands may be grouped by writing either
927.Pp
928.D1 Li \&( Ns Ar list Ns Li \%)
929.Pp
930or
931.Pp
932.D1 Li { Ar list Ns Li \&; }
933.Pp
934The first form executes the commands in a subshell.
935Note that built-in commands thus executed do not affect the current shell.
936The second form does not fork another shell,
937so it is slightly more efficient.
938Grouping commands together this way allows the user to
939redirect their output as though they were one program:
940.Bd -literal -offset indent
941{ echo -n "hello"; echo " world"; } > greeting
942.Ed
943.Ss Functions
944The syntax of a function definition is
945.Pp
946.D1 Ar name Li \&( \&) Ar command
947.Pp
948A function definition is an executable statement; when
949executed it installs a function named
950.Ar name
951and returns an
952exit status of zero.
953The
954.Ar command
955is normally a list
956enclosed between
957.Ql {
958and
959.Ql } .
960.Pp
961Variables may be declared to be local to a function by
962using the
963.Ic local
964command.
965This should appear as the first statement of a function,
966and the syntax is:
967.Pp
968.D1 Ic local Oo Ar variable ... Oc Op Fl
969.Pp
970The
971.Ic local
972command is implemented as a built-in command.
973.Pp
974When a variable is made local, it inherits the initial
975value and exported and readonly flags from the variable
976with the same name in the surrounding scope, if there is
977one.
978Otherwise, the variable is initially unset.
979The shell
980uses dynamic scoping, so that if the variable
981.Va x
982is made local to function
983.Em f ,
984which then calls function
985.Em g ,
986references to the variable
987.Va x
988made inside
989.Em g
990will refer to the variable
991.Va x
992declared inside
993.Em f ,
994not to the global variable named
995.Va x .
996.Pp
997The only special parameter that can be made local is
998.Ql - .
999Making
1000.Ql -
1001local causes any shell options that are
1002changed via the
1003.Ic set
1004command inside the function to be
1005restored to their original values when the function
1006returns.
1007.Pp
1008The syntax of the
1009.Ic return
1010command is
1011.Pp
1012.D1 Ic return Op Ar exitstatus
1013.Pp
1014It terminates the current executional scope, returning from the previous
1015nested function, sourced script, or shell instance, in that order.
1016The
1017.Ic return
1018command is implemented as a special built-in command.
1019.Ss Variables and Parameters
1020The shell maintains a set of parameters.
1021A parameter
1022denoted by a name is called a variable.
1023When starting up,
1024the shell turns all the environment variables into shell
1025variables.
1026New variables can be set using the form
1027.Pp
1028.D1 Ar name Ns = Ns Ar value
1029.Pp
1030Variables set by the user must have a name consisting solely
1031of alphabetics, numerics, and underscores.
1032The first letter of a variable name must not be numeric.
1033A parameter can also be denoted by a number
1034or a special character as explained below.
1035.Ss Positional Parameters
1036A positional parameter is a parameter denoted by a number greater than zero.
1037The shell sets these initially to the values of its command line
1038arguments that follow the name of the shell script.
1039The
1040.Ic set
1041built-in command can also be used to set or reset them.
1042.Ss Special Parameters
1043Special parameters are parameters denoted by a single special character
1044or the digit zero.
1045They are shown in the following list, exactly as they would appear in input
1046typed by the user or in the source of a shell script.
1047.Bl -hang
1048.It Li $*
1049Expands to the positional parameters, starting from one.
1050When
1051the expansion occurs within a double-quoted string
1052it expands to a single field with the value of each parameter
1053separated by the first character of the
1054.Va IFS
1055variable,
1056or by a space if
1057.Va IFS
1058is unset.
1059.It Li $@
1060Expands to the positional parameters, starting from one.
1061When
1062the expansion occurs within double-quotes, each positional
1063parameter expands as a separate argument.
1064If there are no positional parameters, the
1065expansion of
1066.Li @
1067generates zero arguments, even when
1068.Li @
1069is double-quoted.
1070What this basically means, for example, is
1071if
1072.Li $1
1073is
1074.Dq Li abc
1075and
1076.Li $2
1077is
1078.Dq Li "def ghi" ,
1079then
1080.Li \&"$@\&"
1081expands to
1082the two arguments:
1083.Bd -literal -offset indent
1084"abc"   "def ghi"
1085.Ed
1086.It Li $#
1087Expands to the number of positional parameters.
1088.It Li $?
1089Expands to the exit status of the most recent pipeline.
1090.It Li $-
1091(hyphen) Expands to the current option flags (the single-letter
1092option names concatenated into a string) as specified on
1093invocation, by the
1094.Ic set
1095built-in command, or implicitly
1096by the shell.
1097.It Li $$
1098Expands to the process ID of the invoked shell.
1099A subshell
1100retains the same value of
1101.Va $
1102as its parent.
1103.It Li $!
1104Expands to the process ID of the most recent background
1105command executed from the current shell.
1106For a
1107pipeline, the process ID is that of the last command in the
1108pipeline.
1109If this parameter is referenced, the shell will remember
1110the process ID and its exit status until the
1111.Ic wait
1112built-in command reports completion of the process.
1113.It Li $0
1114(zero) Expands to the name of the shell or shell script.
1115.El
1116.Ss Special Variables
1117The following variables are set by the shell or
1118have special meaning to it:
1119.Bl -tag -width ".Va HISTSIZE"
1120.It Va CDPATH
1121The search path used with the
1122.Ic cd
1123built-in.
1124.It Va EDITOR
1125The fallback editor used with the
1126.Ic fc
1127built-in.
1128If not set, the default editor is
1129.Xr ed 1 .
1130.It Va FCEDIT
1131The default editor used with the
1132.Ic fc
1133built-in.
1134.It Va HISTSIZE
1135The number of previous commands that are accessible.
1136.It Va HOME
1137The user's home directory,
1138used in tilde expansion and as a default directory for the
1139.Ic cd
1140built-in.
1141.It Va IFS
1142Input Field Separators.
1143This is normally set to
1144.Aq space ,
1145.Aq tab ,
1146and
1147.Aq newline .
1148See the
1149.Sx White Space Splitting
1150section for more details.
1151.It Va LINENO
1152The current line number in the script or function.
1153.It Va MAIL
1154The name of a mail file, that will be checked for the arrival of new
1155mail.
1156Overridden by
1157.Va MAILPATH .
1158.It Va MAILPATH
1159A colon
1160.Pq Ql \&:
1161separated list of file names, for the shell to check for incoming
1162mail.
1163This variable overrides the
1164.Va MAIL
1165setting.
1166There is a maximum of 10 mailboxes that can be monitored at once.
1167.It Va PATH
1168The default search path for executables.
1169See the
1170.Sx Path Search
1171section for details.
1172.It Va PPID
1173The parent process ID of the invoked shell.
1174This is set at startup
1175unless this variable is in the environment.
1176A later change of parent process ID is not reflected.
1177A subshell retains the same value of
1178.Va PPID .
1179.It Va PS1
1180The primary prompt string, which defaults to
1181.Dq Li "$ " ,
1182unless you are the superuser, in which case it defaults to
1183.Dq Li "# " .
1184.It Va PS2
1185The secondary prompt string, which defaults to
1186.Dq Li "> " .
1187.It Va PS4
1188The prefix for the trace output (if
1189.Fl x
1190is active).
1191The default is
1192.Dq Li "+ " .
1193.El
1194.Ss Word Expansions
1195This clause describes the various expansions that are
1196performed on words.
1197Not all expansions are performed on
1198every word, as explained later.
1199.Pp
1200Tilde expansions, parameter expansions, command substitutions,
1201arithmetic expansions, and quote removals that occur within
1202a single word expand to a single field.
1203It is only field
1204splitting or pathname expansion that can create multiple
1205fields from a single word.
1206The single exception to this rule is
1207the expansion of the special parameter
1208.Va @
1209within double-quotes,
1210as was described above.
1211.Pp
1212The order of word expansion is:
1213.Bl -enum
1214.It
1215Tilde Expansion, Parameter Expansion, Command Substitution,
1216Arithmetic Expansion (these all occur at the same time).
1217.It
1218Field Splitting is performed on fields generated by step (1)
1219unless the
1220.Va IFS
1221variable is null.
1222.It
1223Pathname Expansion (unless the
1224.Fl f
1225option is in effect).
1226.It
1227Quote Removal.
1228.El
1229.Pp
1230The
1231.Ql $
1232character is used to introduce parameter expansion, command
1233substitution, or arithmetic expansion.
1234.Ss Tilde Expansion (substituting a user's home directory)
1235A word beginning with an unquoted tilde character
1236.Pq Ql ~
1237is
1238subjected to tilde expansion.
1239All the characters up to a slash
1240.Pq Ql /
1241or the end of the word are treated as a username
1242and are replaced with the user's home directory.
1243If the
1244username is missing (as in
1245.Pa ~/foobar ) ,
1246the tilde is replaced with the value of the
1247.Va HOME
1248variable (the current user's home directory).
1249.Ss Parameter Expansion
1250The format for parameter expansion is as follows:
1251.Pp
1252.D1 Li ${ Ns Ar expression Ns Li }
1253.Pp
1254where
1255.Ar expression
1256consists of all characters until the matching
1257.Ql } .
1258Any
1259.Ql }
1260escaped by a backslash or within a single-quoted string, and characters in
1261embedded arithmetic expansions, command substitutions, and variable
1262expansions, are not examined in determining the matching
1263.Ql } .
1264Except for the variants with
1265.Ql + ,
1266.Ql - ,
1267.Ql =
1268or
1269.Ql ?\& ,
1270any
1271.Ql }
1272within a double-quoted string is also not examined in determining the matching
1273.Ql } .
1274.Pp
1275The simplest form for parameter expansion is:
1276.Pp
1277.D1 Li ${ Ns Ar parameter Ns Li }
1278.Pp
1279The value, if any, of
1280.Ar parameter
1281is substituted.
1282.Pp
1283The parameter name or symbol can be enclosed in braces, which are
1284optional except for positional parameters with more than one digit or
1285when parameter is followed by a character that could be interpreted as
1286part of the name.
1287If a parameter expansion occurs inside double-quotes:
1288.Bl -enum
1289.It
1290Pathname expansion is not performed on the results of the
1291expansion.
1292.It
1293Field splitting is not performed on the results of the
1294expansion, with the exception of the special parameter
1295.Va @ .
1296.El
1297.Pp
1298In addition, a parameter expansion can be modified by using one of the
1299following formats.
1300.Bl -tag -width indent
1301.It Li ${ Ns Ar parameter Ns Li :- Ns Ar word Ns Li }
1302Use Default Values.
1303If
1304.Ar parameter
1305is unset or null, the expansion of
1306.Ar word
1307is substituted; otherwise, the value of
1308.Ar parameter
1309is substituted.
1310.It Li ${ Ns Ar parameter Ns Li := Ns Ar word Ns Li }
1311Assign Default Values.
1312If
1313.Ar parameter
1314is unset or null, the expansion of
1315.Ar word
1316is assigned to
1317.Ar parameter .
1318In all cases, the
1319final value of
1320.Ar parameter
1321is substituted.
1322Quoting inside
1323.Ar word
1324does not prevent field splitting or pathname expansion.
1325Only variables, not positional
1326parameters or special parameters, can be
1327assigned in this way.
1328.It Li ${ Ns Ar parameter Ns Li :? Ns Oo Ar word Oc Ns Li }
1329Indicate Error if Null or Unset.
1330If
1331.Ar parameter
1332is unset or null, the expansion of
1333.Ar word
1334(or a message indicating it is unset if
1335.Ar word
1336is omitted) is written to standard
1337error and the shell exits with a nonzero
1338exit status.
1339Otherwise, the value of
1340.Ar parameter
1341is substituted.
1342An
1343interactive shell need not exit.
1344.It Li ${ Ns Ar parameter Ns Li :+ Ns Ar word Ns Li }
1345Use Alternate Value.
1346If
1347.Ar parameter
1348is unset or null, null is substituted;
1349otherwise, the expansion of
1350.Ar word
1351is substituted.
1352.El
1353.Pp
1354In the parameter expansions shown previously, use of the colon in the
1355format results in a test for a parameter that is unset or null; omission
1356of the colon results in a test for a parameter that is only unset.
1357.Pp
1358The
1359.Ar word
1360inherits the type of quoting
1361(unquoted, double-quoted or here-document)
1362from the surroundings,
1363with the exception that a backslash that quotes a closing brace is removed
1364during quote removal.
1365.Bl -tag -width indent
1366.It Li ${# Ns Ar parameter Ns Li }
1367String Length.
1368The length in characters of
1369the value of
1370.Ar parameter .
1371.El
1372.Pp
1373The following four varieties of parameter expansion provide for substring
1374processing.
1375In each case, pattern matching notation
1376(see
1377.Sx Shell Patterns ) ,
1378rather than regular expression notation,
1379is used to evaluate the patterns.
1380If parameter is one of the special parameters
1381.Va *
1382or
1383.Va @ ,
1384the result of the expansion is unspecified.
1385Enclosing the full parameter expansion string in double-quotes does not
1386cause the following four varieties of pattern characters to be quoted,
1387whereas quoting characters within the braces has this effect.
1388.Bl -tag -width indent
1389.It Li ${ Ns Ar parameter Ns Li % Ns Ar word Ns Li }
1390Remove Smallest Suffix Pattern.
1391The
1392.Ar word
1393is expanded to produce a pattern.
1394The
1395parameter expansion then results in
1396.Ar parameter ,
1397with the smallest portion of the
1398suffix matched by the pattern deleted.
1399.It Li ${ Ns Ar parameter Ns Li %% Ns Ar word Ns Li }
1400Remove Largest Suffix Pattern.
1401The
1402.Ar word
1403is expanded to produce a pattern.
1404The
1405parameter expansion then results in
1406.Ar parameter ,
1407with the largest portion of the
1408suffix matched by the pattern deleted.
1409.It Li ${ Ns Ar parameter Ns Li # Ns Ar word Ns Li }
1410Remove Smallest Prefix Pattern.
1411The
1412.Ar word
1413is expanded to produce a pattern.
1414The
1415parameter expansion then results in
1416.Ar parameter ,
1417with the smallest portion of the
1418prefix matched by the pattern deleted.
1419.It Li ${ Ns Ar parameter Ns Li ## Ns Ar word Ns Li }
1420Remove Largest Prefix Pattern.
1421The
1422.Ar word
1423is expanded to produce a pattern.
1424The
1425parameter expansion then results in
1426.Ar parameter ,
1427with the largest portion of the
1428prefix matched by the pattern deleted.
1429.El
1430.Ss Command Substitution
1431Command substitution allows the output of a command to be substituted in
1432place of the command name itself.
1433Command substitution occurs when
1434the command is enclosed as follows:
1435.Pp
1436.D1 Li $( Ns Ar command Ns Li )\&
1437.Pp
1438or the backquoted version:
1439.Pp
1440.D1 Li ` Ns Ar command Ns Li `
1441.Pp
1442The shell expands the command substitution by executing command in a
1443subshell environment and replacing the command substitution
1444with the standard output of the command,
1445removing sequences of one or more newlines at the end of the substitution.
1446Embedded newlines before the end of the output are not removed;
1447however, during field splitting, they may be translated into spaces
1448depending on the value of
1449.Va IFS
1450and the quoting that is in effect.
1451.Ss Arithmetic Expansion
1452Arithmetic expansion provides a mechanism for evaluating an arithmetic
1453expression and substituting its value.
1454The format for arithmetic expansion is as follows:
1455.Pp
1456.D1 Li $(( Ns Ar expression Ns Li ))
1457.Pp
1458The
1459.Ar expression
1460is treated as if it were in double-quotes, except
1461that a double-quote inside the expression is not treated specially.
1462The
1463shell expands all tokens in the
1464.Ar expression
1465for parameter expansion,
1466command substitution,
1467arithmetic expansion
1468and quote removal.
1469.Pp
1470The allowed expressions are a subset of C expressions,
1471summarized below.
1472.Bl -tag -width "Variables" -offset indent
1473.It Values
1474All values are of type
1475.Ft intmax_t .
1476.It Constants
1477Decimal, octal (starting with
1478.Li 0 )
1479and hexadecimal (starting with
1480.Li 0x )
1481integer constants.
1482.It Variables
1483Shell variables can be read and written
1484and contain integer constants.
1485.It Unary operators
1486.Li "! ~ + -"
1487.It Binary operators
1488.Li "* / % + - << >> < <= > >= == != & ^ | && ||"
1489.It Assignment operators
1490.Li "= += -= *= /= %= <<= >>= &= ^= |="
1491.It Short-circuit evaluation
1492The
1493.Li &&
1494and
1495.Li ||
1496operators always evaluate both sides.
1497This is a bug.
1498.El
1499.Pp
1500The result of the expression is substituted in decimal.
1501.Ss White Space Splitting (Field Splitting)
1502After parameter expansion, command substitution, and
1503arithmetic expansion the shell scans the results of
1504expansions and substitutions that did not occur in double-quotes for
1505field splitting and multiple fields can result.
1506.Pp
1507The shell treats each character of the
1508.Va IFS
1509variable as a delimiter and uses
1510the delimiters to split the results of parameter expansion and command
1511substitution into fields.
1512.Ss Pathname Expansion (File Name Generation)
1513Unless the
1514.Fl f
1515option is set,
1516file name generation is performed
1517after word splitting is complete.
1518Each word is
1519viewed as a series of patterns, separated by slashes.
1520The
1521process of expansion replaces the word with the names of
1522all existing files whose names can be formed by replacing
1523each pattern with a string that matches the specified pattern.
1524There are two restrictions on this: first, a pattern cannot match
1525a string containing a slash, and second,
1526a pattern cannot match a string starting with a period
1527unless the first character of the pattern is a period.
1528The next section describes the patterns used for both
1529Pathname Expansion and the
1530.Ic case
1531command.
1532.Ss Shell Patterns
1533A pattern consists of normal characters, which match themselves,
1534and meta-characters.
1535The meta-characters are
1536.Ql \&! ,
1537.Ql * ,
1538.Ql \&? ,
1539and
1540.Ql \&[ .
1541These characters lose their special meanings if they are quoted.
1542When command or variable substitution is performed and the dollar sign
1543or back quotes are not double-quoted, the value of the
1544variable or the output of the command is scanned for these
1545characters and they are turned into meta-characters.
1546.Pp
1547An asterisk
1548.Pq Ql *
1549matches any string of characters.
1550A question mark
1551.Pq Ql \&?
1552matches any single character.
1553A left bracket
1554.Pq Ql \&[
1555introduces a character class.
1556The end of the character class is indicated by a
1557.Ql \&] ;
1558if the
1559.Ql \&]
1560is missing then the
1561.Ql \&[
1562matches a
1563.Ql \&[
1564rather than introducing a character class.
1565A character class matches any of the characters between the square brackets.
1566A range of characters may be specified using a minus sign.
1567The character class may be complemented by making an exclamation point
1568.Pq Ql !\&
1569the first character of the character class.
1570.Pp
1571To include a
1572.Ql \&]
1573in a character class, make it the first character listed
1574(after the
1575.Ql \&! ,
1576if any).
1577To include a
1578.Ql - ,
1579make it the first or last character listed.
1580.Ss Built-in Commands
1581This section lists the commands which
1582are built-in because they need to perform some operation
1583that cannot be performed by a separate process.
1584In addition to
1585these, built-in versions of essential utilities
1586are provided for efficiency.
1587.Bl -tag -width indent
1588.It Ic \&:
1589A null command that returns a 0 (true) exit value.
1590.It Ic \&. Ar file
1591The commands in the specified file are read and executed by the shell.
1592The
1593.Ic return
1594command may be used to return to the
1595.Ic \&.
1596command's caller.
1597If
1598.Ar file
1599contains any
1600.Ql /
1601characters, it is used as is.
1602Otherwise, the shell searches the
1603.Va PATH
1604for the file.
1605If it is not found in the
1606.Va PATH ,
1607it is sought in the current working directory.
1608.It Ic \&[
1609A built-in equivalent of
1610.Xr test 1 .
1611.It Ic alias Oo Ar name Ns Oo = Ns Ar string Oc ... Oc
1612If
1613.Ar name Ns = Ns Ar string
1614is specified, the shell defines the alias
1615.Ar name
1616with value
1617.Ar string .
1618If just
1619.Ar name
1620is specified, the value of the alias
1621.Ar name
1622is printed.
1623With no arguments, the
1624.Ic alias
1625built-in command prints the names and values of all defined aliases
1626(see
1627.Ic unalias ) .
1628Alias values are written with appropriate quoting so that they are
1629suitable for re-input to the shell.
1630Also see the
1631.Sx Aliases
1632subsection.
1633.It Ic bg Op Ar job ...
1634Continue the specified jobs
1635(or the current job if no jobs are given)
1636in the background.
1637.It Ic builtin Ar cmd Op Ar arg ...
1638Execute the specified built-in command,
1639.Ar cmd .
1640This is useful when the user wishes to override a shell function
1641with the same name as a built-in command.
1642.It Ic bind Oo Fl aeklrsv Oc Oo Ar key Oo Ar command Oc Oc
1643List or alter key bindings for the line editor.
1644This command is documented in
1645.Xr editrc 5 .
1646.It Ic cd Oo Fl L | P Oc Op Ar directory
1647Switch to the specified
1648.Ar directory ,
1649or to the directory specified in the
1650.Va HOME
1651environment variable if no
1652.Ar directory
1653is specified.
1654If
1655.Ar directory
1656does not begin with
1657.Pa / , \&. ,
1658or
1659.Pa .. ,
1660then the directories listed in the
1661.Va CDPATH
1662variable will be
1663searched for the specified
1664.Ar directory .
1665If
1666.Va CDPATH
1667is unset, the current directory is searched.
1668The format of
1669.Va CDPATH
1670is the same as that of
1671.Va PATH .
1672In an interactive shell,
1673the
1674.Ic cd
1675command will print out the name of the directory
1676that it actually switched to
1677if this is different from the name that the user gave.
1678These may be different either because the
1679.Va CDPATH
1680mechanism was used or because a symbolic link was crossed.
1681.Pp
1682If the
1683.Fl P
1684option is specified,
1685.Pa ..
1686is handled physically and symbolic links are resolved before
1687.Pa ..
1688components are processed.
1689If the
1690.Fl L
1691option is specified,
1692.Pa ..
1693is handled logically.
1694This is the default.
1695.It Ic chdir
1696A synonym for the
1697.Ic cd
1698built-in command.
1699.It Ic command Oo Fl p Oc Op Ar utility Op Ar argument ...
1700.It Ic command Oo Fl v | V Oc Op Ar utility
1701The first form of invocation executes the specified
1702.Ar utility ,
1703ignoring shell functions in the search.
1704If
1705.Ar utility
1706is a special builtin,
1707it is executed as if it were a regular builtin.
1708.Pp
1709If the
1710.Fl p
1711option is specified, the command search is performed using a
1712default value of
1713.Va PATH
1714that is guaranteed to find all of the standard utilities.
1715.Pp
1716If the
1717.Fl v
1718option is specified,
1719.Ar utility
1720is not executed but a description of its interpretation by the shell is
1721printed.
1722For ordinary commands the output is the path name; for shell built-in
1723commands, shell functions and keywords only the name is written.
1724Aliases are printed as
1725.Dq Ic alias Ar name Ns = Ns Ar value .
1726.Pp
1727The
1728.Fl V
1729option is identical to
1730.Fl v
1731except for the output.
1732It prints
1733.Dq Ar utility Ic is Ar description
1734where
1735.Ar description
1736is either
1737the path name to
1738.Ar utility ,
1739a special shell builtin,
1740a shell builtin,
1741a shell function,
1742a shell keyword
1743or
1744an alias for
1745.Ar value .
1746.It Ic echo Oo Fl e | n Oc Op Ar string ...
1747Print a space-separated list of the arguments to the standard output
1748and append a newline character.
1749.Bl -tag -width indent
1750.It Fl n
1751Suppress the output of the trailing newline.
1752.It Fl e
1753Process C-style backslash escape sequences.
1754The
1755.Ic echo
1756command understands the following character escapes:
1757.Bl -tag -width indent
1758.It \ea
1759Alert (ring the terminal bell)
1760.It \eb
1761Backspace
1762.It \ec
1763Suppress the trailing newline (this has the side-effect of truncating the
1764line if it is not the last character)
1765.It \ee
1766The ESC character
1767.Tn ( ASCII
17680x1b)
1769.It \ef
1770Formfeed
1771.It \en
1772Newline
1773.It \er
1774Carriage return
1775.It \et
1776Horizontal tab
1777.It \ev
1778Vertical tab
1779.It \e\e
1780Literal backslash
1781.It \e0nnn
1782(Zero) The character whose octal value is
1783.Ar nnn
1784.El
1785.Pp
1786If
1787.Ar string
1788is not enclosed in quotes then the backslash itself must be escaped
1789with a backslash to protect it from the shell.
1790For example
1791.Bd -literal -offset indent
1792$ echo -e "a\evb"
1793a
1794 b
1795$ echo -e a\e\evb
1796a
1797 b
1798$ echo -e "a\e\eb"
1799a\eb
1800$ echo -e a\e\e\e\eb
1801a\eb
1802.Ed
1803.El
1804.Pp
1805Only one of the
1806.Fl e
1807and
1808.Fl n
1809options may be specified.
1810.It Ic eval Ar string ...
1811Concatenate all the arguments with spaces.
1812Then re-parse and execute the command.
1813.It Ic exec Op Ar command Op arg ...
1814Unless
1815.Ar command
1816is omitted,
1817the shell process is replaced with the specified program
1818(which must be a real program, not a shell built-in command or function).
1819Any redirections on the
1820.Ic exec
1821command are marked as permanent,
1822so that they are not undone when the
1823.Ic exec
1824command finishes.
1825.It Ic exit Op Ar exitstatus
1826Terminate the shell process.
1827If
1828.Ar exitstatus
1829is given
1830it is used as the exit status of the shell;
1831otherwise the exit status of the preceding command is used.
1832The exit status should be an integer between 0 and 255.
1833.It Ic export Ar name ...
1834.It Ic export Op Fl p
1835The specified names are exported so that they will
1836appear in the environment of subsequent commands.
1837The only way to un-export a variable is to
1838.Ic unset
1839it.
1840The shell allows the value of a variable to be set
1841at the same time as it is exported by writing
1842.Pp
1843.D1 Ic export Ar name Ns = Ns Ar value
1844.Pp
1845With no arguments the
1846.Ic export
1847command lists the names
1848of all exported variables.
1849If the
1850.Fl p
1851option is specified, the exported variables are printed as
1852.Dq Ic export Ar name Ns = Ns Ar value
1853lines, suitable for re-input to the shell.
1854.It Ic false
1855A null command that returns a non-zero (false) exit value.
1856.It Ic fc Oo Fl e Ar editor Oc Op Ar first Op Ar last
1857.It Ic fc Fl l Oo Fl nr Oc Op Ar first Op Ar last
1858.It Ic fc Fl s Oo Ar old Ns = Ns Ar new Oc Op Ar first
1859The
1860.Ic fc
1861built-in command lists, or edits and re-executes,
1862commands previously entered to an interactive shell.
1863.Bl -tag -width indent
1864.It Fl e Ar editor
1865Use the editor named by
1866.Ar editor
1867to edit the commands.
1868The
1869.Ar editor
1870string is a command name,
1871subject to search via the
1872.Va PATH
1873variable.
1874The value in the
1875.Va FCEDIT
1876variable is used as a default when
1877.Fl e
1878is not specified.
1879If
1880.Va FCEDIT
1881is null or unset, the value of the
1882.Va EDITOR
1883variable is used.
1884If
1885.Va EDITOR
1886is null or unset,
1887.Xr ed 1
1888is used as the editor.
1889.It Fl l No (ell)
1890List the commands rather than invoking
1891an editor on them.
1892The commands are written in the
1893sequence indicated by the
1894.Ar first
1895and
1896.Ar last
1897operands, as affected by
1898.Fl r ,
1899with each command preceded by the command number.
1900.It Fl n
1901Suppress command numbers when listing with
1902.Fl l .
1903.It Fl r
1904Reverse the order of the commands listed
1905(with
1906.Fl l )
1907or edited
1908(with neither
1909.Fl l
1910nor
1911.Fl s ) .
1912.It Fl s
1913Re-execute the command without invoking an editor.
1914.It Ar first
1915.It Ar last
1916Select the commands to list or edit.
1917The number of previous commands that can be accessed
1918are determined by the value of the
1919.Va HISTSIZE
1920variable.
1921The value of
1922.Ar first
1923or
1924.Ar last
1925or both are one of the following:
1926.Bl -tag -width indent
1927.It Oo Cm + Oc Ns Ar num
1928A positive number representing a command number;
1929command numbers can be displayed with the
1930.Fl l
1931option.
1932.It Fl Ar num
1933A negative decimal number representing the
1934command that was executed
1935.Ar num
1936of
1937commands previously.
1938For example, \-1 is the immediately previous command.
1939.It Ar string
1940A string indicating the most recently entered command
1941that begins with that string.
1942If the
1943.Ar old Ns = Ns Ar new
1944operand is not also specified with
1945.Fl s ,
1946the string form of the first operand cannot contain an embedded equal sign.
1947.El
1948.El
1949.Pp
1950The following variables affect the execution of
1951.Ic fc :
1952.Bl -tag -width ".Va HISTSIZE"
1953.It Va FCEDIT
1954Name of the editor to use for history editing.
1955.It Va HISTSIZE
1956The number of previous commands that are accessible.
1957.El
1958.It Ic fg Op Ar job
1959Move the specified
1960.Ar job
1961or the current job to the foreground.
1962.It Ic getopts Ar optstring var
1963The
1964.Tn POSIX
1965.Ic getopts
1966command.
1967The
1968.Ic getopts
1969command deprecates the older
1970.Xr getopt 1
1971command.
1972The first argument should be a series of letters, each possibly
1973followed by a colon which indicates that the option takes an argument.
1974The specified variable is set to the parsed option.
1975The index of
1976the next argument is placed into the shell variable
1977.Va OPTIND .
1978If an option takes an argument, it is placed into the shell variable
1979.Va OPTARG .
1980If an invalid option is encountered,
1981.Ar var
1982is set to
1983.Ql \&? .
1984It returns a false value (1) when it encounters the end of the options.
1985.It Ic hash Oo Fl rv Oc Op Ar command ...
1986The shell maintains a hash table which remembers the locations of commands.
1987With no arguments whatsoever, the
1988.Ic hash
1989command prints out the contents of this table.
1990Entries which have not been looked at since the last
1991.Ic cd
1992command are marked with an asterisk;
1993it is possible for these entries to be invalid.
1994.Pp
1995With arguments, the
1996.Ic hash
1997command removes each specified
1998.Ar command
1999from the hash table (unless they are functions) and then locates it.
2000With the
2001.Fl v
2002option,
2003.Ic hash
2004prints the locations of the commands as it finds them.
2005The
2006.Fl r
2007option causes the
2008.Ic hash
2009command to delete all the entries in the hash table except for functions.
2010.It Ic jobid Op Ar job
2011Print the process IDs of the processes in the specified
2012.Ar job .
2013If the
2014.Ar job
2015argument is omitted, use the current job.
2016.It Ic jobs Oo Fl lps Oc Op Ar job ...
2017Print information about the specified jobs, or all jobs if no
2018.Ar job
2019argument is given.
2020The information printed includes job ID, status and command name.
2021.Pp
2022If the
2023.Fl l
2024option is specified, the PID of each job is also printed.
2025If the
2026.Fl p
2027option is specified, only the process IDs for the process group leaders
2028are printed, one per line.
2029If the
2030.Fl s
2031option is specified, only the PIDs of the job commands are printed, one per
2032line.
2033.It Ic local Oo Ar variable ... Oc Op Fl
2034See the
2035.Sx Functions
2036subsection.
2037.It Ic pwd Op Fl L | P
2038Print the path of the current directory.
2039The built-in command may
2040differ from the program of the same name because the
2041built-in command remembers what the current directory
2042is rather than recomputing it each time.
2043This makes
2044it faster.
2045However, if the current directory is
2046renamed,
2047the built-in version of
2048.Xr pwd 1
2049will continue to print the old name for the directory.
2050.Pp
2051If the
2052.Fl P
2053option is specified, symbolic links are resolved.
2054If the
2055.Fl L
2056option is specified, the shell's notion of the current directory
2057is printed (symbolic links are not resolved).
2058This is the default.
2059.It Ic read Oo Fl p Ar prompt Oc Oo
2060.Fl t Ar timeout Oc Oo Fl er Oc Ar variable ...
2061The
2062.Ar prompt
2063is printed if the
2064.Fl p
2065option is specified
2066and the standard input is a terminal.
2067Then a line is
2068read from the standard input.
2069The trailing newline
2070is deleted from the line and the line is split as
2071described in the section on
2072.Sx White Space Splitting (Field Splitting)
2073above, and
2074the pieces are assigned to the variables in order.
2075If there are more pieces than variables, the remaining
2076pieces (along with the characters in
2077.Va IFS
2078that separated them)
2079are assigned to the last variable.
2080If there are more variables than pieces, the remaining
2081variables are assigned the null string.
2082.Pp
2083Backslashes are treated specially, unless the
2084.Fl r
2085option is
2086specified.
2087If a backslash is followed by
2088a newline, the backslash and the newline will be
2089deleted.
2090If a backslash is followed by any other
2091character, the backslash will be deleted and the following
2092character will be treated as though it were not in
2093.Va IFS ,
2094even if it is.
2095.Pp
2096If the
2097.Fl t
2098option is specified and the
2099.Ar timeout
2100elapses before a complete line of input is supplied,
2101the
2102.Ic read
2103command will return an exit status of 1 without assigning any values.
2104The
2105.Ar timeout
2106value may optionally be followed by one of
2107.Ql s ,
2108.Ql m
2109or
2110.Ql h
2111to explicitly specify seconds, minutes or hours.
2112If none is supplied,
2113.Ql s
2114is assumed.
2115.Pp
2116The
2117.Fl e
2118option exists only for backward compatibility with older scripts.
2119.It Ic readonly Oo Fl p Oc Op Ar name ...
2120Each specified
2121.Ar name
2122is marked as read only,
2123so that it cannot be subsequently modified or unset.
2124The shell allows the value of a variable to be set
2125at the same time as it is marked read only
2126by using the following form:
2127.Pp
2128.D1 Ic readonly Ar name Ns = Ns Ar value
2129.Pp
2130With no arguments the
2131.Ic readonly
2132command lists the names of all read only variables.
2133If the
2134.Fl p
2135option is specified, the read-only variables are printed as
2136.Dq Ic readonly Ar name Ns = Ns Ar value
2137lines, suitable for re-input to the shell.
2138.It Ic return Op Ar exitstatus
2139See the
2140.Sx Functions
2141subsection.
2142.It Ic set Oo Fl /+abCEefIimnpTuVvx Oc Oo Fl /+o Ar longname Oc Oo
2143.Fl c Ar string Oc Op Fl - Ar arg ...
2144The
2145.Ic set
2146command performs three different functions:
2147.Bl -item
2148.It
2149With no arguments, it lists the values of all shell variables.
2150.It
2151If options are given,
2152either in short form or using the long
2153.Dq Fl /+o Ar longname
2154form,
2155it sets or clears the specified options as described in the section called
2156.Sx Argument List Processing .
2157.It
2158If the
2159.Dq Fl -
2160option is specified,
2161.Ic set
2162will replace the shell's positional parameters with the subsequent
2163arguments.
2164If no arguments follow the
2165.Dq Fl -
2166option,
2167all the positional parameters will be cleared,
2168which is equivalent to executing the command
2169.Dq Li "shift $#" .
2170The
2171.Dq Fl -
2172flag may be omitted when specifying arguments to be used
2173as positional replacement parameters.
2174This is not recommended,
2175because the first argument may begin with a dash
2176.Pq Ql -
2177or a plus
2178.Pq Ql + ,
2179which the
2180.Ic set
2181command will interpret as a request to enable or disable options.
2182.El
2183.It Ic setvar Ar variable value
2184Assigns the specified
2185.Ar value
2186to the specified
2187.Ar variable .
2188The
2189.Ic setvar
2190command is intended to be used in functions that
2191assign values to variables whose names are passed as parameters.
2192In general it is better to write
2193.Dq Ar variable Ns = Ns Ar value
2194rather than using
2195.Ic setvar .
2196.It Ic shift Op Ar n
2197Shift the positional parameters
2198.Ar n
2199times, or once if
2200.Ar n
2201is not specified.
2202A shift sets the value of
2203.Li $1
2204to the value of
2205.Li $2 ,
2206the value of
2207.Li $2
2208to the value of
2209.Li $3 ,
2210and so on,
2211decreasing the value of
2212.Li $#
2213by one.
2214If there are zero positional parameters, shifting does not do anything.
2215.It Ic test
2216A built-in equivalent of
2217.Xr test 1 .
2218.It Ic times
2219Print the amount of time spent executing the shell and its children.
2220The first output line shows the user and system times for the shell
2221itself, the second one contains the user and system times for the
2222children.
2223.It Ic trap Oo Ar action Oc Ar signal ...
2224.It Ic trap Fl l
2225Cause the shell to parse and execute
2226.Ar action
2227when any specified
2228.Ar signal
2229is received.
2230The signals are specified by name or number.
2231In addition, the pseudo-signal
2232.Cm EXIT
2233may be used to specify an
2234.Ar action
2235that is performed when the shell terminates.
2236The
2237.Ar action
2238may be an empty string or a dash
2239.Pq Ql - ;
2240the former causes the specified signal to be ignored
2241and the latter causes the default action to be taken.
2242Omitting the
2243.Ar action
2244is another way to request the default action, for compatibility reasons this
2245usage is not recommended though.
2246When the shell forks off a subshell,
2247it resets trapped (but not ignored) signals to the default action.
2248The
2249.Ic trap
2250command has no effect on signals that were ignored on entry to the shell.
2251.Pp
2252Option
2253.Fl l
2254causes the
2255.Ic trap
2256command to display a list of valid signal names.
2257.It Ic true
2258A null command that returns a 0 (true) exit value.
2259.It Ic type Op Ar name ...
2260Interpret each
2261.Ar name
2262as a command and print the resolution of the command search.
2263Possible resolutions are:
2264shell keyword, alias, special shell builtin, shell builtin, command,
2265tracked alias
2266and not found.
2267For aliases the alias expansion is printed;
2268for commands and tracked aliases
2269the complete pathname of the command is printed.
2270.It Ic ulimit Oo Fl HSabcdflmnpstuvw Oc Op Ar limit
2271Set or display resource limits (see
2272.Xr getrlimit 2 ) .
2273If
2274.Ar limit
2275is specified, the named resource will be set;
2276otherwise the current resource value will be displayed.
2277.Pp
2278If
2279.Fl H
2280is specified, the hard limits will be set or displayed.
2281While everybody is allowed to reduce a hard limit,
2282only the superuser can increase it.
2283The
2284.Fl S
2285option
2286specifies the soft limits instead.
2287When displaying limits,
2288only one of
2289.Fl S
2290or
2291.Fl H
2292can be given.
2293The default is to display the soft limits,
2294and to set both the hard and the soft limits.
2295.Pp
2296Option
2297.Fl a
2298causes the
2299.Ic ulimit
2300command to display all resources.
2301The parameter
2302.Ar limit
2303is not acceptable in this mode.
2304.Pp
2305The remaining options specify which resource value is to be
2306displayed or modified.
2307They are mutually exclusive.
2308.Bl -tag -width indent
2309.It Fl b Ar sbsize
2310The maximum size of socket buffer usage, in bytes.
2311.It Fl c Ar coredumpsize
2312The maximal size of core dump files, in 512-byte blocks.
2313.It Fl d Ar datasize
2314The maximal size of the data segment of a process, in kilobytes.
2315.It Fl f Ar filesize
2316The maximal size of a file, in 512-byte blocks.
2317.It Fl l Ar lockedmem
2318The maximal size of memory that can be locked by a process, in
2319kilobytes.
2320.It Fl m Ar memoryuse
2321The maximal resident set size of a process, in kilobytes.
2322.It Fl n Ar nofiles
2323The maximal number of descriptors that could be opened by a process.
2324.It Fl p Ar pseudoterminals
2325The maximal number of pseudo-terminals for this user ID.
2326.It Fl s Ar stacksize
2327The maximal size of the stack segment, in kilobytes.
2328.It Fl t Ar time
2329The maximal amount of CPU time to be used by each process, in seconds.
2330.It Fl u Ar userproc
2331The maximal number of simultaneous processes for this user ID.
2332.It Fl v Ar virtualmem
2333The maximal virtual size of a process, in kilobytes.
2334.It Fl w Ar swapuse
2335The maximum amount of swap space reserved or used for this user ID,
2336in kilobytes.
2337.El
2338.It Ic umask Oo Fl S Oc Op Ar mask
2339Set the file creation mask (see
2340.Xr umask 2 )
2341to the octal or symbolic (see
2342.Xr chmod 1 )
2343value specified by
2344.Ar mask .
2345If the argument is omitted, the current mask value is printed.
2346If the
2347.Fl S
2348option is specified, the output is symbolic, otherwise the output is octal.
2349.It Ic unalias Oo Fl a Oc Op Ar name ...
2350The specified alias names are removed.
2351If
2352.Fl a
2353is specified, all aliases are removed.
2354.It Ic unset Oo Fl fv Oc Ar name ...
2355The specified variables or functions are unset and unexported.
2356If the
2357.Fl v
2358option is specified or no options are given, the
2359.Ar name
2360arguments are treated as variable names.
2361If the
2362.Fl f
2363option is specified, the
2364.Ar name
2365arguments are treated as function names.
2366.It Ic wait Op Ar job
2367Wait for the specified
2368.Ar job
2369to complete and return the exit status of the last process in the
2370.Ar job .
2371If the argument is omitted, wait for all jobs to complete
2372and return an exit status of zero.
2373.El
2374.Ss Commandline Editing
2375When
2376.Nm
2377is being used interactively from a terminal, the current command
2378and the command history
2379(see
2380.Ic fc
2381in
2382.Sx Built-in Commands )
2383can be edited using
2384.Nm vi Ns -mode
2385command line editing.
2386This mode uses commands similar
2387to a subset of those described in the
2388.Xr vi 1
2389man page.
2390The command
2391.Dq Li "set -o vi"
2392(or
2393.Dq Li "set -V" )
2394enables
2395.Nm vi Ns -mode
2396editing and places
2397.Nm
2398into
2399.Nm vi
2400insert mode.
2401With
2402.Nm vi Ns -mode
2403enabled,
2404.Nm
2405can be switched between insert mode and command mode by typing
2406.Aq ESC .
2407Hitting
2408.Aq return
2409while in command mode will pass the line to the shell.
2410.Pp
2411Similarly, the
2412.Dq Li "set -o emacs"
2413(or
2414.Dq Li "set -E" )
2415command can be used to enable a subset of
2416.Nm emacs Ns -style
2417command line editing features.
2418.Sh ENVIRONMENT
2419The following environment variables affect the execution of
2420.Nm :
2421.Bl -tag -width ".Ev LANGXXXXXX"
2422.It Ev ENV
2423Initialization file for interactive shells.
2424.It Ev LANG , Ev LC_*
2425Locale settings.
2426These are inherited by children of the shell,
2427and is used in a limited manner by the shell itself.
2428.It Ev PWD
2429An absolute pathname for the current directory,
2430possibly containing symbolic links.
2431This is used and updated by the shell.
2432.It Ev TERM
2433The default terminal setting for the shell.
2434This is inherited by children of the shell, and is used in the history
2435editing modes.
2436.El
2437.Pp
2438Additionally, all environment variables are turned into shell variables
2439at startup,
2440which may affect the shell as described under
2441.Sx Special Variables .
2442.Sh EXIT STATUS
2443Errors that are detected by the shell, such as a syntax error, will
2444cause the shell to exit with a non-zero exit status.
2445If the shell is not an interactive shell, the execution of the shell
2446file will be aborted.
2447Otherwise the shell will return the exit status of the last command
2448executed, or if the
2449.Ic exit
2450builtin is used with a numeric argument, it
2451will return the argument.
2452.Sh SEE ALSO
2453.Xr builtin 1 ,
2454.Xr chsh 1 ,
2455.Xr echo 1 ,
2456.Xr ed 1 ,
2457.Xr emacs 1 ,
2458.Xr expr 1 ,
2459.Xr getopt 1 ,
2460.Xr pwd 1 ,
2461.Xr test 1 ,
2462.Xr vi 1 ,
2463.Xr execve 2 ,
2464.Xr getrlimit 2 ,
2465.Xr umask 2 ,
2466.Xr editrc 5
2467.Sh HISTORY
2468A
2469.Nm
2470command, the Thompson shell, appeared in
2471.At v1 .
2472It was superseded in
2473.At v7
2474by the Bourne shell, which inherited the name
2475.Nm .
2476.Pp
2477This version of
2478.Nm
2479was rewritten in 1989 under the
2480.Bx
2481license after the Bourne shell from
2482.At V.4 .
2483.Sh AUTHORS
2484This version of
2485.Nm
2486was originally written by
2487.An Kenneth Almquist .
2488.Sh BUGS
2489The
2490.Nm
2491utility does not recognize multibyte characters.
2492