Museum

Home

Lab Overview

Retrotechnology Articles

⇒ Online Manual

Media Vault

Software Library

Restoration Projects

Artifacts Sought

Related Articles

sh(1)

printenv(1)

access(2)

execve(2)

fork(2)

pipe(2)

tty(4)

environ(5V)

CSH(1)  —  USER COMMANDS

NAME

csh − a shell (command interpreter) with C-like syntax

SYNOPSIS

csh [ −bcefinstvVxX ] [ argument ... ]

DESCRIPTION

csh, the C-Shell, is a command interpreter with a syntax remeniscent of C.  It provides a number of convenient features for interactive use that are not available with the standard (Bourne) shell, including filename completion, command aliasing, history substitution, job control, and a number of builtin commands.  As with the standard shell, the C-Shell provides variable, command and filename substitution. 

Initialization and Termination

When first started, the C-Shell normally performs commands from the .cshrc file in your home directory, if that file exists and you own it.  If the shell is invoked with a name that starts with −, as when it is started by login(1), it is treated as a login shell, in which case the shell then executes commands from the .login file (if owned by you) in your home directory.  Typically, the .login file contains commands to specify the terminal type and environment.  As a login shell terminates, it performs commands from the .logout file (if owned by you) in your home directory. 

Interactive Operation

After startup processing is complete, an interactive C-Shell begin reading commands from the terminal, prompting with hostname% (or hostname# for the super-user).  The shell then repeatedly performs the following actions: a line of command input is read and broken into words. This sequence of words is placed on the history list and then parsed, as described under USAGE, below.  Finally, the shell executes each command in the current line. 

Noninteractive Operation

When running noninteractively, the shell does not prompt for input from the terminal.  A noninteractive C-Shell can execute a command supplied as an argument on its command line, or interpret commands from a script. 

OPTIONS

−b Force a "break" from option processing.  Subsequent command-line arguments are not interpreted as C-Shell options.  This allows the passing of options to a script without confusion.  The shell does not run a set-user-ID script unless this option is present. 

−c Read commands from the first filename argument (which must be present).  Remaining arguments are placed in argv, the argument-list variable. 

−e Exit if a command terminates abnormally or yields a nonzero exit status. 

−f Fast start.  Read neither the .cshrc file, nor the .login file (if a login shell) upon startup. 

−i Forced interactive.  Prompt for command-line input, even if the standard input does not appear to be a terminal (character-special device). 

−n Parse (interpret), but do not execute commands.  This option can be used to check C-Shell scripts for syntax errors. 

−s Take commands from the standard input. 

−t Read and execute a single command line.  A backslash (\) can be used to escape each NEWLINE for continuation of the command line onto subsequent input lines. 

−v Verbose.  Set the verbose predefined variable; command input is echoed after history substitution (but before other substitutions) and before execution. 

−V Set verbose before reading .cshrc.

−x Echo.  Set the echo variable; commands are echoed after all substitutions are performed, just before execution. 

−X Set echo before reading .cshrc.

Except with the flags −c, −i, −s or −t, the first nonflag argument is taken to be the name of a command or script.  It is passed as argument zero, and subsequent arguments are added to the argument list for that command or script. 

USAGE

Refer to Doing More With UNIX: Beginner’s Guide for tutorial information on how to use the various features of the C-Shell. 

Filename Completion

When enabled by setting the variable filec, an interactive C-Shell can complete a partially typed filename or user name.  When followed by an ESC character on the terminal input line, the shell fills in the remaining unambiguous characters of partial filename.  For instance, if the current directory contains the files:

dsc.old chaos  xmpl.o
dsc.new xmpl.cxmpl.out

and the input line typed so far is

manual% ls chESC

the shell fills in the remaining characters from the filename chaos on the input line:

manual% ls chaos__

However, with the partial input line

manual% ls DESC

for which more than one filename matches, the shell fills in only the unambiguous portion contained by all the matching filenames

manual% ls dsc.__

and sounds the terminal bell to indicate that the expansion remains incomplete. 

If a partial filename is followed by the end-of-file character (usually typed as ^D), the shell lists all filenames matching "prefix", and then reprompts (for further input) with the partial command line typed in so far:

manual% ls d^D

dsc.new       dsc.old
manual% ls d__

The same system of ESC and EOF characters expands (or lists matches for) partial user names when the current input word begins with the tilde character (∼):

manual% cd  ∼ro^D

may produce the expansion

manual% cd  ∼root__

This is useful for specifying the home directory of another user. 

The terminal bell signals errors or multiple matches; this can be inhibited by setting the variable nobeep.  Normally, all files in the particular directory are candidates for filename completion.  Files with certain suffixes can be excluded from consideration by setting the variable fignore to the list of those suffixes to be ignored:

manual% set fignore = (.o .out)
manual% ls xESC

results in:

manual% vi xmpl.c__

while ignoring the files xmpl.o and xmpl.out. If, however, the only possible completion includes one of these suffixes, it is not ignored.  fignore does not affect the listing of filenames by ^D. 

Lexical Structure

The shell splits input lines into words at SPACE and TAB characters, except as noted below.  The characters & | ; < > ( and ) form separate words; if paired, the pairs form single words.  These shell metacharacters can be made part of other words, and their special meaning can be suppressed by preceding them with a backslash (\).  A NEWLINE preceded by a \ is equivalent to a SPACE. 

In addition, a string enclosed in matched pairs of single-quotes (´), double-quotes ("), or backquotes (`), forms a partial word; metacharacters in such a string, including any SPACE or TAB characters, do not form separate words.  Within pairs of backquote (`) or double-quote (") characters, a NEWLINE preceded by a backslash (\) gives a true NEWLINE character.  Additional functions of each type of quote are described, below, under Variable Substitution, Command Substitution, and Filename Substitution. 

When the shell’s input is not a terminal, the character # introduces a comment that continues to the end of the input line.  Its special meaning is suppressed when preceded by a \ or enclosed in matching quotes. 

Command Line Parsing

A simple command is composed of a sequence of words.  The first word (that is not part of an I/O redirection) specifies the command to be executed.  A simple command, or a set of simple commands separated by | or |& characters, forms a pipeline.  With |, the standard output of the preceding command is redirected to the standard input of the command that follows.   With |&, both the standard error and the standard output are redirected through the pipeline. 

Pipelines can be separated by semicolons (;), in which case they are executed sequentially.  Pipelines that are separated by && or || form conditional sequences in which the execution of pipelines on the right depends upon the success or failure, respectively, of the pipeline on the left. 

A pipeline or sequence can be enclosed within parentheses "( )" to form a simple command that can be a component in a pipeline or sequence. 

A sequence of pipelines can be executed asynchronously, or "in the background" by appending an &; rather than waiting for the sequence to finish before issuing a prompt, the shell displays the job number (see Job Control, below) and associated process IDs, and prompts immediately. 

History Substitution

History substitution allows you to use words from previous command lines in the command line you are typing.  This simplifies spelling corrections and the repetition of complicated commands or arguments.  Command lines are saved in the history list, the size of which is controlled by the history variable.  The most recent command is retained in any case.  A history substitution begins with a !  (although you can change this with the histchars variable) and may occur anywhere on the command line; history substitutions do not nest.  The !  can be escaped with \ to suppress its special meaning. 

Input lines containing history substitutions are echoed on the terminal after being expanded, but before any other substititions take place or the command gets executed. 

Event Designators

An event designator is a reference to a command-line entry in the history list. 

!  Start a history subsititution, except when followed by a SPACE, TAB, NEWLINE, = or (. 

!!  Refer to the previous command.  By itself, this substitution repeats the previous command. 

!n Refer to command-line n.  !−n Refer to the current command-line minus n. 

!str Refer to the most recent command starting with str. 

!?str [?] Refer to the most recent command containing str. 

!{...} insulate a history reference from adjacent characters (if necessary). 

Word Designators

A : separates the event specification from the word designator.  It can be omitted if the word designator begins with a ^, $, ∗, − or %. 

# The entire command line typed so far. 

0 The first input word (command). 

n The n’th argument.

^ The first argument, that is, 1. 

$ The last argument. 

% The word matched by (the most recent) ?s search. 

x−y A range of words; −y Abbreviates 0−y. 

∗ All the arguments, or a null value if there is just one word in the event. 

x∗ Abbreviates x−$. 

x− Like x∗ but omitting word $. 

Modifiers

After the optional word designator, you can add a sequence of one or more of the following modifiers, each preceded by a :. 

h Remove a trailing pathname component, leaving the head. 

r Remove a trailing suffix of the form ".xxx", leaving the basename.

e Remove all but the suffix. 

s/l/r [/] Substitute r for l. 

t Remove all leading pathname components, leaving the tail. 

& Repeat the previous substitution. 

g Apply the change globally, prefixing the above, for example, ‘g&’. 

p Print the new command but do not execute it. 

q Quote the substituted words, escaping further substitutions. 

x Like q, but break into words at each SPACE, TAB or NEWLINE. 

Unless preceded by a g the modification is applied only to the first string that matches l; an error results if no string matches. 

The left-hand side of substitutions are not regular expressions, but character strings.  Any character can be used as the delimiter in place of /.  A backslash quotes the delimiter character.  The character &, in the right hand side, is replaced by the text from the left-hand-side.  The & can be quoted with a backslash.  A null l uses the previous string either from a l or from a contextual scan string s from !?s.  You can omit the rightmost delimiter if a NEWLINE immediately follows r; the rightmost ?  in a context scan can similarly be omitted. 

Without an event specification, a history reference refers either to the previous command, or to a previous history reference on the command line (if any). 

Quick Substitution

^l^r [^] This is equivalent to the history substitution: !:s^l^r [^]. 

Aliases

The C-Shell maintains a list of aliases that you can create, display, and modify using the alias and unalias commands.  The shell checks the first word in each command to see if it matches the name of an existing alias.  If it does, the command is reprocessed with the alias definition replacing its name; the history substitution mechanism is made available as though that command were the previous input line.  This allows history substitutions, escaped with a backslash in the definition, to be replaced with actual command-line arguments when the alias is used.  If no history substitution is called for, the arguments remain unchanged. 

Aliases can be nested.  That is, an alias definition can contain the name of another alias.  Nested aliases are expanded before any history substitutions is applied.  This is useful in pipelines such as

alias  lm ´ls  −l  \!∗  |  more´

which when called, pipes the output of ls(1V) through more(1).

Execpt for the first word, the name of the alias may not appear in its definition, nor in any alias referred to by its definition.  Such loops are detected, and cause an error message. 

I/O Redirection

The following metacharacters indicate that the subsequent word is the name of a file to which the command’s standard input, standard output, or standard error is redirected; this word is variable, command, and filename expanded separately from the rest of the command. 

< Redirect the standard input. 

<<word
Read the standard input, up to a line that is identical with word, and place the resulting lines in a temporary file.  Unless word is escaped or quoted, variable and command substitutions are performed on these lines.  Then, invoke the pipeline with the temporary file as it’s standard input.  word is not subjected to variable, filename or command substitution, and each line is compared to it before any substitutions are performed by the shell. 

>    >!    >&    >&! 
Redirect the standard output to a file. If the file does not exist, it is created.  If it does exist, it is overwritten; its previous contents are lost.

When set, the variable noclobber prevents destruction of existing files.  It also prevents redirection to terminals and /dev/null, unless one of the ! forms is used.  The & forms redirect both standard output and the the standard error (diagnostic output) to the file. 

>>    >>&    >>!    >>&!
Append the standard output. Like >, but places output at the end of the file rather than overwriting it.  If noclobber is set, it is an error for the file not to exist, unless one of the ! forms is used.  The & forms append both the standard error and standard output to the file. 

Variable Substitution

After an input line is aliased and parsed, and before each command is executed, variable substitution is performed.  I/O redirections are recognized before variable expansion is applied, and are variable-expanded separately.  Strings enclosed in backquotes (`), even when they contain variable references, are interpreted later (see Command Substitution). Otherwise, variable substitution is performed on the command name and argument list together.

The C-Shell maintains a set of variables, each of which is composed of a name and a value.  A variable name consists of up to 20 letters and digits, and starts with a letter (the underscore is considered a letter).  A variable’s value is a space-separated list of zero or more words.  A references to a variable starts with a $, and is replaced the words of that variable’s value, by selected words from the value, or by information about the variable, as described below.  Braces can be used to insulate the reference from subsequent characters, which might otherwise be interpreted as part of it. 

Variable substitution can be suppressed by preceding the $ with a \, except within double-quotes where it always occurs.  Within single-quotes, variable substitution is suppressed.  A $ is escaped if followed by a SPACE, TAB or NEWLINE. 

Variables can be created, displayed, or destroyed using the set and unset commands.  Some variables are maintained or used by the shell.  For instance, the argv variable contains an image of the shell’s argument list.  Of the variables used by the shell, a number are toggles; the shell does not care what their value is, only whether they are set or not. 

Numerical values can be operated on as numbers (as with the @ builtin).  With numeric operations, an empty value is considered to be zero; the second and subsequent words of multiword values are ignored.  For instance, when the verbose variable is set to any value (including an empty value), command input is echoed on the terminal. 

Command and filename substitution is subsequently applied to the words that result from the variable substitution, except when suppressed by double-quotes, when noglob is set (suppressing filename substitution), or when the reference is quoted with the :q modifier.  Within double-quotes, a reference is expanded to form (a portion of) a quoted string; multiword values are expanded to a string with embedded SPACEs.  When the :q modifier is applied to the reference, it is expanded to a list of SPACE-separated words, each of which is quoted to prevent subsequent command or filename substitutions. 

Except as noted below, it is an error to refer to a variable that is not set. 

$var

${var}
These are replaced by words from the value of var, each separated by a SPACE.  If var is an environment variable, its value is returned (but : modifiers and the other forms given below are not available). 

$var [index]

${var[index]}
These select only the indicated words from the value of var.  Variable substitution is applied to index, which may consist of (or result in) a either single number, two numbers separated by a −, or an asterisk.  Words are indexed starting from ‘1’; a ∗ selects all words.  If the first number of a range is omitted (as with ‘$argv[−2]’), it defaults to ‘1’.  If the last number of a range is omitted (as with ‘$argv[1−]’), it defaults to $#var (the word count).  It is not an error for a range to be empty if the second argument is omitted (or within range). 

$#name

${#name}
These give the number of words in the variable.

$0 This substitutes the name of the file from which command input is being read.  An error occurs if the name is not known. 

$n ${n} Equivalent to $argv[n]. 

$∗ Equivalent to $argv[∗]. 

The modifiers :h, :t, :r, :q and :x can be applied (see History Substitution), as can :gh, :gt and :gr.  If braces ({ }) are used, then the modifiers must appear within the braces. The current implementation allows only one such modifier per expansion.

The following references may not be modified with : modifiers. 

$?var

${?var}
Substitutes the string ‘1’ if var is set or ‘0’ if it is not set. 

$?0 Substitutes ‘1’ if the current input filename is known, or ‘0’ if it is not. 

$$ Substitute the process number of the (parent) shell. 

$< Substitutes a line from the standard input, with no further interpretation thereafter.  It can be used to read from the keyboard in a C-Shell script. 

Command and Filename Substitutions

Command and filename substitutions are applied selectively to the arguments of builtin commands.  Portions of expressions that are not evaluated are not expanded.  For non-builtin commands, filename expansion of the command name is done separately from that of the argument list; expansion occurs in a subshell, after I/O redirection is performed. 

Command Substitution

A command enclosed by backquotes (`...`) is performed by a subshell.  Its standard output is broken into separate words at each SPACE, TAB and NEWLINE; null words are discarded.  This text replaces the backquoted string on the current command line.  Within double-quotes, only NEWLINES force new words; SPACE and TAB characters are preserved.  However, a final NEWLINE is ignored.  It is therefore possible for a command substitution to yield a partial word. 

Filename Substitution

Unquoted words containing any of the characters ∗, ?, [, or {, or that begin with ∼, are expanded (also known as globbing) to an alphabetically sorted list of filenames, as follows:

∗ Match any (zero or more) characters. 

?  Match any single character. 

[...] Match any single character in the enclosed list(s) or range(s).  A list is a string of characters.  A range is two characters separated by a minus-sign (−), and includes all the characters in between in the ASCII collating sequence (see ascii(7)).

{str,str, ...}
Expand to each string (or filename-matching pattern) in the comma-separated list. Unlike the pattern-matching expressions above, the expansion of this construct is not sorted.  For instance, "{b,a}" expands to ‘b’ ‘a’, (not ‘a’ ‘b’).  As special cases, the characters { and }, along with the string {}, are passed undisturbed. 

∼[ user]
Your home directory, as indicated by the value of the variable home, or that of user, as indicated by the password entry for user. 

Only the patterns ∗ ?  and [...] imply pattern matching; an error results if no filename matches a pattern that contains them.  The dot character (.), when it is the first character in a filename or pathname component, must be matched explicitly.  The slash (/) must also be matched explicitly. 

Expressions and Operators

A number of C-Shell builtin commands accept expressions, in which the operators are similar to those of C and have the same precedence.  These expressions typically appear in the @, exit, if, set and while commands, and are often used to regulate the flow of control for executing commands.  Components of an expression are separated by white space. 

Null or missing values are considered ‘0’.  The result of all expressions are strings, which may represent decimal numbers. 

The following C-Shell operators are grouped in order of precedence:

(...) grouping

∼ one’s complement

!  logical negation

∗   /   %
multiplication, division, remainder (These are right associative, which can lead to unexpected results.  Group combinations explicitly with parentheses.)

+   − addition, subtraction (also right associative)

<<   >>
bitwise shift left, bitwise shift right

<   >   <=   >=
less than, greater than, less than or equal to, greater than or equal to

==   !=   =∼   !∼
equal to, not equal to, filename-substitution pattern match (described below), filename-substitution pattern mismatch

& bitwise AND

^ bitwise XOR (exclusive or)

| bitwise inclusive OR

&& logical AND

|| logical OR

The operators: ==, !=, =∼, and !∼ compare their arguments as strings; other operators use numbers.  The oprators =∼ and !∼ each check whether or not a string to the left matches a filename substitution pattern on the right.  This reduces the need for switch statements when pattern-matching between strings is all that is required. 

Also available are file inquiries:

−r file Returns true, or ‘1’ if the user has read access.  Otherwise it returns false, or ‘0’. 

−w file True if the user has write access. 

−x file True if the user has execute access. 

−e file True if file exists. 

−o file True if the user owns file. 

−z file True if file is of zero length (empty). 

−f file True if file is a plain file. 

−d file True if file is a directory. 

If file does not exist or is inaccessible, then all inquiries return false. 

An inquiry as to the success of a command is also available:

{ cmd } If cmd runs successfully, the espression evaluates to true, ‘1’.  Otherwise it evaluates to false ‘0’.  (Note that, conversely, cmd itself typically returns ‘0’ when it runs successfully, or some other value if it encounters a problem.  If you want to get at the status directly, use the value of the status variable rather than this expression). 

Control Flow

The shell contains a number of commands to regulate the flow of control in scripts, and within limits, from the terminal.  These commands operate by forcing the shell either to reread input (to loop), or to skip input under certain conditions (to branch).

Each occurrence of a foreach, switch, while, if...then and else builtin must appear as the first word on its own input line. 

If the shell’s input is not seekable and a loop is being read, that input is buffered.  The shell performs seeks within the internal buffer to accomplish the rereading implied by the loop.  (To the extent that this allows, backward goto commands will succeed on nonseekable inputs.) 

Command Execution

If the command is a C-Shell builtin, the shell executes it directly.  Otherwise, the shell searches for a file by that name with execute access.  If the command-name contains a /, the shell takes it as a pathname, and searches for it.  If the command-name does not contain a /, the shell attempts to resolve it to a pathname, searching each directory in the path variable for the command.  To speed the search, the shell uses its hash table (see the rehash builtin) to eliminate directories that have no applicable files.  This hashing can be disabled with the −c or −t, options, or the unhash builtin. 

As a special case, if there is no / in the in the name of the script and there is an alias for the word shell, the expansion of the shell alias is prepended (without modification), to the command line.  The system attempts to execute the first word of this special (late-occurring) alias, which should be a full pathname.  Remaining words of the alias’s definition, along with the text of the input line, are treated as arguments. 

When a pathname is found that has proper execute permissions, the shell forks a new process and passes it, along with its arguments to the kernel (using the execve(2) system call).  The kernel then attempts to overlay the new process with the desired program.  If the file is an executable binary (in a.out(5), the kernel succeeds, and begins executing the new process.  If the file is a text file, and the first line begins with #!, the next word is taken to be the pathname of a shell (or command) to interpret that script.  Subsequent words on the first line are taken as options for that shell.  The kernel invokes (overlays) the indicated shell, using the name of the script as an argument. 

If neither of the above conditions holds, the kernel cannot overlay the file (the execve(2) call fails); the C-Shell then attempts to execute the file by spawning a new shell, as follows:

•If the first character of the file is a #, a C-Shell is invoked. 

•Otherwise, a standard (Bourne) shell is invoked. 

Signal Handling

The shell normally ignores QUIT signals.  Background jobs are immune to signals generated from the keyboard, including hangups.  Other signals have the values that the C-Shell inherited from its environment.  The shell’s handling of interrupt and terminate signals within scripts can be controlled by the onintr builtin.  Login shells catch the TERM signal; otherwise this signal is passed on to child processes.  In no case are interrupts allowed when a login shell is reading the .logout file. 

Job Control

The shell associates a numbered job with each command sequence, to keep track of those commands that are running in the background or have been stopped with TSTP signals (typically ^Z or ^Y).  When a command, or command sequence (semicolon separated list), is started in the background using the & metacharacter, the shell displays a line with the job number in brackets, and a list of associated process numbers:

[1] 1234

To see the current list of jobs, use the jobs builtin command.  The job most recently stopped (or put into the background if none are stopped) is referred to as the current job, and is indicated with a +.  The previous job is indicated with a −; when the current job is terminated or moved to the foreground, this job takes its place (becomes the new current job). 

To manipulate jobs, refer to the bg, fg, kill, stop and % builtins. 

A reference to a job begins with a %.  By itself, the percent-sign refers to the current job. 

%   %+   %%
The current job.

%− The previous job. 

%j Refer to job j as in: kill -9 %j.  j can be a job number, or a string that uniquely specifies the command-line by which it was started; fg %vi might bring a stopped vi job to the foreground, for instance. 

%?string
Specify the job for which the command-line uniquely contains string. 

A job running in the background stops when it attempts to read from the terminal.  Background jobs can normally produce output, but this can be suppressed using the stty tostop command. 

Status Reporting

While running interactively, the shell tracks the status of each job and reports whenever a finishes or becomes blocked.  It normally displays a message to this effect as it issues a prompt, so as to avoid disturbing the appearance of your input.  When set, the notify variable indicates that the shell is to report status changes immediately.  By default, the notify command marks the current process; after starting a background job, type notify to mark it. 

Builtin Commands

Builtin commands are executed within the C-Shell.  If a builtin command occurs as any component of a pipeline except the last, it is executed in a subshell. 

: Null command.  This command is interpreted, but performs no action. 

alias [name[def]]
Assign def to the alias name.  def is a list of words that may contain escaped history-substitution metasyntax.  name is not allowed to be alias or unalias.  If def is omitted, the alias name is displayed along with its current definition.  If both name and def are omitted, all aliases are displayed. 

bg [% job] ...
Run the current or specified jobs in the background.

break Resume execution after the end of the nearest enclosing foreach or while loop.  The remaining commands on the current line are executed.  This allows multilevel breaks to be written as a list of break commands, all on one line. 

breaksw Break from a switch, resuming after the endsw. 

case label: A label in a switch statement. 

cd [dir]

chdir [dir] Change the shell’s working directory to directory dir.  If no argument is given, change to the home directory of the user.  If dir is a relative pathname not found in the current directory, check for it in those directories listed in the cdpath variable.  If dir is the name of a shell variable whose value starts with a /, change to the directory named by that value. 

continue Continue execution of the nearest enclosing while or foreach. 

default: Labels the default case in a switch statement.  The default should come after all case labels.  Any remaining commands on the command line are first executed. 

dirs [−l]
Print the directory stack, most recent to the left; the first directory shown is the current directory. With the −l argument, produce an unabbreviated printout; use of the ∼ notation is suppressed. 

echo [ −n] list
The words in list are written to the shell’s standard output, separated by spaces.  The output is terminated with a NEWLINE unless the −n option is used. 

eval arg ...
Reads the arguments as input to the shell, and executes the resulting command(s).  This is usually used to execute commands generated as the result of command or variable substitution, since parsing occurs before these substitutions.  See tset(1) for an example of how to use eval. 

exec command
Execute command in place of the current shell, which terminates. 

exit [( expr) ]
The shell exits, either with the value of the status variable, or with the value of the specified by the expression expr.

fg %[ job] Bring the current or specified job into the foreground. 

foreach var (wordlist)

   ...

end The variable var is successively set to each member of wordlist.  The sequence of commands between this command and the matching end is executed for each new value of var.  (Both foreach and end must appear alone on separate lines.) 

The builtin command continue may be used to continue the loop prematurely and the builtin command break to terminate it prematurely.  When this command is read from the terminal, the loop is read up once prompting with ‘?’ before any statements in the loop are executed. 

glob wordlist
Perform filename expansion on wordlist.  Like echo, but no \ escapes are recognized. Words are delimited by null characters in the output. 

goto label The specified label is filename and command expanded to yield a label.  The shell rewinds its input as much as possible and searches for a line of the form label: possibly preceded by SPACE or TAB characters.  Execution continues after the indicated line. 

hashstat Print a statistics line indicating how effective the internal hash table has been at locating commands (and avoiding execs).  An exec is attempted for each component of the path where the hash function indicates a possible hit, and in each component that does not begin with a ‘/’. 

history [−hr] [n]
Display the history list; if n is given, display only the n most recent events. 

−r Reverse the order of printout to be most recent first rather than oldest first. 

−h display the history list without leading numbers.  This is used to produce files suitable for sourcing using the −h option to source.

if (expr) command
If the specified expression evaluates to true, the single command with arguments is executed.  Variable substitution on command happens early, at the same time it does for the rest of the if command.  command must be a simple command, not a pipeline, a command list, or a parenthesized command list.  Note that I/O redirection occurs even if expr is false, when command is not executed (this is a bug). 

if (expr) then

...

else if (expr2) then

...

else

...

endif If expr is true, commands up to the first else are executed.  Otherwise, if expr2 is true, the commands between the else if and the second else are executed.  Otherwise, commands between the else and the endif are executed.  Any number of else if pairs are allowed, but only one else.  Only one endif is needed, but it is required.  The words else and endif must be the first nonwhite characters on a line.  The if must appear alone on its input line or after an else.) 

jobs [−l] List the active jobs under job control. 

−l List process ids, in addition to the normal information. 

kill [− sig] [pid] [% job ] ...

kill −l Send the TERM (terminate) signal, by default, or the signal specified, to the specified process id, the job indicated, or the current job.  Signals are either given by number or by name.  There is no default.  Typing ‘kill’ does not send a signal to the current job.  If the signal being sent is TERM (terminate) or HUP (hangup), then the job or process is sent a CONT (continue) signal as well. 

−l List the signal names that can be sent. 

limit [−h] [resource [max-use]]
Limit the consumption by the current process or any process it spawns, each not to exceed max-use on the specified resource.  If max-use is omitted, print the current limit; if resource is omitted, display all limits. 

−h Use hard limits instead of the current limits.  Hard limits impose a ceiling on the values of the current limits.  Only the superuser may raise the hard limits. 

resource is one of:

cputime Maximum CPU seconds per process. 

filesize Largest single file allowed. 

datasize Maximum data size (including stack) for the process. 

stacksize Maximum stack size for the process. 

coredumpsize Maximum size of a core dump (file). 

max-use is a number, with an optional scaling factor, as follows:

nh Hours (for cputime). 

nk n kilobytes.  This is the default for all but cputime. 

nm n megabytes or minutes (for cputime). 

mm:ss Minutes and seconds (for cputime). 

login Terminate a login shell and invoke login(1). The .logout file is not processed. 

logout Terminate a login shell. 

nice [+ n | − n] [command]
Increment the nice value for the shell or for command by n. The higher the nice value, the lower the priority of a process, and the slower it runs. When given, command is always run in a subshell, and the restrictions placed on commands in simple if commands apply.  If command is omitted, nice increments the value for the current shell.  If no increment is specified, nice sets the nice value to 4.  The range of nice values is from −20 to 20.  Values of n outside this range set the value to the lower, or to the higher boundary, respectively. 

+n Increment the nice value by n. 

−n Decrement by n.  This argument can be used only by the super-user. 

nohup [command]
Run command with hangups ignored.  With no arguments, ignore hangups throughout the remainder of a script.  When given, command is always run in a subshell, and the restrictions placed on commands in simple if commands apply.  All processes detached with & are effectively nohup’ed. 

notify [% job] ...
Notify the user asynchronously when the status of the current, or of specified jobs, changes.

onintr [ − | label]
Control the action of the shell on interrupts. With no arguments, onintr restores the default action of the shell on interrupts.  (The shell terminates shell scripts and returns to the terminal command input level).  With the − argument, the shell ignores all interrupts.  With a label argument, the shell executes a goto label when an interrupt is received or a child process terminates because it was interrupted. 

popd [+ n]
Pops the directory stack, and cds to the new top directory.  The elements of the directory stack are numbered from 0 starting at the top. 

+n Discard the n’th entry in the stack. 

pushd [+ n | dir]
Push a directory onto the directory stack. With no arguments, exchange the top two elements.

+n Rotate the n’th entry to the top of the stack and cd to it. 

dir push the current working directory onto the stack and change to dir. 

rehash Recompute the internal hash table of the contents of directories listed in the path variable to account for new commands added. 

repeat count command
Repeat command count times command is subject to the same restrictions as with the one-line if statement. 

set [var [ = value ] ]

set var[n] = word
With no arguments, set displays the values of all shell variables.  Multiword values are displayed as a parenthesized list.  With the var argument alone, set assigns an empty (null) value to the variable var.  With arguments of the form var = value set assigns value to var, where value is one of:

word A single word (or quoted string). 

(wordlist) A space-separated list of words enclosed in parentheses. 

Values are command and filename expanded before being assigned.  The form set var[n] = word replaces the n’th word in a multiword value with word. 

setenv [var[ word]]
With no arguments, setenv displays all environment variables.  With the var argument sets the environment variable var to have an empty (null) value.  (By convention, environment variables are normally given upper-case names.)  With both var and word arguments setenv sets the environment variable name to the value word, which must be either a single word or a quoted string.  The most commonly used environment variables, USER, TERM and PATH, are automatically imported to and exported from the csh variables user, term, and path; there is no need to use setenv for these.  In addition, the shell sets the PWD environment variable from the csh variable cwd whenever the latter changes. 

shift [variable]
The components of argv, or variable, if supplied, are shifted to the left, discarding the first component.  It is an error for the variable not to be set, or to have a null value. 

source [−h] name
Reads commands from name.  source commands may be nested, but if they are nested too deeply the shell may run out of file descriptors.  An error in a sourced file at any level terminates all nested source commands. 

−h Place commands from the the file name on the history list without executing them. 

stop [% job] ...
Stop the current or specified background job.

suspend Stops the shell in its tracks, much as if it had been sent a stop signal with ^Z.  This is most often used to stop shells started by su.

switch (string)

case label:

...

breaksw

...

default:

...

breaksw

endsw Each label is successively matched, against the specified string, which is first command and filename expanded.  The file metacharacters ∗, ?  and [...] may be used in the case labels, which are variable expanded.  If none of the labels match before a ‘default’ label is found, execution begins after the default label.  Each case statement and the default statement must appear at the beginning of a line.  The command breaksw continues execution after the endsw.  Otherwise control falls through subsequent case and default statements as with C.  If no label matches and there is no default, execution continues after the endsw. 

time [command]
With no argument, print a summary of time used by this C-Shell and its children. With an optional command, execute command and print a summary of the time it uses. 

umask [value]
Display the file creation mask. With value set the file creation mask.  value is given in octal, and is XORed with the permissions of  666 for files and 777 for directories to arrive at the permissions for new files.  Common values include 002, giving complete access to the group, and read (and directory search) access to others, or 022, giving read (and directory search) but not write permission to the group and others. 

unalias pattern
Discard aliases that match (filename substitution) pattern. All aliases are removed by unalias ∗. 

unhash Disable the internal hash table. 

unlimit [−h] [resource]
Remove a limitation on resource.  If no resource is specified, then all resource limitations are removed.  See the description of the limit command for the list of resource names. 

−h Remove corresponding hard limits.  Only the super-user may do this. 

unset pattern
Remove variables whose names match (filename substitution) pattern.  All variables are removed by unset ∗; this has noticeably distasteful side-effects. 

unsetenv variable
Removes variable from the environment.  Pattern matching, as with unset is not performed. 

wait Wait for background jobs to finish (or for an interrupt) before prompting. 

while (expr)

...

end While expr is true (evaluates to non-zero), repeat commands between the while and the matching end statement.  break and continue may be used to terminate or continue the loop prematurely.  The while and end must appear alone on their input lines.  If the shell’s input is a terminal, it prompts for commands with a question-mark until the end command is entered and then performs the commands in the loop. 

% [job] [&]
Bring the current or indicated job to the foreground.  With the ampersand, continue running job in the background. 

@ [var =expr ]

@ [var [n] =expr
With no arguments, display the values for all shell variables. With arguments, the variable var, or the n’th word in the value of var, to the value that expr evaluates to.  (If [n] is supplied, both var and its n’th component must already exist.)

If the expression contains the characters >, <, & or |, then at least this part of expr must be placed within parentheses. 

The operators ∗=, +=, etc., are available as in C.  The space separating the name from the assignment operator is optional.  Spaces are, however, mandatory in separating components of expr that would otherwise be single words. 

Special postfix operators, ++ and −− increment or decrement name, respectively. 

Environment Variables and Predefined Shell Variables

Unlike the standard shell, the C-Shell maintains a distinction between environment variables, which are automatically exported to processes it invokes, and shell variables, which aren’t.  Both types of variables are treated similarly under variable substitution.  The shell sets the variables argv, cwd, home, path, prompt, shell, and status upon initialization.  The shell copies the environment variable USER into the shell variable user, TERM into term, and HOME into home, and copies each back into the respective environment variable whenever the shell variables are reset.  PATH and path are similarly handled.  You need only set path once in the .cshrc or .login file.  The environment variable PWD is set from cwd whenever the latter changes.  The following shell variables have predefined meanings:

argv Argument list.  Contains the list of command line arguments supplied to the current invocation of the shell.  This variable determines the value of the positional parameters $1, $2, and so on. 

cdpath Contains a list of directories to be searched by the cd, chdir, and popd commands, if the directory argument each accepts is not a subdirectory of the current directory. 

cwd The full pathname of the current directory. 

echo Echo commands (after substitutions), just before execution. 

fignore A list of filename suffixes to ignore when attempting filename completion.  Typically the single word ‘.o’. 

filec Enable filename completion, in which case the EOT character (^D) and the ESC character have special significance when typed in at the end of a terminal input line:

EOT Print a list of all filenames that start with the preceding string. 

ESC Replace the preceding string with the longest unambiguous extension. 

hardpaths
If set, pathnames in the directory stack are resolved to contain no symbolic-link components.

histchars A two-character string.  The first character replaces !  as the history-substitution character.  The second replaces the carat (^) for quick substitutions. 

history The number of lines saved in the history list.  A very large number may use up all of the C-Shell’s memory.  If not set, the C-Shell saves only the most recent command. 

home The user’s home directory.  The filename expansion of ∼ refers to the value of this variable. 

ignoreeof If set, the shell ignores end-of-file from terminals.  This protects against accidentally killing a C-Shell by typing a ^D. 

mail A list of files where the C-Shell checks for mail.  If the first word of the value is a number, it specifies a mail checking interval in seconds (default 5 minutes). 

nobeep Suppresses the bell during command completion when you ask the C-Shell to extend an ambiguous filename. 

noclobber Restricts output redirection so that existing files are not destroyed by accident.  > redirections can only be made to new files.  >> redirections can only be made to existing files. 

noglob Inhibit filename substitution.  This is most useful in shell scripts once filenames (if any) are obtained and no further expansion is desired. 

nonomatch
Returns the filename substitution pattern, rather than an error, if the pattern is not matched.  Malformed patterns still result in errors.

notify If set, the shell notifies you immediately as jobs are completed, rather than waiting until just before issuing a prompt. 

path The list of directories in which to search for commands.  path is initialized from the environment variable PATH, which the C-Shell updates whenever path changes.  A null word specifies the current directory.  The default is typically: (. /usr/ucb /bin /usr/bin).  If path becomes unset only full pathnames will execute.  An interactive C-Shell will normally hash the contents of the directories listed after reading .cshrc, and whenever path is reset.  If new commands are added, use the rehash command to update the table. 

prompt The string an interactive C-Shell prompts with.  Noninteractive shells leave the prompt variable unset.  Aliases and other commands in the .cshrc file that are only useful interactively, can be placed after the following test: if ($?prompt == 0) exit, to reduce startup time for noninteractive shells.  A !  in the prompt string is replaced by the current event number.  The default prompt is hostname% for mere mortals, or hostname# for the super-user. 

savehist The number of lines from the history list that are saved in ∼/.history when the user logs out.  Large values for savehist slow down the C-Shell during startup. 

shell The file in which the C-Shell resides.  This is used in forking shells to interpret files that have execute bits set, but that are not executable by the system. 

status The status returned by the most recent command.  If that command terminated abnormally, 0200 is added to the status.  Builtin commands that fail return exit status ‘1’, all other builtin commands set status to ‘0’. 

time Controls automatic timing of commands.  Can be supplied with one or two values.  The first is the reporting threshold in CPU seconds.  The second is a string of tags and text indicating which resources to report on.  A tag is a percent sign (%) followed by a single upper-case letter (unrecognized tags print as text):

%D Average amount of unshared data space used in Kilobytes. 

%E Elapsed (wallclock) time for the command. 

%F Page faults. 

%I Number of block input operations. 

%K Average amount of unshared stack space used in Kilobytes. 

%M Maximum real memory used during execution of the process. 

%O Number of block output operations. 

%P Total CPU time — U (user) plus S (system) — as a percentage of E (elapsed) time. 

%S Number of seconds of CPU time consumed by the kernel on behalf of the user’s process. 

%U Number of seconds of CPU time devoted to the user’s process. 

%W Number of swaps. 

%X Average amount of shared memory used in Kilobytes. 

The default summary display outputs from the %U, %S, %E, %P, %X, %D, %I, %O, %F and %W tags, in that order. 

verbose Display each command after history substitution takes place. 

DIAGNOSTICS

You have stopped jobs. 
You attempted to exit the C-Shell with stopped jobs under job control. An immediate second attempt to exit will succeed, terminating the stopped jobs.

FILES

∼/.cshrc Read at beginning of execution by each shell. 

∼/.login Read by login shells after ‘.cshrc’ at login. 

∼/.logout Read by login shells at logout. 

∼/.history Saved history for use at next login. 

/bin/sh Standard shell, for shell scripts not starting with a ‘#’. 

/tmp/sh∗ Temporary file for ‘<<’. 

/etc/passwd Source of home directories for ‘∼name’.

LIMITATIONS

Words can be no longer than 1024 characters.  The system limits argument lists to 10240 characters.  The number of arguments to a command which involves filename expansion is limited to 1/6’th the number of characters allowed in an argument list.  Command substitutions may substitute no more characters than are allowed in an argument list.  To detect looping, the shell restricts the number of alias substitutions on a single line to 20. 

SEE ALSO

sh(1), printenv(1), access(2), execve(2), fork(2), pipe(2), tty(4), environ(5V)

Getting Started With UNIX: Beginner’s Guide

Doing More With UNIX: Beginner’s Guide

BUGS

When a command is restarted from a stop, the shell prints the directory it started in if this is different from the current directory; this can be misleading (that is, wrong) as the job may have changed directories internally. 

Shell builtin functions are not stoppable/restartable.  Command sequences of the form a ; b ; c are also not handled gracefully when stopping is attempted.  If you suspend b, the shell never executes c.  This is especially noticeable if the expansion results from an alias.  It can be avoided by placing the sequence in parentheses to force it into a subshell. 

Control over terminal output after processes are started is primitive; use the Sun Window system if you need better output control. 

Shell procedures, as with the standard shell, should be provided. 

Commands within loops, prompted for by ?, are not placed in the history list. 

Control structures should be parsed rather than being recognized as builtin commands.  This would allow control commands to be placed anywhere, to be combined with |, and to be used with & and ; metasyntax. 

It should be possible to use the : modifiers on the output of command substitutions.  There are two problems with : modifier usage on variable substitutions: not all of the modifiers are available, and only one modifier per substitution is allowed. 

Quoting conventions are contradictory and confusing. 

Symbolic links can fool the shell.  Setting the hardpaths variable alleviates this. 

set  path should remove duplicate pathnames from the pathname list.  These often occur because a shell script or a .cshrc file does something like set  path=(/usr/local  /usr/hosts  $path) to ensure that the named directories are in the pathname list. 

The only way to direct the standard output and standard error separately is by invoking a subshell, as follows:

tutorial% (command > outfile) >& errorfile

Although robust enough for general use, adventures into the esoteric periphery of the C-Shell may reveal unexpected quirks. 

Sun Release 3.2  —  Last change: 24 July 1986

Typewritten Software • bear@typewritten.org • Edmonds, WA 98026