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