发信人: jerk (徐子陵), 信区: Unix
标  题: Unix Unleased -13
发信站: 饮水思源站 (Fri Nov 20 20:12:41 1998) , 站内信件

    
    13 — C Shell 
                    By John Valley
            A Little History 
            Invoking C Shell 
            Shell Basics 
                Executing Commands—The Basics 
                    Command Names as Shell Input 
                    Built-In Shell Commands 
                    Executing Simple Commands 
                    Entering Multiple Commands on One Line 
                    Entering Commands Too Long for One Line 
                    Executing Commands in the Background 
                    Repetitively Executing a Command—repeat 
                    Executing Commands in a Subshell—() 
                    Executing Commands Conditionally
                Shell Statements—A Closer Look 
                Filename Substitutions (Globbing) 
                Redirecting Input and Output 
                    Input Redirection 
                    Output Redirection
                Quoting or Escaping from Special Characters 
                Working with Directories and the Directory Stack 
                    Changing Directories—cd and chdir 
                    Listing the Directory Stack—dirs 
                    Changing to a Directory Using the Directory Stack—pushd 
                    Returning to a Previous Directory Using the Directory 
                    Stack—popd
                Changing the Active Shell 
                    Invoking a New Shell—exec 
                    Exiting from the Current Shell—exit
                Invoking the System Login Procedure—login 
                    Exiting from a Login Shell—logout 
                    Preventing a Command from Terminating Execution after 
                    Logout—nohup
                Displaying and Setting the Process File Creation Mask—umask 
                Echoing Arguments to Standard Output 
                    Using the echo Command 
                    Using the glob Command
                Rescanning a Line for Substitutions—eval 
                Changing Your Group ID—newgrp 
                Timing the Execution of a Command—time
            Aliases 
                Defining, Listing, and Changing Command Aliases—alias 
                Deleting a Command Alias—unalias
            Shell Options 
            Command History 
                Displaying the Command History 
                Using History Substitutions to Execute Commands
            Variables 
                Variable Names 
                Creating Shell Variables 
                    Displaying and Setting Local Shell Variables—set 
                    Deleting Local Shell Variables—unset 
                    Displaying and Setting Global Environment Variables—setenv 
                    Deleting Global Environment Variables—unsetenv
                Obtaining Variable Values with Reference Expressions 
                Using Array Variables 
                Using Special Read-Only Variables 
                Using Predefined Variables
            Shell Programming 
                What Is a Shell Script? 
                Writing Shell Scripts—An Overview 
                A Simple Shell Script 
                Using Expressions and Operators in Shell Statements 
                    Arithmetic and Logical Operators 
                    Assignment Operators—Evaluating Expressions and Assigning 
                    the Results to Variables 
                    Operator Precedence for Arithmetic and Logical Operators 
                    Operators for Command Execution and File Testing
                Entering Comments in Shell Programs 
                Conditional Statements 
                    The if Statement 
                    The switch Statement 
                    Beginning a Case in switch—case 
                    Using the Default Case in switch—default 
                    Exiting from a switch Statement—breaksw
                Iterative Statements 
                    The while Loop 
                    The foreach Loop
                Altering the Order of Command Execution—goto 
                Specifying the Response to a Signal—onintr 
                Processing an Arbitrary Number of Parameters—shift 
                Interpreting a Script in the Current Shell—source
            Customizing Your Shell Environment 
                What to Put in Your .cshrc Initialization File 
                What to Put in Your .login Initialization File 
                What to Put in Your .logout File
            Job Control 
                Executing Jobs in the Background—& 
                Listing Active Background Jobs—jobs 
                    fg and bg—Referring to Job Numbers
                Moving Foreground Jobs into the Background—bg 
                Pausing and Resuming Background Jobs 
                Moving Background Jobs into the Foreground—fg 
                Stopping a Background Job—stop 
                Stopping the Current Shell—suspend 
                Waiting for Background Jobs to Finish—wait 
                Requesting Notification of Background Job Status Changes—notify 
                Controlling Background Process Dispatch Priority—nice 
                Signaling a Process—kill
            Using the Shell's Hash Table 
                Determining the Effectiveness of the Hash Table—hashstat 
                Rebuilding the Hash Table—rehash 
                Disabling the Use of the Hash Table—unhash
            Managing Resource Limits—limit and unlimit 
                Displaying or Setting Maximum Resource Limits—limit 
                Canceling a Previous limit Command—unlimit
            Summary

13 — C Shell 

By John Valley 

As a UNIX user, you have a choice of shells available to you. These are the 
Bourne shell, the C shell, and the Korn shell. The C shell—the subject of this 
chapter—is one of the more popular shells available in UNIX. Chronologically, it 
was developed after the Bourne shell and before the Korn shell. The C shell 
incorporates many features of the Bourne shell and adds many new ones that make 
your UNIX sessions more efficient and convenient. 

There are advantages and disadvantages to each shell. You may wish to review 
Chapter 14, "Which Shell Is Right for You?" to help you decide which one to use. 


A Little History 

The Bourne and Korn shells were created at AT&T's Bell Labs, which, not 
coincidentally, is also where UNIX originated. Bell Labs is not the only 
organization that contributed to the development of UNIX, however. The 
Department of Computer Science at the Berkeley campus, University of California, 
played a very important role. 

As you might have already read, the early versions of UNIX were made available 
only to colleges and universities under a rather restrictive licensing 
arrangement: UNIX could be used outside of AT&T only for "research purposes." At 
Berkeley, interest in UNIX was very high. The computer science labs added many 
new features to UNIX and offered their version to other universities as well. 
The Berkeley version soon became the more popular version, not only because of 
its many new features and extensions, but also because Berkeley, unlike Bell 
Labs, offered maintenance and support to other user groups. Given this fact, it 
shouldn't be surprising that by the late 1970s, the BSD version (Berkeley 
Software Distribution) was the dominant variant of UNIX in use. 

One of the additions to UNIX was a new shell, written by Bill Joy (also the 
author of the vi text editor). Joy did not pattern his shell after the Bourne 
shell; indeed, to judge by results, he apparently felt that the Bourne shell 
syntax was clumsy and nonintuitive. As a syntax model, he chose the C 
programming language. The C shell commands, especially if, while, and the other 
structured programming statements, are somewhat similar in syntax to the 
equivalent statements in C. A shell is quite a different animal from a compiler, 
however, so the C programming language served only as a model; many forms and 
structures in the C shell have nothing to do with the C programming language. 

Because the C shell is not just an extension of the Bourne shell syntax, this 
chapter will cover all aspects of C shell operation; it can therefore be read 
independently from Chapter 11, "Bourne Shell," and Chapter 12, "Korn Shell." 

Invoking C Shell 

Each time you log in to UNIX, you're placed in an interactive shell referred to 
as your login shell. If your login shell is C shell, you can tell by its 
command-line prompt: the percent sign (%). The C shell prompt differs from the 
dollar sign prompt ($) of the Bourne shell to remind you that you're using the C 
shell. You can customize your keyboard prompt when using the C shell; for more 
information see the definition of prompt in the section titled "Variables" later 
in this chapter. 

If your login shell is not C shell, and C shell is available on your system, you 
can invoke it as an interactive shell from the command line. Even when you're 
already running the C shell, there will be times when you want to launch the C 
shell again, for example to run a shell script or to temporarily change the 
shell's options. To invoke the C shell interactively, use the following command: 


$ csh



%


NOTE: The csh command is usually located in either the /bin or the /usr/bin 
directory. Because both directories are usually in your search path, you 
shouldn't have any trouble finding the csh command if your system has it. If you 
don't find it right away, you might look in the directory /usr/ucb (standard 
home for BSD components in a UNIX System V system), or in /usr/local/bin, home 
for programs your shop has acquired that weren't provided with the original 
system. Remember, though, that the C shell was for many years available only to 
those shops using the BSD variant of UNIX; unlike the Bourne shell, there is no 
guarantee that you will have the csh command on your system. 



The csh command also supports a number of options and arguments (described later 
in this chapter in the section titled "Shell Options"), but most of them are not 
relevant to running an interactive shell. 

Whenever csh is invoked, whether as the login shell or as a subshell, it loads 
and executes a profile script named .cshrc. If it is a login shell, the C shell 
will also execute a profile script on startup named .login, and another on exit 
named .logout. Note that the .login script is executed after .cshrc, not before. 
For additional information about C shell profile scripts, see the section titled 
"Customizing Your Shell Environment" later in this chapter. 

Most versions of the C shell import environment variables such as PATH into 
local array variables at startup. The C shell does not refer to the public 
environment variables (including PATH) for its own operation. This means that 
usually you'll want to maintain the path variable for directory searches, not 
PATH. Some versions of the C shell do not properly import environment variables, 
with confusing results. If it appears that you have no search path set, but the 
PATH variable is set and accurate (as shown by echo $PATH), check that the 
variable path has a matching value. If not, you'll need to import critical 
environment variables into local variables yourself. 



NOTE: If you are familiar with Bourne shell, you won't notice much difference 
working with the C shell unless you use advanced shell features such as 
variables, command replacement, and so on. 

Important differences do exist, however. Among these are the set of punctuation 
characters having special meaning to the shell (often called metacharacters). 
The C shell is sensitive to all the special characters of the Bourne shell, as 
well as the tilde (~), the commercial at sign (@), and the exclamation point 
(!). Don't forget to quote or escape these characters when writing commands 
unless you intend their special shell meaning. (See the section "Quoting and 
Escaping from Special Characters" for a discussion of the details.) 



Shell Basics 

When you enter commands at the shell prompt, you are providing input to the 
shell. The shell sees a line of input as a string of characters terminated with 
a newline character that is usually the result of pressing return on your 
keyboard. That input can be anything from a single, simple command to multiple 
commands joined with command operators. Each command line that you enter is 
actually a shell statement. In addition to providing input to the shell manually 
by entering shell statements on the command line, you can also provide input to 
the shell by putting shell statements into a file and executing the file. 

The next section covers the basics of interacting with the shell by entering 
shell statements on the command line. (Of course, anything that you can enter on 
the command line can also be put into a file for later, "canned" execution. Such 
files are called shell scripts.) The section following is titled "Shell 
Statements—A Closer Look," which provides a more detailed, technical look at 
components of shell statements. If you plan to write shell scripts, you'll 
definitely want to read this section. 

When you finish this section, you will feel like you know a lot about the shell, 
but this is just the beginning. In addition to its basic service of providing a 
means to instruct the computer, the shell also provides a number of tools you 
can use to expedite your work flow. These tools, or features of the shell, are 
described in subsequent sections of this chapter. 

Executing Commands—The Basics 

C shell accepts several types of commands as input: UNIX commands, built-in 
shell commands, user-written commands, and command aliases. This section 
describes the different types of commands you can execute and the various ways 
you can execute commands. 

Command Names as Shell Input 

As you know, you execute a command by entering the command's name. The C shell 
supports any of the following as command names: 

    Built-in C shell command. The shell provides a number of commands 
    implemented within the shell program itself: invoking a built-in command 
    therefore executes very quickly because no program files need to be loaded. 
    A built-in command is always invoked by a simple name, never by a pathname. 
    
    Because the shell first checks a command name for built-in commands before 
    searching for a file of the same name, you cannot redefine a built-in 
    command with a shell script. The next section, "Built-In Shell Commands," 
    briefly describes each one; detailed descriptions with examples of how to 
    use these commands are presented in the task-oriented sections of this 
    chapter. 
    
    
    Filename. You can specify the filename or a relative or absolute pathname of 
    a file as a command. The file must be marked executable and must be either a 
    binary load file or a shell script in the C shell language. The C shell 
    cannot process shell scripts written for the Bourne or Korn shells. (See the 
    section titled "Shell Programming" later in this chapter for notes about 
    using shell scripts with the C shell.) 
    
    All UNIX commands are provided as executable files in the /bin or /usr/bin 
    directories. You invoke a UNIX command by entering its filename or full 
    pathname. 
    
    Examples of invoking an executable program file include the following: 
    
    % cat big.script 
    % /usr/bin/cat big.script 
    % /usr/ucb/cc myprog.c 
    % ../paylist paymast 
    
    
    Command alias. A command alias is a name you define using the alias shell 
    built-in command. 
    
    An alias can have the same name as a shell built-in command or an executable 
    file. You can always invoke an executable file having the same name as an 
    alias by using the file's full pathname. An alias having the same name as a 
    built-in command, however, effectively hides the built-in command. Aliases 
    are described in detail in the section titled "Aliases" later in this 
    chapter. 
    
    
Built-In Shell Commands 

C shell provides a number of commands implemented within the shell program 
itself. Built-in commands execute very quickly because no external program file 
needs to be loaded. Table 13.1 lists the commands alphabetically along with a 
brief description of each one. The remainder of this chapter groups these 
commands into subsections dedicated to particular tasks you'll perform in the 
shell and describes how to use each command. 

    Table 13.1. Built-in commands for C shell. 
    
Command




            Description




            
            aliasDefine or list a command alias
            bgBackground execution
            breakBreaking out of a loop
            breakswExit from a switch statement
            caseBegin a case in switch
            cdChange directory
            chdirChange directory
            continueBegin the next loop iteration immediately
            defaultLabel for the default case in switch
            dirsList the directory stack
            echoEcho arguments to standard output
            evalRescan a line for substitutions
            execInvoke a new shell
            exitExit from the current shell
            fgSwitch a job to foreground execution
            foreachLooping control statement
            globEcho arguments to standard output
            gotoAlter the order of command execution
            hashstatPrint hash table statistics
            historyList command history
            ifConditional execution
            jobsList active jobs
            killSignal a process
            limitRespecify maximum resource limits
            loginInvoke the system login procedure
            logoutExit from a login shell
            newgrpChange your group ID
            niceControl background process dispatch priority
            nohupPrevent termination on logout
            notifyRequest notification of background job status changes
            onintrProcess interrupt within a shell script
            popdReturn to a previous directory
            pushdChange directory with pushdown stack
            rehashRehash the directory search path
            repeatRepetitively execute a command
            setDisplay or change a variable
            setenvSet environment variable
            shiftShift parameters
            sourceInterpret a script in the current shell
            stopStop a background job
            suspendStop the current shell
            switchConditional execution
            timeTime a command
            umaskDisplay or set the process file creation mask
            unaliasDelete a command alias
            unhashDisable use of the hash table
            unlimitCancel a previous limit command
            unsetDelete shell variables
            unsetenvDelete environment variables
            waitWait for background jobs to finish
            whileLooping control
            %jobForeground execution
            @Expression evaluation
    
Executing Simple Commands 

The most common form of input to the shell is the simple command, where a 
command name is followed by any number of arguments. For example, in the 
following command line 

% chdir dirname
chdir is the command and dirname is the argument. It is the responsibility of 
the command, not the shell, to interpret the arguments. Many commands, but 
certainly not all, take the form 

% command -options filenames
Although the shell does not interpret the arguments of the command, the shell 
does make some interpretation of the input line before passing the arguments to 
the command. Special characters entered on a command line cause the shell to 
redirect input and output, start a different command, search the directories for 
filename patterns, substitute variable data, and substitute the output of other 
commands. 

Entering Multiple Commands on One Line 

Ordinarily, the shell interprets the first word of command input as the command 
name and the rest of the input as arguments to that command. The semicolon (;) 
directs the shell to interpret the word following the symbol as a new command, 
with the rest of the input as arguments to the new command. For example, the 
command line 

% who -H; df -v; ps -e
is the equivalent of 

% who -H



% df -v



% ps -e
except that in the second case the results of each command would appear between 
the command input lines. 

When the semicolon is used to separate commands on a line, the commands are 
executed in sequence. The shell waits until one command is complete before 
executing the next. You can also execute commands simultaneously (see the 
section titled "Executing Commands in the Background") or execute them 
conditionally, which means that the shell executes the next command only if the 
first command succeeds or fails (see the section titled "Executing Commands 
Conditionally"). 

Entering Commands Too Long for One Line 

Sometimes command lines get quite lengthy. On some terminals, when you reach the 
edge of the display screen the input autowraps to the next line, but depending 
on terminal settings, some do not. It would be nice if you could type part of a 
command on one line and enter the remainder of the command on a second line. 
This can be accomplished by escaping the newline character. 

Remember that the shell sees a line of input as a statement terminated with a 
newline character. But the newline character is also considered to be a white 
space character. If you end a line with a backslash (\), the next character—the 
newline character—will be treated literally, meaning that the shell will not 
interpret the newline character as the end of the line of input. 

% echo Now is the time for all good men     \_



to come to the aid of the party.



Now is the time for all good men to come to the aid of the party.
Executing Commands in the Background 

Normally when you execute commands, they are executed in the foreground. This 
means that the command has the system's undivided attention, and you can't do 
anything else until the command finishes executing. For commands that take a 
long time to execute, however, this can be a problem. To free your system 
without waiting for the command to finish, you can execute the command in the 
background by putting an ampersand (&) at the end of the command: 

% who -H &



[1] +  Running    who -H &



%
You also can run multiple commands in the background simultaneously: 

% who -H & df -v & ps -e &
A command executing in the background is referred to as a job, and each job is 
assigned a job number—the bracketed number in the preceding example. C shell 
provides you with several commands for managing background jobs; see the section 
later in this chapter titled "Job Control." 

Repetitively Executing a Command—repeat 

You can use the repeat command to execute some other command a specified number 
of times. While the repeat command doesn't see frequent use, it can on occasion 
be quite handy. For example, if you had stored some text in a model file, and 
wanted to make five copies of it, you could do so easily with the command 

repeat 5 cat model.txt new.txt
Or, if you were writing a shell script to print a document, you might use the 
command 

repeat 5 echo *******************************
to mark its first page clearly as the start of the document. 

The syntax of the repeat command is as follows: 

repeat count command
For count, specify a decimal integer number. A count of zero is valid and 
suppresses execution of the command. 

For command, specify a simple command that is subject to the same restrictions 
as the first format of the if statement. The command is scanned for variable, 
command, and history substitutions, filename patterns, and quoting. It cannot be 
a compound command, a pipeline, a statement group (using {}), or a parenthesized 
command list. 

Any I/O redirections are performed only once regardless of the value of count. 
For example, repeat 10 echo Hello >hello.list would result in ten lines of Hello 
in a file named hello.list. 

Executing Commands in a Subshell—() 

A command (or a list of commands separated with semicolons) enclosed in 
parentheses groups the command or commands for execution in a subshell. A 
subshell is a secondary invocation of the shell, so any change to shell 
variables, the current directory, or other such process information lasts only 
while executing the commands in the group. This is a handy way, for example, to 
switch to another directory, execute a command or two, and then switch back 
without having to restore your current directory: 

% (cd /home/bill; cp *.txt /home/john)
Without the parentheses, you would have to write: 

% cd /home/bill



% cp *.txt /home/john



% cd /home/john
The syntax for grouping commands is: 

( commands )
Enclosing a list of commands in parentheses is a way to override the default 
precedence rules for the &&, ||, and | operators, at the expense of invoking a 
subshell and losing any environmental effects of the commands' execution. For 
example, (grep || echo) | pr will pipe the output of the grep command, and 
possibly that of echo if grep sets a nonzero exit code, to the pr command. 

I/O redirections can be appended to the subshell just as for a simple command; 
the redirections are in effect for all of the commands within the subshell. For 
example, (cat; echo; date) > out will write the output of the cat, echo, and 
date commands to a file named out without any breaks. If you look at the file 
afterward, first you'll see the lines written by cat, followed by the lines 
written by echo, and finally the lines written by date. Similarly, input 
redirections apply to all commands in the subshell, so that each command in turn 
reads lines from the redirected file, starting with the line following those 
read by any previously executed commands in the subshell. 

Executing Commands Conditionally 

Compound commands are actually two or more commands combined together so that 
the shell executes all of them before prompting (or, in the case of shell 
scripts, reading) more input. 

Compound commands are not often needed for work at the keyboard, and you'll 
rarely feel the lack if you don't understand or don't use compound commands. 
However, compound commands form a very useful extension to the shell's syntax, 
especially in shell scripts. Some compound command formats, such as & 
(background job) and | (the pipe operator) are essential to effective work with 
UNIX. 

Conditional Execution on Success—&& (And) 

The double ampersand operator (read and) is used to join two commands: command1 
&& command2. It causes the shell to execute command2 only if command1 is 
successful (has a zero exit code). 

For command1 or command2, you can write a simple command or a compound command. 
The && operator has higher precedence than || but lower precedence than |. For 
example, 

grep '#include' *.c | pr && echo OK
will echo OK only if the pipeline grep | pr sets a zero exit code. (For 
pipelines, the exit code is the exit code of the last command in the pipeline.) 

The compound command cp file1.c file1.bak && rm file1.c shows the possible 
benefit of using &&: The rm command will delete file1.c only if it is first 
successfully copied to file1.bak. 

Conditional Execution on Failure —|| (Or) 

The or operator is used to join two commands: command1 || command2. It causes 
the shell to execute command2 only if command1 failed (set a nonzero exit code). 


For command1 or command2, you can write a simple command or a compound command. 
The || operator has lower precedence than both the && and | operators. For 
example, in the following command 

grep '#include' *.c || echo No files | pr
either grep succeeds, or else the words No files are piped to the pr command. 
That is, the pipe is between the echo and pr commands, not between grep (or grep 
|| echo) and pr. 

Use the || operator to provide an alternative action. For example, in the 
following case, if the mkdir command fails, the exit command prevents further 
execution of the shell script: 

mkdir $tmpfile || exit
Shell Statements—A Closer Look 

A command is either a basic command, or a basic command embellished with one or 
more I/O redirections. 

A basic command is a series of words, each subject to replacements, which when 
fully resolved specifies an action to be executed and provides zero or more 
options and arguments to modify or control the action taken. The first word of a 
basic command, sometimes called the command name, must specify the required 
action. 

In plainer terms, a statement is the smallest executable unit. When the shell is 
operating in interactive mode, it displays its prompt when it requires a 
statement. You must continue to enter shell statement components, using multiple 
lines if necessary, until you have completed a full statement. If the statement 
is not completed on one line, the shell will continue to prompt you, without 
executing the line or lines you have entered, until it has received a full 
statement. 

Shell statements are formed from a number of tokens. A token is a basic 
syntactic element and can be any of the following: 

    Comments. A comment begins with any word having a pound sign (#) as its 
    first character, and extends to the end of the line. This interpretation can 
    be avoided by enclosing the pound sign (or the entire word) in quotes. (See 
    "Quoting and Escaping Special Characters" later in this chapter.) 
    
    
    White space. White space consists of blanks and tabs, and sometimes the 
    newline character. White space is used to separate other tokens which, if 
    run together, would lose their separate identity. Units of text separated by 
    white space are generically called words. 
    
    
    Statement delimiters. Statement delimiters include the semicolon (;) and the 
    newline character (generated when you press return). You can use the 
    semicolon to run commands together on the same line. The shell treats the 
    commands as if they had been entered on separate lines. 
    
    Normally every command or shell statement ends at the end of the line. The 
    return (or Enter) key you press to end the line generates a character 
    distinct from printable characters, blanks and tabs, which the shell sees as 
    a newline character. Some statements require more than one line of input, 
    such as the if and while commands. The syntax description for these commands 
    shows how they should be split over lines; the line boundaries must be 
    observed, and you must end each line at the indicated place or else you will 
    get a syntax error. 
    
    
    Operators. An operator is a special character, or a combination of special 
    characters, to which the shell attaches special syntactic significance. 
    Operators shown as a combination of special characters must be written 
    without white space between them, otherwise they will be seen as two single 
    operators instead of the two-character operator. 
    
    Punctuation characters having special significance to the shell must be 
    enclosed in quotes to avoid their special interpretation. For example, the 
    command grep '#' *.c uses quotes to hide the pound sign from the shell so 
    that the pound sign can be passed to grep as an argument. See the section 
    later in this chapter titled "Quoting and Escaping from Special Characters" 
    for details about using quotes. 
    
    
    Words. A word is any consecutive sequence of characters occurring between 
    white space, statement delimiters, or operators. A word can be a single 
    group of ordinary characters, a quoted string, a variable reference, a 
    command substitution, a history substitution, or a filename pattern; it can 
    also be any combination of these elements. The final form of the word is the 
    result of all substitutions and replacements, together with all ordinary 
    characters, run together to form a single string. The string is then used as 
    the command name or command argument during command execution. 
    
    
Filename Substitutions (Globbing) 

Filename generation using patterns is an important facility of the Bourne shell. 
The C shell supports the filename patterns of the Bourne shell and adds the use 
of {} (braces) to allow greater flexibility. 

Several shell commands and contexts allow the use of pattern-matching strings, 
such as the case statement of switch and the =~ and !~ expression operators. In 
these cases, pattern strings are formed using the same rules as for filename 
generation, except that the patterns are matched to another string. 

When any of the pattern expressions described below are used as arguments of a 
command, the entire pattern string is replaced with the filenames or pathnames 
that match the pattern. By default, the shell searches the current directory for 
matching filenames, but if the pattern string contains slashes (/), it searches 
the specified directory or directories instead. Note that several directories 
can be searched for matching files in a single pattern string: a pattern of the 
form dir/*/*.c will search all the directories contained in dir for files ending 
with .c. 

*The asterisk matches any string of characters, including a null 
            string. Used by itself, it matches all filenames. Used at the 
            beginning of a pattern string, it means that leading prefixes of the 
            filename pattern are ignored: *.c matches any filename ending with 
            .c. Used at the end of a pattern string, it means that trailing 
            suffixes of the filename pattern are ignored: s.* will match s.main, 
            s.prog.c, and any filename beginning with s.. Used in the middle of 
            a pattern, it means that matching filenames must begin and end as 
            shown but can contain any character sequences in the middle: pay*.c 
            matches filenames beginning with pay and ending with .c, such as 
            payroll.c, paymast.c, and paycheck.c.
            ?The question mark matches any one character. For example, ? as a 
            complete word will match all filenames one character long in the 
            current directory. The pattern pay?.c will match pay1.c and pay2.c 
            but not payroll.c. Multiple question marks can be used to indicate a 
            specific number of don't-care positions in the filename: pay??.c 
            will match filenames beginning with pay and containing any two 
            characters before .c, such as pay01.c and paybb.c, but will not 
            match payroll.c.
            []The square brackets enclose a list of characters. Matching 
            filenames contain one of the indicated characters in the 
            corresponding position of the filename. For example, [abc]* will 
            match any filename beginning with the letter a, b, or c. Because of 
            the asterisk, the first character can be followed by any sequence of 
            characters.
            
            Use a hyphen (-) to indicate a range of characters. For example, 
            pay[1-3].c will match filenames pay1.c, pay2.c, and pay3.c, but not 
            pay4.c or pay11.c. Multiple ranges can be used in a single bracketed 
            list. For example, [A-Za-z0-9]* will match any filename beginning 
            with a letter or a digit. To match a hyphen, list the hyphen at the 
            beginning or end of the character list: [-abc] or [abc-] will match 
            an a, b, c, or hyphen.
            
            Use a circumflex (^) after [ to negate the range of characters. The 
            pattern [^a-zA-Z0-9]* will match all filenames that do not begin 
            with a letter or digit—that is, filenames beginning with a 
            punctuation character such as .c or #myfile.txt.
            {}Braces enclose a list of patterns separated by commas. The brace 
            expression matches filenames having any one of the listed patterns 
            in the corresponding position of the name. For example, the pattern 
            /usr/home/{kookla,fran,ollie}/.profile expands to the path list 
            /usr/home/kookla/.profile /usr/home/fran/.profile 
            /usr/home/ollie/.profile. Unlike *, ?, and [], brace-enclosed lists 
            are not matched against existing filenames; they are simply expanded 
            into filenames regardless of whether the corresponding files exist. 
            Brace-enclosed lists can be nested, for example 
            /usr/{bin,lib,home/{john,bill}} refers to any of the directories 
            /usr/bin, /usr/lib, /usr/home/john, and /usr/home/bill.
    
The tilde (~) can be used at the beginning of a word to invoke directory 
substitution. The tilde forms are as follows: 

~Substituted with the full pathname of your home directory. Also 
            used in the form ~/path to refer to a file or directory under your 
            home directory.
            ~nameSubstituted with the full pathname of user name's home 
            directory. For example, ~ken/bin refers to /usr/ken/bin if the home 
            directory for user ken is /usr/ken. The password file /etc/passwd is 
            searched for name to determine the directory pathname; if name is 
            not found, the shell generates an error message and stops.
    
If the tilde does not appear by itself as a word, and is not followed by a 
letter or by a slash, or appears in any position other than the first, it is not 
replaced. Thus, /usr/marta/~file.c is a reference to the file ~file.c in the 
directory /usr/marta. 

It is important to realize that filename generation using pattern strings causes 
a replacement of one word with many. A filename pattern must be a single word. 
The ordinary characters and pattern-matching characters in the word describe a 
rule for choosing filenames from the current or specified directory. The word is 
replaced with each filename or pathname found that matches the pattern. Consider 
the following examples: 

% echo Files: *.txt



Files: ch1.txt ch2.txt chlast.txt



% set files=(*.txt)



% echo Found $#files files



Found 3 files



% echo $files[2]



ch2.txt



mkdir $tmpfile || exit
Redirecting Input and Output 

C shell provides several commands for redirecting the input and output of 
commands. You might already be familiar with the input (<) or output (>) 
redirection characters from earlier chapters. C shell provides you with these 
and more. 

An I/O redirection is an instruction to the shell you append to a command. It 
causes one of the standard file descriptors to be assigned to a specific file. 
You might have previously encountered standard files in the discussion of the 
Bourne shell (Chapter 11). The UNIX operating system defines three standard file 
descriptors: standard input, standard output, and standard error. (These names 
are sometimes abbreviated to stdin, stdout, and stderr.) 



NOTE: The UNIX operating system actually provides at least twenty-five file 
descriptors for use by a command. It is only by convention that the first three 
are set aside for reading input, writing output, and printing error messages. 
Unless you instruct otherwise, the shell always opens these three file 
descriptors before executing a command, and assigns them all to your terminal. 



A file descriptor is not the file itself. Rather, it is a channel, much like the 
phone jack on the back of your stereo: you can connect it to any audio source 
you like. Similarly, a file descriptor such as standard input must be connected 
to a file—your terminal by default, or the disk file or readable device of your 
choice. 

You can change the location where a command reads data, writes output, and 
prints error messages, using one or more of the I/O redirection operators. The 
operators are shown in Table 13.2. 

    Table 13.2. I/O redirection operators. 
    
Format




            Effect




            
            Input Redirection
            < filenameUse the contents of filename as input to a command.
            << wordProvide shell input lines as command input. Lines of the 
            shell input which follow the line containing this redirection 
            operator are read and saved by the shell in a temporary file. 
            Reading stops when the shell finds a line beginning with word. The 
            saved lines then become the input to the command. Of course, the 
            lines read and saved are effectively deleted from the shell input, 
            and will not be executed as commands; they are effectively "eaten" 
            by the << operator. Shell execution continues with the line 
            following the line beginning with word. If you use the << operator 
            on a command you type at the terminal, be careful: lines you type 
            afterward will be gobbled up by the shell—not executed—until you 
            enter a line begining with whatever you specified as word. The << 
            operator is most often used in shell scripts.
            Output Redirection
            > filenameWrite command output to filename
            >! filenameWrite command output to filename, and ignore the 
            noclobber option. The noclobber option is fully explained in the 
            section "Using Predefined Variables" later in this chapter. Briefly 
            it causes the shell to disallow the > filename redirection when 
            filename already exists; noclobber is therefore a safety you can use 
            to prevent your accidentally destroying an existing file. Of course, 
            sometimes you want to redirect output to a file even though it 
            already exists. In such a case, you must use the >! operator to tell 
            the shell you really want to proceed with the redirection. If you 
            don't set the noclobber option, then you won't need to use the >! 
            operator either.
            >& filenameOpen filename and write both the command output and error 
            messages to it
            >&! filenameOpen filename and write both the command output and 
            error messages to it, and ignore the noclobber option
            >> filenameOpen filename and write command output at the end of the 
            file (append mode)
            >>! filenameOpen filename and write command output at the end of the 
            file (append mode), and ignore the noclobber option
            >>& filenameOpen filename and write command output and error 
            messages at the end of the file (append mode)
            >>&! filenameOpen filename and write command output and error 
            messages at the end of the file (append mode), and ignore the 
            noclobber option
    
In Table 13.2, filename represents any ordinary filename or pathname, or any 
filename or pathname resulting after variable substitution, command 
substitution, or filename generation. 

I/O redirection operators are appended to a command; for example, date >curdate 
will write the current date to the file curdate instead of to your terminal. You 
can also use more than one redirection per command: simply list them one after 
another at the end of the command. The order doesn't matter: for example, both 
cat <infile >outfile and cat >outfile <bigfile will have the same effect. 

Input Redirection 

Some commands make no special use of the standard input file, such as the date 
and the ls system commands; others require an input file to function properly, 
such as the cat and awk commands. You can use the < redirection operator in the 
form command < filename to designate a file as the source of input for commands 
like cat and awk; if you do not, these commands will read data from your 
keyboard—sometimes useful, but usually not. If you provide an input redirection, 
but the command does not read data (such as ls), the I/O redirection is still 
performed by the shell, it is just ignored by the command. 

It is an error to redirect standard input to a file that doesn't exist. 

The redirection << word is a special form of the input redirection operator. 
Rather than taking input from a file, input to the command comes from the 
current shell input stream—your keyboard, if you append << to a command you type 
in, or your shell script if you use << on a command in a shell script. 

For word, you choose an arbitrary string to delimit the lines of input. Then 
write the lines to be provided to the command as input immediately following the 
command line, and follow the last line with a line beginning with word. The 
shell reads the lines ahead, stores them in a temporary file, and sets up the 
temporary file as standard input for the command. 

This form of input redirection is called a here document, because it is located 
here, in line with your shell commands. It is useful when you want to provide 
predefined data to a command, and it saves you from having to create a file to 
hold the data. 

Unlike the filename part of other I/O redirection operators, word for the here 
document is not scanned for variable references, command substitutions, or 
filename patterns; it is used as is. Also, the following shell input lines are 
checked for the presence of word as the first word of the line before any 
substitutions or replacements are performed on the line. 

Normally, lines of the here document are checked for variable references and 
command replacements; this allows you to encode variable information in the here 
document. If you quote any part of word, however, the lines are read and passed 
to the command without modification. For example, the redirection << STOP reads 
lines up to STOP, and performs substitutions on the lines it reads; the 
redirection << "STOP" reads lines up to the line beginning with STOP, and passes 
the lines directly to the command, as is, without substitutions or replacements 
of any kind. 

The line beginning with word is discarded, and neither passed to the command in 
the here document, nor executed by the shell. 

The following example shows the use of a here document to print a customized 
message: 

pr << HERE | lp



Hello, $user.



Your print job,



'lpstat'



has been scheduled for output at a later time.



Please contact Joe if you have any questions.



HERE
The line containing the word HERE will not appear in the output message; it is 
simply a mark to let the shell know where the redirected lines end. 

Output Redirection 

Output redirections have the general form > and >>. The first operator creates a 
new file of the specified name. The file is opened before command execution 
begins, so even if the command fails, or cannot be found, or if the shell finds 
an error on the command line and stops, the output file will still be created. 

If you've set the noclobber option (with set noclobber), then the shell will 
refuse to create the named output file if it already exists; doing so would 
destroy its current contents. If you want to perform the output redirection even 
if the file filename already exists, use the redirection operator >! instead; it 
overrides the noclobber option. 

The >> command arranges for command output to be added to the end of the named 
file. For this redirection operator, the noclobber option requires that the 
named file already exist. If you use the alternate form >>!, or if you use >> 
and the noclobber option is not set, the shell will create the named file if 
necessary. 

The >& and >>& operators redirect both the standard output and standard error 
files to filename. The Bourne shell allows you to redirect the standard output 
and standard error files separately; the C shell does not. Actually, this is not 
much of a limitation in real life. 

If you have the noclobber option set, you'll need to use >&! instead of >& to 
proceed even if the named file exists, or >>&! to proceed even if the named file 
doesn't exist. 



NOTE: For purposes of understanding shell syntax, it might be noted that 
appending an I/O redirection to a simple command yields a simple command. Except 
where specifically prohibited, a command with redirections appended can be used 
wherever a simple command is allowed, such as on the single-line if statement. 



Quoting or Escaping from Special Characters 

As you've seen from previous sections, certain characters have special meaning 
for the shell. That is, when the shell encounters a special character, it will 
perform the action that the special character calls for. The following 
punctuation characters available on the standard keyboard are special to the 
shell and disrupt the scanning of ordinary words: 

~ ' ! @ # $ % ^ & * ( ) \ | { } [ ] ; ' " < > ?
In some contexts, particularly within the switch statement, the : (colon) is 
also a special character. The colon is recognized as a special character only 
when expected, in a case or default statement, and as a statement label. It does 
not need to be quoted except to avoid these specific interpretations. 

To use one of these characters as a part of a word without its special 
significance, you can escape the character by placing a backslash (\) 
immediately in front of the character. Note that a backslash intended as an 
ordinary character must be written as two backslashes in succession: \\. To 
escape a two-character operator such as >>, you must insert a backslash in front 
of each character: \>\>. 

Alternatively, you can enclose the special character or any portion of the word 
containing the character in quotes. The shell recognizes three kinds of quotes: 
the apostrophe ('), the quote ("), and the backquote (`). 

Use two apostrophes (also called single quotes) to enclose a character sequence 
and avoid all interpretation by the shell. I often call a string enclosed in 
apostrophes a hard-quoted string, because the shell performs absolutely no 
substitution, replacement, or special interpretation of anything appearing 
between the apostrophes. Even the backslash character is treated as an ordinary 
character, so there are no escapes within an apostrophe-enclosed string, and you 
cannot embed an apostrophe in such a string. That is, the string 'who's there' 
will cause a shell error: the shell will see this as who concatenated with an s, 
followed by a white space delimiter, followed by a word beginning with there, 
and then the starting apostrophe of another string. The third apostrophe starts 
a quoted string that the shell will follow over as many lines as necessary to 
find an ending apostrophe, probably eating up shell lines you intended as 
commands, and eventually yielding a shell syntax error or an erroneous command 
execution. 

One of the uses of quoted strings is to specify a single word containing blanks, 
tabs, and newline characters. For example, the following shows the use of a 
single echo command to print two lines of output: 

% echo -n 'Hello.



Please enter your name: '



Hello.



Please enter your name:
The double apostrophe or quote (") also provides a special bracket for character 
strings. Like the apostrophe, the quote hides most special characters from the 
shell's observation. Quoted strings, however, are subject to two kinds of scan 
and replacement: variable references and command substitutions. 

Any of the reference forms for shell variables ($1, $name, ${name}, 
$name[index], $*, and others) are recognized inside quoted strings and are 
replaced with the corresponding string value. The replacement occurs inside the 
quoted string, leaving its unity as a single word intact (even if the 
substituted value includes blanks, tabs, or newline characters). 

Command substitution occurs for strings enclosed in backquotes ('). The entire 
string enclosed between matching backquotes is extracted and executed by the 
shell as if it were an independent command. The command can be two or more 
commands separated with semicolons, or a pipeline, or any form of compound 
statement. Any data written to standard output by the command is captured by the 
shell and becomes the string value of the backquoted command. The string value 
is parsed into words, and the series of words replaces the entire backquoted 
string. 

All forms of shell substitution will occur inside backquoted command strings, 
including variable replacement, nested command executions, history 
substitutions, and filename patterns. Nested command strings will work, but the 
backquotes introducing them must be escaped with \ to hide them from the shell's 
first scan of the backquoted string. 

A backquoted command string (or any number of them) can appear inside a quoted 
string and will have its normal effect; this is the second form of substitution 
performed on "-quoted strings. A quoted command substitution 
("xxx`commands`xxx") generates new words only at the end of each line, except at 
the end of the last line. If the executed command prints only one line of text, 
the text replaces the backquoted expression without introducing any word breaks. 


Both quoting forms '...' and "..." suppress filename generation. For example, 
note the difference in the following echo commands: 

% echo *.c



main.c io.c parse.c math.c



% echo "*.c"



*.c
Apostrophes and quotes can appear inside a double-quoted string. The double 
quote must be escaped with a backslash to prevent premature termination of the 
quoted string (for example "He said, \"John!\""). The apostrophe has no special 
significance when appearing inside a double-quoted string and does not need to 
be backslashed. The following example shows the use of quotes inside quoted 
strings: 

% echo "He said, \"John!\""



He said, "John!"



% echo "Filename: '$1'"



Filename: '/usr/bin/ls'
A backslash appearing inside an apostrophe-quoted string is retained and appears 
in the string's value, because no substitutions occur inside an 
apostrophe-quoted string. Inside a double-quoted string or a command 
substitution using ', or in a normal unquoted word, a backslash has the effect 
of suppressing shell interpretation of the character that follows it; the 
backslash is then removed from the string. The following examples show the 
effect of a backslash in all these contexts: 

% echo "Double \" quote"



Double " quote



% echo Double \" quote



Double " quote



% echo 'Single \' quote



Single \ quote



% echo Single \' quote



Single ' quote
Working with Directories and the Directory Stack 

C shell provides you with several built-in commands for working with 
directories. The cd, chdir, pushd, and popd commands all change the current 
directory in one way or another. 

The pushd and popd commands provide a pushdown stack mechanism for changing 
directories, and the dirs command displays the contents of the stack. If you 
switch to another directory using pushd instead of cd, the pathname of your 
previous directory is "saved" in the directory stack. A subsequent popd will 
then return you to the previous directory. Be aware that the cd command does not 
maintain the directory stack; you cannot use popd to return to a directory that 
you left using cd. 

Changing Directories—cd and chdir 

In C shell, you can choose from two commands for changing your current working 
directory: cd and chdir. The chdir command is equivalent to cd in every way. The 
syntax for these commands is as follows: 

cd [ name ]



chdir [ name ]
If you omit the name argument, the command attempts to change to the directory 
whose pathname is given by the value of the C shell variable home; see the 
section later in this chapter titled "Using Predefined Variables" for more about 
home. 

If you specify a name, the cd or chdir command uses a search hierarchy to 
attempt to locate the referenced directory, as follows: 

    If name begins with /, ./, or ../, the command attempts to switch to the 
    named directory; failure terminates the command immediately. In other words, 
    if you use a relative or absolute pathname, the specified directory must 
    exist and must be accessible to you, otherwise the command fails. 
    
    
    The command searches your current directory. A partial pathname, of the form 
    name1/name2/.../namen implies searching your current directory for the 
    entire subtree. 
    
    
    If the directory path cannot be found in your current directory, the command 
    checks to see if the variable cdpath exists and has a value. If it does, 
    then each of the directories named in cdpath is checked to see if it 
    contains name. If successful, the command changes to the name in that 
    directory and prints the full pathname of the new current directory. 
    
    
    If no variable cdpath exists, or if name cannot be found in any of the 
    directories listed in cdpath, the command checks to see if name is a 
    variable name and has a value beginning with /. If so, the command changes 
    to that directory. 
    
    
    If name still cannot be found, the command fails. 
    
    
For more information about the cdpath variable, see the section titled "Using 
Predefined Variables" later in this chapter. 

The cd and chdir commands as implemented by the C shell provide a great deal of 
flexibility in generating shortcuts for directory names. There is nothing more 
painful than having to repeatedly type long directory names on the cd command. 
The purpose of the cd command's search hierarchy is to provide some mechanisms 
you can use for shortening a reference to a directory name. The cdpath variable 
is your principal tool: if you set it to a list of directories you often 
reference, you can switch to one of those directories just by giving the base 
directory name. If cdpath is not sufficiently flexible to suit your needs, you 
can define a shell variable as an alias for a directory's full pathname, then cd 
varname will switch you to that directory for the price of a few keystrokes. 



NOTE: When using a shell variable as a pseudonym for a directory path, you do 
not need to write $ in front of the variable name; doing so is permitted and 
also works because of the shell's variable substitution mechanism but is not 
required. 



Listing the Directory Stack—dirs 

The directory stack is a mechanism by which you can store and recall directories 
you have changed to using the special change-directory commands pushd and popd, 
discussed in the next two sections. The dirs command lists the directories in 
the directory stack: 

% dirs



/usr/home/john/bin /usr/home/john /usr/home/john/docs
Three directories are on the directory stack in this example for user john. The 
first directory listed is the current directory (the one you would see if you 
entered the pwd command). Directories to the right are previous directories, the 
farthest to the right being the least recent. In this example, the directory 
/usr/home/john/docs was the first directory to be changed to—that is, "pushed" 
onto the pushdown directory stack, /usr/home/john was the next directory, and 
/usr/home/john/bin was the directory most recently changed to (the current 
directory). 

Changing to a Directory Using the Directory Stack—pushd 

To save the pathname of a directory on the directory stack, use the pushd 
command to change to another directory. Using pushd saves the pathname of your 
previous directory on the directory stack so that you can return to the previous 
directory quickly and easily using the popd command. Use dirs to display the 
directories currently saved on the pushdown stack. 

There are three forms of the pushd command: 

pushd



pushd name



pushd +n
Used in the form pushd, the command exchanges the top two directory stack 
elements, making your previous directory the current and your current directory 
the previous. Successive pushd commands used without an argument therefore 
switch you back and forth between the top two directories. 

Used in the form pushd name, the command changes to directory name in the same 
way as cd would have; pushd uses the cdpath directory list to resolve name, and 
succeeds or fails in the same cases as cd. The pathname of the current directory 
is saved in a directory stack prior to the change. The directory stack is an 
implicit array variable maintained by the shell (which you cannot access 
directly) so that each pushd adds the current directory on the left and pushes 
all existing entries to the right; the top (or first) element is always your 
current directory, and subsequent entries are the pathnames of your previous 
directories in reverse order. The popd command discards the top stack entry and 
changes to the new top entry, reducing the total number of items stacked by one. 


Use the form pushd +n to do a circular shift of the directory stack by n 
positions, changing to the new top directory. A circular shift treats the list 
of elements as if they were in a ring, with the first preceded by the last and 
the last followed by the first; the shift changes your position in the ring 
without deleting any of the elements. Consider the following example: 

% dirs



/home/john /home/mary /home/doggie /home/witherspoon



% pushd +2



/home/doggie



% dirs



/home/doggie /home/witherspoon /home/john /home/mary
Note that both before and after the pushd, /home/john precedes /home/mary, and 
/home/doggie precedes /home/witherspoon. The example also shows that, for the 
purpose of the pushd +n command form, /home/witherspoon (the last entry) is 
effectively followed by /home/john (the first entry). 

Returning to a Previous Directory Using the Directory Stack—popd 

After you have saved directories on the directory stack with pushd, you can use 
popd to return to a previous directory. The syntax for the popd command is as 
follows: 

popd [ +n ]
The following example shows the use of pushd, dirs, and popd together: 

% pwd



/usr/home/john



% pushd /usr/spool



% pushd uucppublic



% pushd receive



% dirs



/usr/spool/uucppublic/receive /usr/spool/uucppublic /usr/spool



_/usr/home/john



% popd



/usr/spool/uucppublic



% dirs



/usr/spool/uucppublic /usr/spool /usr/home/john



% popd



/usr/spool



% dirs



/usr/spool /usr/home/john



% popd



/usr/home/john



% dirs



/usr/home/john
Used in the form popd +n, the command deletes the nth entry in the stack. Stack 
entries are numbered from 0, which is your current directory. 

Changing the Active Shell 

The C shell provides a number of commands for changing the active shell. 
Although your login shell may be the C shell, you are not limited to it; you can 
change your shell to Bourne shell or the Korn shell at any time using the exec 
command. The exit and logout commands also change the active shell, by returning 
you to the shell that was active before your current shell: issued from your 
login shell, they return you to the login screen, which is itself a kind of 
shell (of somewhat limited functionality). 

Other commands, such as umask and nohup, change the manner in which UNIX treats 
the shell. 

In order to make the best use of the information in this section, you should 
also read Part IV, Process Control, later in this book, which describes some of 
the UNIX mechanisms these commands are designed to manipulate. 

Invoking a New Shell—exec 

The exec command transfers control to the specified command, replacing the 
current shell. The command you specify becomes your new current shell. The 
syntax of the exec command is as follows: 

exec command
Nearly always, command should be a shell invocation command such as csh, sh, or 
ksh. Control cannot be returned to the invoking environment because it is 
replaced by the new environment. Shell variables exported with the setenv 
command will be passed to the new shell in the usual manner; all other command 
contexts, including local variables and aliases, will be lost. 

The exec command is equivalent to the Bourne shell exec. 

Exiting from the Current Shell—exit 

The exit command causes the current shell invocation to be exited. Its syntax is 
as follows: 

exit [ (exp) ]
If issued from within a shell script, the shell script is terminated and control 
returns to the invoking shell. If issued from your login shell, the .logout 
script in your home directory will be executed before the shell exits. Normally, 
the UNIX operating system will redisplay a login screen after an exit from the 
login shell. 

If you provide the optional exp argument (which must be enclosed in 
parentheses), the argument is evaluated as an arithmetic expression, and the 
resulting value is used as the shell's exit code; otherwise, the current value 
of the status variable is taken as the shell's exit code. The status variable is 
described in the section "Using Predefined Variables" later in this chapter. 

Invoking the System Login Procedure—login 

Use the login command to log out from your current shell and to immediately log 
in under the same or a different user ID. Its syntax is as follows: 

login name [ arg ... ]
Using this shell built-in command is not quite equivalent to logging out in the 
normal manner and then logging in. If you use the login command from a remote 
terminal, the line connection will not be dropped, whereas logging out in the 
normal manner drops the line and requires you to re-establish the connection 
before you can log in again. 

You cannot execute the login built-in command from a subshell; it is legal only 
for your login shell. 

For name, specify the user name you want to log in with. Any arguments you 
specify after name are passed to the /bin/login command and are defined by 
/bin/login, not by the shell. 

Exiting from a Login Shell—logout 

Use the logout command to log out from your login shell. 

logout
You can also terminate the login shell (or any subshell) with the exit command. 
If you have the ignoreeof option set, you cannot use the EOF key to exit from 
the shell; in such a case, use logout or exit. See the section "Using Predefined 
Variables" for a definition of the ignoreeof option. 

Preventing a Command from Terminating Execution after Logout—nohup 

Use the nohup command to run a command that is insensitive to the Hangup signal. 


nohup [ command ]
The UNIX operating system always sends a Hangup signal (signal 1) to a process 
when its process group leader logs out. The net effect is that normally any 
command you are running when you log out is terminated. (Although you can't 
ordinarily issue the logout or exit command, or enter an EOF character, while 
you are running a command, you can always force a logout by turning off your 
terminal, or if using a remote terminal connection, by hanging up the line.) 

When you invoke a command with nohup, the shell effectively disables the Hangup 
signal so that the command cannot receive it, thus allowing command to continue 
to execute after you log out. 

You can disable the Hangup signal for your interactive shell or from within a 
shell script using the trap built-in command, and binary programs written in the 
C language can also disable or ignore the Hangup signal. However, not all 
commands do this. If you use nohup to invoke the command, you are assured that 
the Hangup signal will be ignored whether or not the command disables the 
signal. 

Use nohup with no arguments from within a shell script to disable the Hangup 
signal for the duration of the script. 

Use nohup command to run command with the signal disabled. 

Displaying and Setting the Process File Creation Mask—umask 

The process file creation mask (sometimes, for purposes of brevity, called the 
umask), is an attribute of the shell process, just like the current directory is 
a process attribute. The purpose of the file creation mask is to specify the 
default permissions assigned to new files you create, for example when 
redirecting the output of a command to a file with the > operator. It would be 
extremely inconvenient if the system prompted you for file permissions every 
time it created a file, especially since most of the time you would assign the 
same permissions to all new files. 

If you're not familiar with file permissions, you may want to review the section 
"File Security" in Chapter 3, "The UNIX File System." Briefly, file permissions 
are little flags that UNIX associates which each file. The flags indicate 
whether the file can be read, written, or executed, and by whom. 

The file creation mask is a device you use for indicating what permissions UNIX 
is to assign to a new file by default. If you want some other access permissions 
for a file, the usual approach is to first create the file, then change the 
file's permissions with the chmod command. 

The file creation mask itself is a binary value consisting of nine bits, 
corresponding to each of the permission bits for a file. As a matter of 
convention, the nine bits are represented by three octal digits, with each digit 
representing three bits. The file creation mask is therefore a value expressed 
in octal as three octal digits. The use of octal number representation for the 
file creation mask is a matter of convention, not necessity, yet the umask 
command does not allow you to use any other number form for displa> 



Transfer interrupted!

--

         隋末风云起,双龙走天下。
         尽数天下英豪,唯我独尊! 

※ 来源:·饮水思源站 bbs.sjtu.edu.cn·[FROM: 202.120.5.209]
--
※ 修改:.fzx 于 Aug  1 12:22:41 修改本文.[FROM: heart.hit.edu.cn]
※ 转寄:.紫 丁 香 bbs.hit.edu.cn.[FROM: chen.hit.edu.cn]

--
☆ 来源:.哈工大紫丁香 bbs.hit.edu.cn.[FROM: jmm.bbs@bbs.hit.edu.]
[百宝箱] [返回首页] [上级目录] [根目录] [返回顶部] [刷新] [返回]
Powered by KBS BBS 2.0 (http://dev.kcn.cn)
页面执行时间:820.993毫秒