Index Click this button to go to the index for this section.


sh(1b)

NAME

sh, Rsh - The Bourne shell, an interactive command interpreter and command programming language

SYNOPSIS

sh [-ir] [+ | -aefhkntuvx] [file] [argument ...] [-ccommand_string | -s] Rsh [-ir] [+ | -aefhkntuvx] [file] [argument ...] [-ccommand_string | -s] The shell carries out commands either interactively from a keyboard or from a file.

DESCRIPTION

The Bourne shell is a command programming language that executes commands read from a terminal or a file. The Rsh command specifies a restricted version of the standard command interpreter sh; Rsh is used to set up login names and execution environments whose capabilities are more controlled than those of the standard shell. This allows you to create user environments that have a limited set of privileges and capabilities. (See Restricted Shell for more information.) A file from which the shell carries out commands is usually called a shell script, a shell procedure, or a command file. A simple command is a sequence of words separated by spaces or tabs. A word is a sequence of characters that contains no unquoted spaces or tabs. The first word in the sequence (numbered as 0), usually specifies the name of a command. Any remaining words, with a few exceptions, are passed to that command. A space refers to both spaces and tabs. The value of a simple command is its exit value if it ends normally, or (octal) 200 added to the signal number if it terminates due to a signal. For a list of status values, see the signal() system call. A pipeline is a sequence of one or more commands separated by a | (vertical bar) or, for historical compatibility, by a ^ (circumflex). In a pipeline, the standard output of each command becomes the standard input of the next command. Each command runs as a separate process, and the shell waits for the last command to end. A filter is a command that reads its standard input, transforms it in some way, then writes it to its standard output. A pipeline normally consists of a series of filters. Although the processes in a pipeline (except the first process) can execute in parallel, they are synchronized to the extent that each program needs to read the output of its predecessor. The exit value of a pipeline is the exit value of the last command. A list is a sequence of one or more pipelines separated by ; (semicolon), & (ampersand), && (two ampersands), or || (two vertical bars) and optionally ended by a ; (semicolon), an & (ampersand), a |& (coprocess), or a newline. These separators and terminators have the following effects: ; Causes sequential execution of the preceding pipeline; the shell waits for the pipeline to finish. & Causes asynchronous execution of the preceding pipeline; the shell does not wait for the pipeline to finish. && Causes the list following it to be executed only if the preceding pipeline returns a 0 (zero) exit value. || Causes the list following it to be executed only if the preceding pipeline returns a nonzero exit value. The cd command is an exception; if it returns a nonzero exit value, no subsequent commands in a list are executed, regardless of the separator characters. The ; and & separators have equal precedence, as do && and ||. The single-character separators have lower precedence than the double-character separators. An unquoted newline character following a pipeline functions the same as a ; (semicolon). The shell treats as a comment any word that begins with a # character and ignores that word and all characters following up to the next newline character. Shell Flow Control Statements Unless otherwise stated, the value returned by a statement is that of the last simple command executed in the statement. for identifier [in word ...] do list done For each word, sets identifier to word and executes the commands in list. If you omit in word ..., then the for command executes list for each positional parameter that is set. Execution ends when there are no more words in the list. case word in [pattern [ | pattern ] ...) list ;;] ... esac Executes the commands in the list associated with the first pattern that matches word. Uses the same character-matching notation in patterns that you use for file name substitution (see File name Substitution), except that you do not need to match explicitly a / (slash), a leading . (dot), or a . (dot) immediately following a / (slash). if list then list [elif list then list] ... [else list] fi Executes the list following the if keyword. If it returns a 0 (zero) exit value, executes the list following the first then. Otherwise, executes the list following elif (if there is an elif), and if its exit value is 0 (zero), executes the next then. Failing that, executes the list following the else. If no else list or then list is executed, the if command returns a 0 (zero) exit value. while list do list done Executes the list following the while. If the exit value of the last command in the list is 0 (zero), executes the list following do. Continues looping through the lists until the exit value of the last command in the while list is nonzero. If no commands in the do list are executed, the while command returns a 0 (zero) exit value. until list do list done Executes the list following the until. If the exit value of the last command in the list is nonzero, executes the list following do. Continues looping through the lists until the exit value of the last command in the until list is 0 (zero). If no commands in the do list are executed, the until command returns a 0 (zero) exit value. (list) Executes the commands in list in a subshell. { list; } Executes the commands in list in the current shell process; does not spawn a subshell. name () { list; } Defines a function that is referenced by name. The body of the function is the list of commands between the braces. The following reserved words are recognized only when they appear without quotes as the first word of a command. if esac then case else for elif while fi until do done { } Command Execution Each time the shell executes a command, it carries out the substitutions discussed in the following text. If the command name matches one of the built-in commands discussed in Built-In Commands, it executes it in the shell process. If the command name does not match a built-in command but matches the name of a defined function, it executes the function in the shell process. The shell sets the positional parameters to the parameters of the function. If the command name matches neither a built-in command nor the name of a defined function and the command names an executable file that is a compiled (binary) program, the shell (as parent) spawns a new (child) process that immediately runs the program. If the file is marked executable but is not a compiled program, the shell assumes that it is a shell script. In this case, the shell spawns another instance of itself (a subshell), to read the file and execute the commands included in it (note how this differs from the execution of functions). The shell also executes a command enclosed in parentheses in a subshell. From the perspective of an end user, a compiled program is run in exactly the same way as a shell script. The shell normally searches for commands in two places in the file system. The shell first looks for the command in the current directory; if it does not find the command there, it looks in the /usr/bin directory. This search order is in effect if the PATH environment variable is not set (or is set to :/usr/bin, as is the case by default on many systems). You can also give a specific pathname when you invoke a command, for example /usr/bin/sort, in which case the shell does not search any directories other than the one you specify in the pathname. If the command name contains a / (slash), the shell does not use the search path (note that the restricted shell will not execute such commands). You can give a full pathname that begins with the root directory (as in /usr/bin/sort), or a pathname relative to the current directory, for example bin/myfile. In this last case, the shell looks in the current directory for a directory named bin and in that directory for myfile. You can change the particular sequence of directories searched by resetting the PATH variable (see Variables Used by the Shell). The shell remembers the location in the search path of each executed command (to avoid unnecessary exec commands later). If the command was found in a relative directory (one whose name does not begin with /), the shell must redetermine its location whenever the current directory changes. The shell forgets all remembered locations whenever you change the PATH variable or execute the hash -r command (see Built-In Commands). Signals The shell ignores SIGINT and SIGQUIT signals for an invoked command if the command is terminated with a & (that is, if it is running in the background). Otherwise, signals have the values inherited by the shell from its parent, with the exception of signal 11 (see also the built-in trap command in Built-In Commands). Initialization Files When you log in, the shell is called to read your commands. Before it does that, however, it checks to see if a file named /etc/profile exists on the system, and if it does, it reads commands from it (this file sets variables needed by all users). After this, the shell looks for a file named .profile in your login directory. If it finds one, it executes commands from it. Finally, the shell is ready to read commands from your standard input. File name Substitution Command arguments are very often file names. You can automatically produce a list of file names as arguments on a command line by specifying a pattern that the shell matches against the file names in a directory. Most characters in such a pattern match themselves, but you can also use some special pattern-matching characters in your pattern. These special characters are as follows: . Matches any single character, except a newline character. * Matches any string, including the null string. ? Matches any one character. [ ...] Matches any one of the characters enclosed in brackets. [! ...] Matches any character other than those that follow the exclamation point within brackets. Inside brackets, a pair of characters separated by a - (dash) specifies a set of all characters lexically within the inclusive range of that pair according to the current collating sequence. The LANG and LC_COLLATE environment variables control the collating sequence. The current collating sequence groups characters into equivalence classes for the purpose of defining the endpoints of a range of characters. For example, if the collating sequence defines the lexical order to be AaBbCc ... and groups uppercase and lowercase characters into equivalence classes, then all the following have the same effect: [a-c], [A-C], [a-C], and [A- c]. Pattern matching has some restrictions. If the first character of a file name is a . (dot), it can be matched only by a pattern that begins with a dot. For example, * (asterisk) matches the file names myfile and yourfile, but not the file names .myfile and .yourfile. To match these files, use a pattern such as the following: .*file If a pattern does not match any file names, then the pattern itself is returned as the result of the attempted match. File and directory names should not contain the characters *, ?, [, or ], because this requires quoting those names in order to refer to the files and directories. Shell Variables and Command-Line Substitutions The shell has several mechanisms for creating variables (assigning a string value to a name). Certain variables, positional parameters and keyword parameters, are normally set only on a command line. Other variables are simply names to which you or the shell can assign string values. Positional Parameters When you run a shell script, the shell implicitly creates positional parameters that reference each word on the command line by its position on the command line. The word in position 0 (the procedure name), is called $0, the next word (the first parameter) is called $1, and so on up to $9. To refer to command-line parameters numbered higher than 9, use the built- in shift command (see Built-In Commands). You can also assign values to these positional parameters explicitly by using the built-in set command (see Built-In Commands). When an argument for a position is not specified, its positional parameter is set to null. Positional parameters are global and can be passed to nested shell scripts. User-Defined Variables The shell also recognizes alphanumeric variables to which string values can be assigned. You assign a string value to a name, as follows: name=string A name is a sequence of letters, digits, and underscores that begins with an underscore or a letter. To use the value that you have assigned to a variable, add a $ (dollar sign) to the beginning of its name. Thus, $name yields the value string. Note that no spaces surround the = (equal sign) in an assignment statement. (Positional parameters cannot appear in an assignment statement; they can only be set as described earlier.) You can put more than one assignment on a command line, but remember: the shell performs the assignments from right to left. If you surround string with quotes, either " " (double) or ' ' (single), the shell does not treat spaces, tabs, semicolons, and newline characters within it as word delimiters but embeds them literally in the string. If you surround string with double quotes, the shell still recognizes variable names in the string and performs variable substitution; that is, it replaces references to positional parameters and other variable names that are prefaced by $ with their corresponding values, if any. The shell also performs command substitution (see Command Substitution) within strings that are surrounded by double quotes. If you surround string with single quotes, the shell does no variable or command substitution within the string. The following sequence illustrates this difference: You enter: stars=***** asterisks1="Add $stars" asterisks2='Add $stars' echo $asterisks1 The system displays: Add ***** You enter: echo $asterisks2 The system displays: Add $stars The shell does not reinterpret spaces in assignments after variable substitution (see Interpretation of Spaces). Thus, the following assignments result in $first and $second having the same value: first='a string with embedded spaces' second=$first When you reference a variable, you can enclose the variable name (or the digit designating a positional parameter) in { } (braces) to delimit the variable name from any following string. In particular, if the character immediately following the name is a letter, digit, or underscore and the variable is not a positional parameter, then the braces are required: You enter: a='This is a' echo "${a}n example" The system displays: This is an example You enter: echo "$a test" The system displays: This is a test See Conditional Substitution for a different use of braces in variable substitutions. A Command's Environment All the variables (with their associated values) that are known to a command at the beginning of its execution constitute its environment. This environment includes variables that a command inherits from its parent process and variables specified as keyword parameters on the command line that calls the command. The shell passes to its child processes the variables that were named as arguments to the built-in export command. The export command places the named variables in the environments of both the shell and all its future child processes. Keyword parameters are variable-value pairs that appear in the form of assignments, normally before the procedure name on a command line (but see also the -k flag, discussed under the set command in Built-In Commands). Such variables are placed in the environment of the procedure being called. For example, given the following simple procedure that echoes the values of two variables (saved in a command file named key_command): # cat key_command echo $a $b # The following command lines produce the output shown: You enter: a=key1 b=key2 key_command The system displays: key1 key2 You enter: a=tom b=john key_command The system displays: tom john A procedure's keyword parameters are not included in the parameter count stored in $#. A procedure can access the values of any variables in its environment; however, if it changes any of these values, these changes are not reflected in the shell environment. They are local to the procedure in question. To place these changes in the environment that the procedure passes to its child processes, you must export these values within that procedure. To obtain a list of variables that were made exportable from the current shell, enter: export (You will also get a list of variables that were made read only.) To get a list of name-value pairs in the current environment, enter: env Conditional Substitution Normally, the shell replaces $variable with the string value assigned to variable, if there is one. However, there is a special notation that allows conditional substitution, depending on whether the variable is set and is not null. By definition, a variable is set if it was assigned a value. The value of a variable can be the null string, which you can assign to a variable in any one of the following ways: A= bcd="" Efg='' set '' "" The first three of these examples assign the null string to each of the corresponding variable names. The last example sets the first and second positional parameters to the null string and unsets all other positional parameters. The following is a list of the available expressions you can use to perform conditional substitution: ${ variable-string } If the variable is set, substitute the value of variable in place of this expression. Otherwise, replace this expression with the value of string. ${ variable:-string } If the variable is set and is not null, substitute the value of variable in place of this expression. Otherwise, replace this expression with the value of string. ${ variable=string } If the variable is set, substitute the value of variable in place of this expression. Otherwise, set variable to string and then substitute the value of the variable in place of this expression. You cannot assign values to positional parameters in this fashion. ${ variable:=string } If the variable is set and is not null, substitute the value of variable in place of this expression. Otherwise, set variable to string and then substitute the value of the variable in place of this expression. You cannot assign values to positional parameters in this fashion. ${ variable?string } If the variable is set, substitute the value of variable in place of this expression. Otherwise, display a message of the form: variable: string and exit from the current shell, unless the shell is the login shell. If you do not specify string, the shell displays the following message: variable: parameter null or not set ${ variable:?string } If the variable is set and not null, substitute the value of variable in place of this expression. Otherwise, display a message of the form: variable: string and exit from the current shell, unless the shell is the login shell. If you do not specify string, the shell displays the following message: variable: parameter null or not set ${ variable+string } If the variable is set, substitute the value of string in place of this expression. Otherwise, substitute the null string. ${ variable:+string } If the variable is set and not null, substitute the value of string in place of this expression. Otherwise, substitute the null string. In conditional substitution, the shell does not evaluate string until it uses it as a substituted string, so that, in the following example, the shell executes the pwd command only if d is not set or is null: echo ${ d:-`pwd` } Variables Used by the Shell The shell uses the following variables. The shell sets some of them, and you can set or reset all of them. CDPATH The search path for the cd (change directory) command. HOME The name of your login directory, the directory that becomes the current directory upon completion of a login. The login program initializes this variable. The cd command uses the value of $HOME as its default value. If you use this variable in your shell scripts rather than using the full pathname, your procedures run even if your login directory is changed or if another user runs them. LANG Specifies the locale of your system, which is comprised of three parts: language, territory, and codeset. The default locale is the C locale, which specifies the value English for language, U.S. for territory, and ASCII for codeset. The locale specified for the LANG variable controls the language applied to messages. Unless set explicitly, the LC_COLLATE, LC_CTYPE, LC_MESSAGES, LC_MONETARY, LC_NUMERIC, and LC_TIME variables also derive their settings from the locale set for LANG. LC_COLLATE Specifies the collating sequence to use when sorting names and when character ranges occur in patterns. The default value is the collating sequence for American English. If absent, the collating sequence may be taken from the LANG variable. If both LC_COLLATE and LANG are absent, the ANSI C collating sequence is used. LC_CTYPE Specifies the character classification information to use on your system. The default value is American English. LC_MESSAGES Specifies the language that the system expects for user input of yes and no strings. The default value is American English. LC_MONETARY Specifies the monetary format for your system. The default value is the monetary format for American English. LC_NUMERIC Specifies the numeric format for your system. The default value is the numeric format for American English. LC_TIME Specifies the date and time format for your system. The default value is the date and time format for American English. LOGNAME Your login name, marked readonly in the /etc/profile file. MAIL The pathname of the file used by the mail system to detect the arrival of new mail. If MAIL is set, the shell periodically checks the modification time of this file and displays the value of $MAILMSG, if this time changes and the length of the file is greater than 0 (zero). Set MAIL in your .profile file. The value normally assigned to it by users of the mail or mailx commands is /var/spool/mail/$LOGNAME. MAILCHECK The number of seconds that the shell lets elapse before checking again for the arrival of mail in the files specified by the MAILPATH or MAIL variables. The default value is 600 seconds (10 minutes). If you set MAILCHECK to 0 (zero), the shell checks before each prompt. MAILPATH A list of file names separated from one another by a : (colon). If you set this variable, the shell informs you of the arrival of mail in any of the files specified in the list. You can follow each file name by a % (percent sign) and a message to be displayed when mail arrives. Otherwise, the shell uses the value of MAILMSG or, by default, the message you have mail. When MAILPATH is set, these files are checked instead of the file set by MAIL. To check the files set by MAILPATH and the file set by MAIL, specify the MAIL file in your list of MAILPATH files. MAILMSG The mail notification message. If you explicitly set MAILMSG to a null string (MAILMSG=""), no message is displayed. NLSPATH Specifies a list of directories to search to find message catalogs. PATH An ordered list of directory pathnames separated by colons. The shell searches these directories in the specified order when it looks for commands. A null string anywhere in the list represents the current directory. PATH is normally initialized in the /etc/profile file, usually to :/usr/bin (by definition, a null string is assumed in front of the leading colon). You can reset this variable to suit your own needs. Thus, if you wish to search your current directory last rather than first, you would enter: PATH=/usr/bin: If you have a personal directory of commands (say, $HOME/bin) that you want searched before the standard system directories, set your PATH as follows: PATH=$HOME/bin:/usr/bin: The best place to set your PATH to something other than the default value is in your .profile file (see the .profile file). You cannot reset PATH if you are executing commands under the restricted shell (Rsh). PS1 The string to be used as the primary system prompt. An interactive shell displays this prompt string when it expects input. The default value of PS1 is $ followed by a space. PS2 The value of the secondary prompt string. If the shell expects more input when it encounters a newline character in its input, it prompts with the value of PS2. The default value of PS2 is > followed by a space. IFS The characters that are internal field separators (the characters that the shell uses during interpretation of spaces, see Interpretation of Spaces). The shell initially sets IFS to include the space, tab, and newline characters. SHACCT The name of a file that you own. If this variable is set, the shell writes an accounting record in the file for each shell script executed. You can use accounting programs such as acctcom and acctcms to analyze the data collected. SHELL A pathname whose simple part (the part after the last /) contains an r if you want the shell to become restricted when invoked. This should be set and exported by the $HOME/.profile file of each restricted login. TIMEOUT A number of minutes. After the shell displays its prompt, you have TIMEOUT minutes to enter a command. If you fail to do so, the shell exits; in the login shell, such an exit is a logout. Setting TIMEOUT to 0 (zero) inhibits automatic logout. Predefined Special Variables Several variables have special meanings; the following are set only by the shell: $# The number of positional parameters passed to the shell, not counting the name of the shell script itself. The $# variable thus yields the number of the highest-numbered positional parameter that is set. One of the primary uses of this variable is to check for the presence of the required number of arguments. $? The exit value of the last command executed. Its value is a decimal string. Most commands return 0 (zero) to indicate successful completion. The shell itself returns the current value of $? as its exit value. $$ The process number of the current process. Because process numbers are unique among all existing processes, this string of up to five digits is often used to generate unique names for temporary files. The following example illustrates the recommended practice of creating temporary files in a directory used only for that purpose: temp=$HOME/temp/$$ ls >$temp . . . rm $temp $! The process number of the last process run in the background (using the & terminator). Again, this is a string of up to five digits. $- A string consisting of the names of the execution flags (see Built-In Commands) currently set in the shell. Command Substitution To capture the output of any command as an argument to another command, place that command line within ` ` (grave accents). This concept is known as command substitution. The shell first executes the command or commands enclosed within the grave accents, and then replaces the whole expression, grave accents and all, with their output. This feature is often used in assignment statements: today=`date` This statement assigns the string representing the current date to the today variable. The following assignment saves, in the files variable, the number of files in the current directory: files=`ls | wc -l` You perform command substitution on any command that writes to standard output by enclosing that command in grave accents. You can nest command substitutions by preceding each of the inside sets of grave accents with a \ (backslash): logmsg=`echo Your login directory is \`pwd\`` You can also give values to shell variables indirectly by using the built- in read command. The read command takes a line from standard input (usually your keyboard), and assigns consecutive words on that line to any variables named: read first middle last Thus, read will accept the following input line: Jane C. Chen and it will have the same effect as if you had entered the following: first=Jane init=C. last=Chen The read command assigns any excess words to the last variable. Quoting Mechanisms The following characters have a special meaning to the shell and cause termination of a word unless quoted: ; & ( ) | ^ < > <newline> <space> <tab> Using ' ' (single) and " " (double) quotes to surround a string or a \ (backslash) before a single character enables the character to stand for itself, instead of conveying special meaning to the shell. Within single quotes, all characters (except the single quote character itself), are taken literally, with any special meaning removed. Thus, entering: stuff='echo $? $*; ls * | wc' results only in the literal string echo $? $*; ls * | wc being assigned to the stuff variable; the echo, ls, and wc commands are not executed, nor are the variables $? and $* and the special character * expanded by the shell. To verify this you could export the variable stuff with the command export stuff, and then use the command printenv stuff to view it. This is different from the simple command echo $stuff. Within double quotes, the special meaning of certain characters ($, `, and ") does persist, while all other characters are taken literally. Thus, within double quotes, command and variable substitution takes place. In addition, the quotes do not affect the commands within a command substitution that is part of the quoted string, so characters there retain their special meanings. Consider the following sequence: You enter: ls * System displays: file1 file2 file3 You enter: message="This directory contains `ls * ` " echo $message System displays: This directory contains file1 file2 file3 This shows that the * special character inside the command substitution was expanded. To hide the special meaning of $, `, and " within double quotes, precede these characters with a \ (backslash). Outside of double quotes, preceding a character with \ (backslash) is equivalent to placing it within single quotes. Hence, a \ (backslash) immediately preceding the newline character (that is, a \ (backslash) at the end of the line) hides the newline character and allows you to continue the command line on the next physical line. Redirection of Input and Output In general, most commands do not know or care whether their input or output is associated with the keyboard, the display screen, or a file. Thus, a command can be used conveniently either at the keyboard or in a pipeline. Standard Input and Standard Output When a command begins running, it usually expects that three files are already open: standard input, standard output, and standard error (sometimes called error output or standard error output). A number called a file descriptor is associated with each of these files as follows: File descriptor 0 Standard input File descriptor 1 Standard output File descriptor 2 Standard error A child process normally inherits these files from its parent; all three files are initially assigned to the terminal. Conventionally, commands read from standard input (0), write to standard output (1), and write error messages to standard error (2). The shell permits them to be redirected elsewhere before control is passed to a command. Any argument to the shell in the form <file or >file opens the specified file as the standard input or output, respectively. In the case of output, this process destroys the previous contents of file, if it already exists and write permission is available. An argument in the form >>file directs the standard output to the end of file, thus allowing you to add data to it without destroying its existing contents. If file does not exist, the shell creates it. Such redirection arguments are subject only to variable and command substitution; neither interpretation of spaces nor pattern matching of file names occurs after these substitutions. Thus, entering: echo 'this is a test' > *.ggg produces a 1-line file named *.ggg, and entering: cat < ? produces an error message, unless you have a file named ? (a bad choice for a file name). Diagnostic and Other Output Diagnostic output from commands is normally directed to the file associated with file descriptor 2. You can redirect this error output to a file by immediately preceding either output redirection symbol (> or >>) with a 2 (the number of the file descriptor). There must be no space between the file descriptor and the redirection symbol; otherwise, the shell interprets the number as a separate argument to the command. You can also use this method to redirect the output associated with any of the first 10 file descriptors (numbered 0 to 9) so that, for instance, if a command writes to file descriptor 9 (although this is not a recommended programming habit), you can capture that output in a file named savedata as follows: command 9> savedata If a command writes to more than one output, you can independently redirect each one. Suppose that a command directs its standard output to file descriptor 1, directs its error output to file descriptor 2, and builds a data file on file descriptor 9. The following command line redirects each of these outputs to a different file: command > standard 2> error 9> data Inline Input (Here) Documents When the shell sees a command line of the following form, where eof_string is any string that contains no pattern-matching characters, the shell takes the subsequent lines as the standard input of command until it reads a line consisting of only eof_string (possibly preceded by one or more tab characters): command << eof_string The lines between the first eof_string and the second are frequently referred to as a here document. If a - (dash) immediately follows the <<, the shell strips leading tab characters from each line of the input document before it passes the line to the command. The shell creates a temporary file containing the input document and performs variable and command substitution on its contents before passing it to the command. It performs pattern matching on file names that are a part of command lines in command substitutions. If you want to prohibit all substitutions, quote any character of eof_string: command << \eof_string The here document is especially useful for a small amount of input data that is more conveniently placed in the shell script rather than kept in a separate file (such as editor scripts). For instance, you could enter: cat <<- xyz This message is shown on the display with leading tabs removed. xyz This feature is most useful in shell scripts. Inline input documents cannot appear within grave accents (command substitution). I/O Redirection with File Descriptors As discussed previously, a command occasionally directs output to some file associated with a file descriptor other than 1 or 2. The shell also provides a mechanism for creating an output file associated with a particular file descriptor. For example, if you enter the following, where digit1 and digit2 are valid file descriptors, you can direct the output that would normally be associated with file descriptor digit1 to the file associated with digit2: digit1>&digit2 The default value for digit1 and digit2 is 1 (standard output). If, at execution time, no file is associated with digit2, then the redirection is void. The most common use of this mechanism is to direct standard error output to the same file as standard output, as follows: command 2>&1 If you want to redirect both standard output and standard error output to the same file, enter: command > file 2>&1 The order here is significant. First, the shell associates file descriptor 1 with file; then it associates file descriptor 2 with the file that is currently associated with file descriptor 1. If you reverse the order of the redirections, standard error output goes to the display and standard output goes to file because at the time of the error output redirection, file descriptor 1 was still associated with the display. You can also use this mechanism to redirect standard input. You could enter: digit1<&digit2 where digit1 refers to standard input and digit2 refers to standard output, to cause both file descriptors to be associated with the same input file. For commands that run sequentially, the default value of digit1 and digit2 is 0 (standard input). For commands that run asynchronously (commands terminated by &), the default value of digit1 and digit2 is /dev/null. Such input redirection is useful for commands that use two or more input sources. Summary of Redirection Options The following can appear anywhere in a simple command or can precede or follow a command, but they are not passed to the command: <file Use file as standard input. >file Use file as standard output. Create the file if it does not exist; otherwise, truncate it to 0 (zero) length. >>file Use file as standard output. Create the file if it does not exist; otherwise, append the output to the end of the file. <<[-]eof_string Read as standard input all lines from eof_string up to a line containing only eof_string or up to an End-of-File character. If any character in eof_string is quoted, the shell does not expand or interpret any characters in the input lines; otherwise, it performs variable and command substitution and ignores a quoted newline character (\newline). Use a \ (backslash) to quote characters within eof_string or within the input lines. If you add a - (dash) to <<, then all leading tabs are stripped from eof_string and from the input lines. < &digit Associate standard input with file descriptor digit. > &digit Associate standard output with file descriptor digit. < &- Close standard input. > &- Close standard output. The restricted shell does not allow the redirection of output. Interpretation of Spaces After the shell performs variable and command substitution, it scans the results for internal field separators (those defined in the IFS shell variable, see Variables Used by the Shell). It splits the line into distinct words at each place it finds one of these characters. It retains explicit null arguments ("" '') and discards implicit null arguments (those resulting from parameters that have no values). Built-In Commands : Does nothing. This null command returns a 0 (zero) exit value. . file Reads and executes commands from file and returns. Does not spawn a subshell. The search path specified by PATH is used to find the directory containing file. break [n] Exits from the enclosing for, while, or until loop, if any. If n is specified, then breaks n levels. continue [n] Resumes the next iteration of the enclosing for, while, or until loop. If n is specified, resumes at the nth enclosing loop. cd [directory] Changes the current directory to directory. If no directory is specified, the value of the HOME shell variable is used. The CDPATH shell variable defines the search path for directory. Alternative directory names appear in a list, separated from one another by a : (colon). A null pathname specifies the current directory, which is the default path. This null pathname can appear immediately after the = (equal sign) in the assignment or between the colon delimiters anywhere else in the path list. If directory begins with a / (slash), the shell does not use the search path. Otherwise, the shell searches each directory in the path. The cd command cannot be executed by the restricted shell. echo [argument ...] Writes arguments to standard output. eval [argument ...] Reads arguments as input to the shell and executes the resulting commands. The eval command is most often used in command substitution. For example, the following command sets up the shell's TERM and TERMCAP variables according to the type of terminal the user is logged in on: eval `tset -s vt100` exec [argument ...] Executes the command specified by argument in place of this shell without creating a new process. Input and output arguments can appear and, if no other arguments appear, cause the shell input or output to be modified (not a good idea with your login shell). If this command is given from your login shell, you are logged out after the specified command has been executed. exit [n] Causes a shell to exit with the exit value specified by n. If you omit n, the exit value is that of the last command executed. (Pressing the End-of-File key sequence also causes a shell to exit.) The value of n can be from 0 to 255, inclusive. export [name ...] Marks the specified names for automatic export to the environments of subsequently executed commands. If you do not specify a name, the export command displays a list of all the names that are exported in this shell. You cannot export function names. hash [-r] [name ...] For each name, finds and remembers the location in the search path of the command specified by name. The -r flag causes the shell to forget all locations. If you do not specify the flag or any names, the shell displays information about the remembered commands. In this information, hits is the number of times a command has been run by the shell process. The cost is a measure of the work required to locate a command in the search path. There are certain situations that require that the stored location of a command be recalculated (for example, the location of a relative pathname when the current directory changes). Commands for which that might be done are indicated by an * (asterisk) next to the hits information. The cost is incremented when the recalculation is done. inlib library_name This command is no longer supported. See the loader(5) reference page for information on using shared libraries. newgrp [-] [group] Changes the primary group identification of the current shell process to group. If you specify -, newgrp changes the login environment to the login environment of the new group. If you do not specify a group, newgrp changes the group identification to that specified for the current user in the /etc/passwd file. The newgrp command recognizes group names only; it does not recognize group ID numbers. Only a user with superuser authority can change the primary group of the shell to one to which that user does not belong. Any active user-generated shell is terminated when the newgrp command is used. pwd Displays the current directory. See pwd for a discussion of command options. read [name...] Reads one line from standard input. Assigns the first word in the line to the first name, the second word to the second name, and so on, with leftover words assigned to the last name. This command returns a 0 (zero) unless it encounters an end of file. readonly [name...] Marks the specified names as read only. The values of these names cannot be reset. If you do not specify any names, the readonly command displays a list of all readonly names. return [n] Causes a function to exit with a return value of n. If you do not specify n, the function returns the status of the last command executed in that function. This command is valid only when executed within a shell function. rmlib library_name This command is no longer supported. See the loader(5) reference page for information on using shared libraries. set [+ | -flag ...] [argument ...] Sets one or more of the following flags: -a Marks for export all variables that are modified or changed. -e Exits immediately if a command exits with a nonzero exit value. -f Disables file name substitution. -h Locates and remembers the commands called within functions as the functions are defined. (Normally these commands are located when the function is executed; see the built-in hash command.) -k Places all keyword parameters in the environment for a command, not just those that precede the command name. -n Reads commands, but does not execute them. -t Exits after reading and executing one command. -u Treats an unset variable as an error when performing variable substitution. -v Displays shell input lines as they are read. -x Displays commands and their arguments as they are executed. -- Does not change any of the flags. This is useful in setting the $1 positional parameter to a string beginning with a - (dash). Using a + (plus sign) rather than a - (dash) unsets flags. You can also specify these flags on the shell command line. The $- special variable contains the current set of flags. Any arguments to set are positional parameters and are assigned, in order, to $1, $2, and so on. If you do not specify flags or arguments, set displays all names. shift [n] Shifts command-line arguments to the left; that is, reassigns the value of the positional parameters by discarding the current value of $1 and assigning the value of $2 to $1, of $3 to $2, and so on. If there are more than nine command line arguments, the tenth is assigned to $9 and any that remain are still unassigned (until after another shift). If there are nine or fewer arguments, a shift unsets the highest-numbered positional parameter. The command name ($0) is never shifted. The command shift n is a shorthand notation for n consecutive shifts. The default value of n is 1. test expression | [ expression ] Evaluates conditional expressions. See test for a discussion of command options. times Displays the accumulated user and system times for processes run from the shell. trap [command] [n] ... Runs the command specified by command when the shell receives n signals. (Note that the shell scans command once when the trap is set and once when the trap is taken). The trap commands are executed in order of signal number. Any attempt to set a trap on a signal that was ignored on entry to the current shell is ineffective. If you do not specify a command, then all traps n are reset to their current values. If command is a null string, this signal is ignored by the shell and by the commands it invokes. If n is 0 (zero), the command is executed on exit from the shell. If neither a command or a signal (n) is specified, trap displays a list of commands associated with each signal number. Note Although n is an optional parameter, using command without specifying a value for n will have no effect. This is not considered an error. type [name ...] For each name specified, indicates how the shell interprets it as a command name. ulimit [-HS] [-a | -c | -d | -f | -h | -m | -n | -s | -t] [limit] Displays or adjusts allocated shell resources. There are two modes for displaying the shell resource settings, which can either be displayed individually or as a group. The default mode is to display resources set to the soft setting, or the lower bound, as a group. To display the hard, or upper bound, limits, use the -h flag as the only argument for this group. To display an individual soft limit, use the flag that corresponds to the required resource on the command line. To display an individual hard limit, use the -h flag along with the resource flag. The setting of shell resources depends on the effective user ID of the current shell. The hard level of a resource can be set only if the effective user ID of the current shell is root. If a user other than the superuser attempts to set a resource's hard level, an error occurs. By default, the superuser sets both the hard and soft limits of a particular resource. Therefore, the superuser should be careful in using the -S, -H, or default flag usage of limit settings. The standard user can only set the soft limit of a resource. Furthermore, the standard user can only expand the soft limit up to the current hard limit setting. To set a resource limit, choose the appropriate flag and the new resource limit value. The new resource limit value should be an integer. You can set only one resource limit at a time. If more than one resource flag is specified, the results are undefined. By default, ulimit with only a new value on the command line sets the file size of the shell. Therefore, use of the -f flag is optional. You can use the following flags with ulimit: -a Sets or displays the address space for the shell. -c Sets or displays the amount of core segment size for the shell. -d Sets or displays the amount of data segment size for the shell. -f Sets or displays the file size for the shell. -h Sets or displays the current hard resource setting. -H Sets or displays the hard resource limit (superuser only). -m Sets or displays the memory allocation for the shell. -n Sets or displays the maximum number of open file descriptors for the shell. -s Sets or displays the stack segment size for the shell. -S Sets or displays the soft resource limit. -t Sets or displays the CPU time maximum for the shell. (For more information on resource settings, see getrlimit(2).) If no option is given, -f is assumed. umask [nnn] Sets your file-creation mask to the octal value nnn (see the umask() system call). If you omit nnn, umask displays the current value of the mask. unset [name ...] For each name, removes the corresponding variable, built-in command, or function. The PATH, PS1, PS2, MAILCHECK, and IFS variables cannot be unset. wait [n] Waits for the child process whose process number is n to end and reports its termination status. If you do not specify n, then the shell waits for all currently active child processes and the return value is 0 (zero). Character Classes You can use the following notation to match file names within a range indication: [:charclass:] This format instructs the system to match any single character belonging to charclass; the defined classes correspond to ctype() subroutines as follows: alnum alpha cntrl digit graph lower print punct space upper xdigit Your locale might define additional character properties, such as the following: [:vowel:] The preceding character class could be TRUE for a, e, i, o, u, or y. You could then use [:vowel] inside a set construction to match any vowel. Refer to The LC_CTYPE Category section of the locale file format reference page for more information. Running the Shell The sh command can be run either as a login shell or as a subshell under the login shell. Only the login command can call sh as a login shell. It does this by using a special form of the sh command name: -sh. When called with an initial - (dash), the shell first reads and runs commands found in the system .profile file and your $HOME/.profile, if one exists. It then accepts commands as described in the following discussion of flags. Once logged in and working under a login shell, you can call sh with the command name sh. This command runs a subshell, a second shell running as a child of the login shell. Restricted Shell The restricted shell, Rsh, is used to set up login names and execution environments whose capabilities are more controlled than those of the standard shell. The actions of Rsh are identical to those of sh, except that the following are not allowed: · Changing directory (with the cd command) · Setting the value of PATH or SHELL · Specifying pathnames or command names containing / · Redirecting output (with > and >>) A restricted shell can be invoked in one of the following ways: (1) Rsh is the file name part of the last entry in the /etc/passwd file; (2) the environment variable SHELL exists and Rsh is the file name part of its value; (3) the shell is invoked and Rsh is the file name part of argument 0 (zero); (4) the shell is invoked with the -r flag. When a command to be run is determined to be a shell script, Rsh invokes sh to run the command. Thus, it is possible to provide the end user with shell scripts that have access to the full power of the standard shell, while imposing a limited menu of commands; this scheme assumes that the end user does not have write and execute permissions in the same directory. The preceding restrictions are enforced after the .profile file is interpreted. Therefore, the writer of the .profile has complete control over user actions by performing set-up actions and leaving the user in an appropriate directory (probably not the login directory). An administrator can set up a directory of commands in /usr/rbin that the Rsh command can invoke. When called with the name -rsh or -Rsh, Rsh reads the user's .profile from $HOME/.profile. It acts as the standard sh while doing this, except that an Interrupt causes an immediate exit instead of a return to command level. The system administrator should be aware that use of Rsh does not imply that the system is secure. A secure system implements a system-wide framework to protect the system against unauthorized activity. Rsh is not designed to implement this type of system security.

FLAGS

The following flags are interpreted by the shell only when you call it. Unless you specify either the -c or -s flag, the shell assumes that the next argument is a command file (shell procedure). It passes anything else on the command line to that command file (see Positional Parameters). -c command_string Runs commands read from command_string. The shell does not read additional commands from standard input when you specify this flag. -i Makes the shell interactive, even if input and output are not from a terminal. In this case, the shell ignores the SIGTERM signal (so that kill 0 does not stop an interactive shell) and traps a SIGINT (so that you can interrupt wait). In all cases, the shell ignores the SIGQUIT signal. (See the sigaction() system call and kill for more information about signals.) -r Creates a restricted shell (the same as running Rsh). -s Reads commands from standard input. Any remaining arguments specified are passed as positional parameters to the new shell. Shell output is written to standard error, except for the output of built-in commands (see Built-In Commands). The remaining flags and arguments are discussed in the description of the built-in set command (see Built-In Commands).

NOTES

1. If a command is executed, and a command with the same name is installed in a directory in the search path before the directory where the original command was found, the shell executes the original command. Use the hash command to correct this situation. 2. When the shell encounters the >> characters, it does not open the file in append mode; instead, the shell opens the file for writing and seeks to the end. 3. Failure (nonzero exit status) of a special command preceding a || symbol prevents the list following || from executing. 4. XPG4 and SVR4 compliance To make your shell environment XPG4 compliant, you must set the value of the environment to "xpg4", by typing: BIN_SH=xpg4; export BIN_SH When you do that, the Bourne shell automatically invokes the XPG4 compliant shell, which is currently the Korn shell. The syntax for the C shell is: setenv BIN_SH xpg4 If you do not set or unset BIN_SH, the normal Bourne shell runs. To unset BIN_SH, type: unset BIN_SH The syntax for the C shell is: unsetenv BIN_SH xpg4 To make your shell environment SVR4 compliant, you must set the value of the environment to "svr4", by typing: BIN_SH=svr4; export BIN_SH When you do that, the Bourne shell automatically invokes the SVR4 compliant shell. The syntax for the C shell is: setenv BIN_SH svr4 The SVR4 version of the Bourne shell must have been installed by the system administrator or you get an error message. If you do not set or unset BIN_SH, the normal Bourne shell runs. To unset BIN_SH, type: unset BIN_SH The syntax for the C shell is: unsetenv BIN_SH svr4

RETURN VALUES

For information about exit values, see the following sections: The Shell Commands, Predefined Special Variables, Built-In Commands, and FLAGS.

FILES

$HOME/.profile User profile. /etc/passwd Contains user information.

RELATED INFORMATION

Commands: acctcms(8), acctcom(8), cd(1), csh(1), echo(1), env(1)/printenv(1), ksh(1), login(1), mail(1)/binmail(1), mailx(1)/Mail(1), pwd(1), sh(1), sh(1p), test(1) Functions: fcntl(2), exec(2), fork(2), pipe(2), sigaction(2), stat(2), umask(2) Routines: ulimit(3) Files: null(7) Miscellaneous: loader(5)