On Unix-like operating systems, the csh command launches the C shell, and is a command interpreter with a syntax inspired by the C programming language.

Description

csh is a command language interpreter with many powerful features, including a history mechanism (see History substitutions), job control facilities (see Jobs), interactive file name and username completion (see File Name Completion), and a C-like syntax. It is used both as an interactive login shell and a shell script command processor.

  • Description
  • Syntax
  • Options
  • Lexical Structure
  • Commands
  • Jobs
  • Status Reporting
  • File Name Completion
  • History Substitutions
  • Quotations with ’ and "
  • Alias substitution
  • Variable substitution
  • Command and file name substitution
  • Command substitution
  • File name substitution
  • Input/output
  • Expressions
  • Control flow
  • Built-in commands
  • Pre-defined and environment variables
  • Non-built-in command execution
  • Signal handling
  • Limitations
  • Files
  • Examples
  • Related commands
  • Linux commands help

If the first argument (argument 0) to the shell is a dash (’-’), then csh is run as a login shell. A login shell also can be specified by invoking the shell with the -l flag as the only argument.

Syntax

csh [-bcefimnstVvXx] [argument …]

csh [-l]

Options

After flag arguments are processed, if arguments remain but none of the -c, -i, -s, or -t options were given, the first argument is taken as the name of a file of commands to be executed. The shell opens this file, and saves its name for possible resubstitution by $0. Since many systems use either the standard version 6 or version 7 shells whose shell scripts are not compatible with this shell, the shell executes such a “standard” shell if the first character of a script is not a hash mark (#); i.e., if the script does not start with a comment. Remaining arguments initialize the variable argv.

An instance of csh begins by executing commands from the file /etc/csh.cshrc and, if this is a login shell, /etc/csh.login. It then executes commands from .cshrc in the home directory of the invoker, and, if this is a login shell, the file .login in the same location. It is typical for users on CRT monitors to put the command “stty crt” in their .login file, and to also invoke tset there.

In the normal case, the shell begins reading commands from the terminal, prompting with % . Processing of arguments and the use of the shell to process files containing command scripts are described below.

The shell repeatedly performs the following actions: a line of command input is read and broken into “words”. This sequence of words is placed on the command history list and parsed. Finally each command in the current line is executed.

When a login shell terminates it executes commands from the files .logout in the user’s home directory and /etc/csh.logout.

Lexical Structure

The shell splits input lines into words at blanks and tabs with the following exceptions. The characters &, |, ;, <, >, (, and ) form separate words. If doubled in &&, ||, «, or », these pairs form single words. These parser metacharacters may be made part of other words, or have their special meaning prevented, by preceding them with a backslash (). A newline preceded by a \ is equivalent to a blank.

Strings enclosed in matched pairs of quotations, ‘, `, or “, form parts of a word; metacharacters in these strings, including blanks and tabs, do not form separate words. These quotations have semantics to be described later. Within pairs of ’ or " characters, a newline preceded by a \ gives a true newline character.

When the shell’s input is not a terminal, the character # introduces a comment that continues to the end of the input line. This special meaning is prevented when preceded by \ and in quotations using `, ‘, and “.

Commands

A simple command is a sequence of words, the first of which specifies the command to be executed. A simple command or a sequence of simple commands separated by | characters forms a pipeline. The output of each command in a pipeline is connected to the input of the next. Sequences of pipelines may be separated by ;, and are then executed sequentially. A sequence of pipelines may be executed without immediately waiting for it to terminate by following it with a &.

Any of the above may be placed in ( ) to form a simple command (that may be a component of a pipeline, for example). It is also possible to separate pipelines with || or && showing, as in the C language, that the second is to be executed only if the first fails or succeeds, respectively. See Expressions.

Jobs

The shell associates a job with each pipeline. It keeps a table of current jobs, printed by the jobs command, and assigns them small integer numbers. When a job is started asynchronously with &, the shell prints a line that looks like:

[1] 1234

Showing that the job which was started asynchronously was job number 1 and had one (top-level) process, whose process ID was 1234.

If you are running a job and want to do something else you may hit ^Z (control-Z), which sends a SIGSTOP signal to the current job. The shell then normally shows the job is “Stopped”, and print another prompt. You can then manipulate the state of this job, putting it in the background with the bg command, or run some other commands and eventually bring the job back into the foreground with the fg command. A ^Z takes effect immediately and is like an interrupt in that pending output and unread input are discarded when it is typed. There is another special key ^Y that does not generate a SIGSTOP signal until a program attempts to read it. This request can usefully be typed ahead when you have prepared some commands for a job that you want to stop after it has read them.

A job being run in the background stops if it tries to read from the terminal. Background jobs are normally allowed to produce output, but this can be disabled by giving the command stty tostop. If you set this tty option, then background jobs stop when they try to produce output like they do when they try to read input.

There are several ways to refer to jobs in the shell. The character % introduces a job name. If you want to refer to job number 1, you can name it %1. Only naming a job brings it to the foreground; so, %1 is a synonym for fg %1, bringing job number 1 back into the foreground. Similarly, saying %1 & resumes job number 1 in the background. Jobs can also be named by prefixes of the string typed in to start them, if these prefixes are unambiguous; thus %ex would normally restart a suspended ex job, if there were only one suspended job whose name began with the string “ex”. It is also possible to say %?string, which specifies a job whose text contains string, if there is only one such job.

The shell maintains a notion of the current and previous jobs. In output about jobs, the current job is marked with a + and the previous job with a -. The abbreviation %+ refers to the current job and %- refers to the previous job. For close analogy with the syntax of the history mechanism (described below), %% is also a synonym for the current job.

The job control mechanism requires that the stty option new be set. It is an artifact from a new implementation of the tty driver that allows generation of interrupt characters from the keyboard to tell jobs to stop. See stty for details on setting options in the new tty driver.

Status Reporting

The shell learns immediately whenever a process changes state. It normally informs you whenever a job becomes blocked so that no further progress is possible, but only right before it prints a prompt. This is done so that it does not otherwise disturb your work. If, however, you set the shell variable notify, the shell notifies you immediately of changes of status in background jobs. There is also a shell command notify that marks a single process so that its status changes are immediately reported. By default, notify marks the current process; say notify after starting a background job to mark it.

When you try to leave the shell while jobs are stopped, you are warned that “You have stopped jobs”. You may use the jobs command to see what they are. If you try to exit again immediately, the shell does not warn you a second time, and the suspended jobs are terminated.

File Name Completion

When the file name completion feature is enabled by setting the shell variable filec (see set), csh interactively completes file names and usernames from unique prefixes when they are input from the terminal followed by the escape character (the Escape key, or control-[). For example, if the current directory looks like

DSC.OLD bin cmd lib xmpl.c DSC.NEW chaosnet cmtest mail xmpl.o bench class dev mbox xmpl.out

and the input is

% vi ch

csh completes the prefix “ch” to the only matching file name “chaosnet”, changing the input line to

% vi chaosnet

However, given

% vi D

csh only expands the input to

% vi DSC.

And sounds the terminal bell to indicate that the expansion is incomplete, since there are two file names matching the prefix D.

If a partial file name is followed by the end-of-file character (usually control-D), then, instead of completing the name, csh lists all file names matching the prefix. For example, the input

% vi D

Causes all files beginning with D to be listed:

DSC.NEW DSC.OLD

While the input line remains unchanged.

The same system of escape and end-of-file can also be used to expand partial usernames, if the word to be completed (or listed) begins with the tilde character (~). For example, typing

cd ~ro

May produce the expansion

cd ~root

The use of the terminal bell to signal errors or multiple matches can be inhibited by setting the variable nobeep.

Normally, all files in the particular directory are candidates for name completion. Files with certain suffixes can be excluded from consideration by setting the variable fignore to the list of suffixes to be ignored. Thus, if fignore is set by the command

% set fignore = (.o .out)

Then typing

% vi x

Would result in the completion to

% vi xmpl.c

Ignoring the files “xmpl.o” and “xmpl.out”. However, if the only completion possible requires not ignoring these suffixes, then they are not ignored. In addition, fignore does not affect the listing of file names by control-D. All files are listed regardless of their suffixes.

History Substitutions

History substitutions place words from previous command input as portions of new commands, making it easy to repeat commands, repeat arguments of a previous command in the current command, or fix spelling mistakes in the previous command with little typing and a high degree of confidence. History substitutions begin with the character ! and may begin anywhere in the input stream (provided that they do not nest). This ! may be preceded by a \ to prevent its special meaning; for convenience, a ! character is passed unchanged when it is followed by a blank, tab, newline, = or (. History substitutions also occur when an input line begins with ^. This special abbreviation is described below. Any input line containing history substitution is echoed on the terminal before it is executed as typed without history substitution.

Commands input from the terminal that consist of one or more words are saved on the history list. The history substitutions reintroduce sequences of words from these saved commands into the input stream. The size of the history list is controlled by the history variable; the previous command is always retained, regardless of the value of the history variable. Commands are numbered sequentially from 1.

Consider the following output from the history command:

09 write michael 10 ex write.c 11 cat oldwrite.c 12 diff *write.c

The commands are shown with their event numbers. It is not usually necessary to use event numbers, but the current event number can be made part of the prompt by placing a ! in the prompt string.

With the current event 13 we can refer to previous events by event number !11, relatively as in !-2 (referring to the same event), by a prefix of a command word as in !d for event 12 or !wri for event 9, or by a string contained in a word in the command as in !?mic? also referring to event 9. These forms, without further change, reintroduce the words of the specified events, each separated by a single blank. As a special case, !! refers to the previous command; thus !! alone is a re-do.

To select words from an event we can follow the event specification by a : and a designator for the desired words. The words of an input line are numbered from 0, the first (usually command) word being 0, the second word (first argument) being 1, etc. The basic word designators are:

The : separating the event specification from the word designator can be omitted if the argument selector begins with a ^, $, *, -, or %. After the optional word designator, a sequence of modifiers can be placed, each preceded by a :. The following modifiers are defined:

Unless preceded by a g the change is applied only to the first modifiable word. With substitutions, it is an error for no word to be applicable.

The left side of substitutions are not regular expressions in the sense of the editors, but instead strings. Any character may be used as the delimiter in place of /; a \ quotes the delimiter into the l and r strings. The character & in the right side is replaced by the text from the left. A \ also quotes &. A NULL l (//) uses the previous string either from an l or from a contextual scan string s in !?s?. The trailing delimiter in the substitution may be omitted if a newline follows immediately as may the trailing ? in a contextual scan.

A history reference may be given without an event specification; e.g., !$. Here, the reference is to the previous command unless a previous history reference occurred on the same line in which case this form repeats the previous reference. Thus “!?foo?^ !$” gives the first and last arguments from the command matching “?foo?”.

A special abbreviation of a history reference occurs when the first non-blank character of an input line is a ^. This is equivalent to “!:s^” providing a convenient shorthand for substitutions on the text of the previous line. Thus ^lb^lib fixes the spelling of “lib” in the previous command. Finally, a history substitution may be surrounded with { and } if necessary to insulate it from the characters that follow. Thus, after ls -ld ~paul we might do !{l}a to do ls -ld ~paula, while !la would look for a command starting with “la”.

Quotations with ’ and "

The quotation of strings by ’ and " can prevent all or some of the remaining substitutions. Strings enclosed in ’ are prevented from any further interpretation. Strings enclosed in " may be expanded as described below.

In both cases the resulting text becomes (all or part of) a single word; only in one special case (see Command Substitution, below) does a " quoted string yield parts of more than one word; ’ quoted strings never do.

Alias substitution

The shell maintains a list of aliases that can be established, displayed and modified by the alias and unalias commands. After a command line is scanned, it is parsed into distinct commands and the first word of each command, left-to-right, is checked to see if it has an alias. If it does, then the text that is the alias for that command is reread with the history mechanism available as though that command were the previous input line. The resulting words replace the command and argument list. If no reference is made to the history list, then the argument list is left unchanged.

Thus if the alias for “ls” is “ls -l”, the command ls /usr would map to ls -l /usr, the argument list here being undisturbed. Similarly, if the alias for “lookup” was “grep !^ /etc/passwd”, then lookup bill would map to grep bill /etc/passwd.

If an alias is found, the word transformation of the input text is performed and the aliasing process begins again on the reformed input line. Looping is prevented if the first word of the new text is the same as the old by flagging it to prevent further aliasing. Other loops are detected and cause an error.

Note that the mechanism allows aliases to introduce parser “metasyntax.” Thus, we can alias print ‘pr !* | lpr’ to make a command that pr’s its arguments to the line printer.

Variable substitution

The shell maintains a set of variables, each of which has as value a list of zero or more words. Some of these variables are set by the shell or referred to by it. For instance, the argv variable holds the shell’s argument list, and words of this variable’s value are referred to in special ways.

The values of variables may be displayed and changed using the set and unset commands. Of the variables referred to by the shell a number are toggles; the shell does not care what their value is, only whether they are set or not. For instance, the verbose variable is a toggle that causes command input to be echoed. The setting of this variable results from the -v command-line option.

Other operations treat variables numerically. The @ command permits numeric calculations to be performed and the result assigned to a variable. Variable values are, however, always represented as (zero or more) strings. For numeric operations, the null string is considered to be zero, and the second and additional words of multiword values are ignored.

After the input line is aliased and parsed, and before each command is executed, variable substitution is performed, keyed by $ characters. This expansion can be prevented by preceding the $ with a \ except within double quotes (”), where substitution always occurs, and within single quotes (’), where it never occurs. Strings quoted by backticks ( ) are interpreted later (see Command Substitution, below), so $ substitution does not occur there until later, if at all. A $ is passed unchanged if followed by a blank, tab, or end-of-line.

Input/output redirections are recognized before variable expansion, and are variable expanded separately. Otherwise, the command name and entire argument list are expanded together. It is thus possible for the first (command) word (to this point) to generate more than one word, the first of which becomes the command name, and the rest of which become arguments.

Unless enclosed in " or given the :q modifier, the results of variable substitution may eventually be command and file name substituted. Within “, a variable whose value consists of multiple words expands to (a portion of) a single word, with the words of the variable’s value separated by blanks. When the :q modifier is applied to a substitution, the variable expands to multiple words with each word separated by a blank and quoted to prevent later command or file name substitution.

The following metasequences are provided for introducing variable values into the shell input. Except as noted, it is an error to reference a variable that is not set.

The modifiers :e, :h, :t, :r, :q, and :x may be applied to the substitutions above as may :gh, :gt, and :gr. If braces { } appear in the command form, then the modifiers must appear in the braces. The current implementation allows only one : modifier on each $ expansion.

The following substitutions may not be modified with : modifiers.

Command and file name substitution

The remaining substitutions, command and file name substitution, are applied selectively to the arguments of built-in commands. Here, “selectively” means that portions of expressions that are not evaluated are not subjected to these expansions. For commands that are not internal to the shell, the command name is substituted separately from the argument list. This occurs very late, after input-output redirection is performed, and in a child of the main shell.

Command substitution

Command substitution is shown by a command enclosed in `. The output from such a command is normally broken into separate words at blanks, tabs, and newlines, with null words being discarded; this text then replaces the original string. Within double quotes (”), only newlines force new words; blanks and tabs are preserved.

In any case, the single final newline does not force a new word. Note that it is therefore possible for a command substitution to yield only part of a word, even if the command outputs a complete line.

File name substitution

If a word contains any of the characters *, ?, [, or {, or begins with the character ~, then that word is a candidate for file name substitution, also known as “globbing”. This word is then regarded as a pattern, and replaced with an alphabetically sorted list of file names that match the pattern. In a list of words specifying file name substitution it is an error for no pattern to match an existing file name, but it is not required for each pattern to match. Only the metacharacters *, ?, and [ imply pattern matching, the characters ~ and { being more akin to abbreviations.

In matching file names, the character . at the beginning of a file name or immediately following a /, and the character / must be matched explicitly. The character * matches any string of characters, including the null string. The character ? matches any single character.

The sequence “[…]” matches any one of the characters enclosed. Within “[…]”, a pair of characters separated by - matches any character lexically between the two (inclusive). Within “[…]”, the name of a character class enclosed in [: and :] stands for the list of all characters belonging to that class. Supported character classes:

  • alnum
  • alpha
  • blank
  • cntrl
  • digit
  • graph
  • lower
  • print
  • space
  • upper
  • punct
  • xdigit

These match characters using the macros specified in ctype. A character class may not be used as an endpoint of a range.

The character ~ at the beginning of a file name refers to home directories. Standing alone, i.e., ~, it expands to the invoker’s home directory as reflected in the value of the variable home. When followed by a name consisting of letters, digits, and - characters, the shell searches for a user with that name and substitutes their home directory; thus “~ken” might expand to “/usr/ken” and “~ken/chmach” to “/usr/ken/chmach”. If the character ~ is followed by a character other than a letter or /, or does not appear at the beginning of a word, it is left undisturbed.

The metanotation “a{b,c,d}e” is a shorthand for “abe ace ade”. Left to right order is preserved, with results of matches being sorted separately at a low level to preserve this order. This construct can be nested. Thus, “~source/s1/{oldls,ls}.c” expands to “/usr/source/s1/oldls.c /usr/source/s1/ls.c” without chance of error if the home directory for “source” is “/usr/source”. Similarly “../{memo,*box}” might expand to “../memo ../box ../mbox”. Note that “memo” was not sorted with the results of the match to “*box”. As a special case {, }, and {} are passed undisturbed.

Input/output

The standard input and the standard output of a command may be redirected with the following syntax:

A command receives the environment in which the shell was invoked as modified by the input-output parameters and the presence of the command in a pipeline. Thus, unlike some previous shells, commands run from a file of shell commands have no access to the text of the commands by default; instead they receive the original standard input of the shell. The « mechanism should be used to present inline data. This permits shell command scripts to function as components of pipelines and allows the shell to block read its input. Note that the default standard input for a command run detached is not modified to be the empty file /dev/null; instead the standard input remains as the original standard input of the shell. If this is a terminal and if the process attempts to read from the terminal, then the process blocks and the user is notified (see Jobs above).

The standard error output may be directed through a pipe with the standard output. Use the form |& instead of only |.

Expressions

Several of the built-in commands (to be described later) take expressions, in which the operators are similar to those of C, with the same precedence, but with the opposite grouping: right to left. These expressions appear in the @, exit, if, and while commands. The following operators are available:

  • ||
  • &&
  • |
  • &
  • ==
  • !=
  • =~
  • !~
  • <=
  • =

  • <
  • «
  • +
  • -
  • *
  • /
  • %
  • !
  • ~
  • (
  • )

Here the precedence increases down the list, with == != =~ and !~, <= >= < and >, « and », + and -, * / and % being, in groups, at the same level. The == != =~ and !~ operators compare their arguments as strings; all others operate on numbers. The operators =~ and !~ are like != and == except that the right side is a pattern (containing, e.g., *’s, ?’s, and instances of “[…]”) against which the left operand is matched. This reduces the need for use of the switch statement in shell scripts when all that is really needed is pattern matching.

Strings that begin with 0 are considered octal numbers. Null or missing arguments are considered 0. The results of all expressions are strings, which represent decimal numbers. It is important to note that no two components of an expression can appear in the same word; except when adjacent to components of expressions that are syntactically significant to the parser (&, |, <, >, (, and )), they should be surrounded by spaces.

Also available in expressions as primitive operands are command executions enclosed in { and } and file enquiries of the form -l name where l is one of:

The specified name is command and file name expanded and then tested to see if it has the specified relationship to the real user. If the file does not exist or is inaccessible then all enquiries return false, i.e., 0. Command executions succeed, returning true, i.e., 1, if the command exits with status 0, otherwise they fail, returning false, i.e., 0. If more detailed status information is required then the command should be executed outside an expression and the variable status examined.

Control flow

The shell contains several commands that can regulate the flow of control in command files (shell scripts) and (in limited but useful ways) from terminal input. These commands all operate by forcing the shell to reread or skip in its input and, because of the implementation, restrict the placement of some of the commands.

The foreach, switch, and while statements, and the if-then-else form of the if statement require that the major keywords appear in a single simple command on an input line as shown below.

If the shell’s input is not seekable, the shell buffers up input whenever a loop is being read and performs seeks in this internal buffer to accomplish the rereading implied by the loop. To the extent that this allows, backward goto’s succeed on non-seekable inputs.

Built-in commands

Built-in commands are executed in the shell. If a built-in command occurs as any component of a pipeline except the last then it is executed in a sub-shell.

Pre-defined and environment variables

The following variables have special meaning to the shell. Of these, argv, cwd, home, path, prompt, shell and status are always set by the shell. Except for cwd and status, this setting occurs only at initialization; these variables are not modified unless done explicitly by the user.

The shell copies the environment variable USER into the variable user, TERM into term, and HOME into home, and copies these back into the environment whenever the normal shell variables are reset. The environment variable PATH is likewise handled; it is not necessary to worry about its setting other than in the file .cshrc as inferior csh processes import the definition of path from the environment, and re-export it if you then change it.

Non-built-in command execution

When a command to be executed is found to not be a built-in command the shell attempts to execute the command via execve. Each word in the variable path names a directory where the shell attempts to execute the command. If it’s given neither a -c nor a -t option, the shell hashes the names in these directories to an internal table so that it only tries an exec in a directory if there is a possibility that the command resides there. This shortcut greatly speeds command location when many directories are present in the search path. If this mechanism is turned off (via unhash), or if the shell was given a -c or -t argument, and in any case for each directory component of path that does not begin with a /, the shell concatenates with the given command name to form a path name of a file which it then attempts to execute.

Parenthesized commands are always executed in a sub-shell. Thus

(cd; pwd); pwd

Prints the home directory; leaving you where you were (printing this after the home directory), while

cd; pwd

Leaves you in the home directory. Parenthesized commands are most often used to prevent chdir from affecting the current shell.

If the file has execute permissions but is not an executable binary to the system, then it is assumed to be a file containing shell commands and a new shell is spawned to read it.

If there is an alias for shell, then the words of the alias are prepended to the argument list to form the shell command. The first word of the alias should be the full path name of the shell (e.g., “$shell”). Note that this is a special, late occurring, case of alias substitution, and only allows words to be prepended to the argument list without change.

Signal handling

The shell normally ignores SIGQUIT signals. Jobs running detached (either by & or the bg or %… & commands) are immune to signals generated from the keyboard, including hangups. Other signals have the values which the shell inherited from its parent. The shell’s handling of interrupts and terminate signals in shell scripts can be controlled by onintr. Login shells catch the SIGTERM (terminate) signal; otherwise this signal is passed on to children from the state in the shell’s parent. Interrupts are not allowed when a login shell is reading the file .logout.

Limitations

Word lengths: Words can be no longer than 1024 characters. The number of arguments to a command that involves file name expansion is limited to 1/6th 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.

Files

Examples

csh

Executes and runs the C Shell (if present).

See the .cshrc guide for an example of the .cshrc file and additional information about this file.

bash — The Bourne Again shell command interpreter.bc — A calculator.echo — Output text.login — Begin a session on a system.ls — List the contents of a directory or directories.more — Display text one screen at a time.ps — Report the status of a process or processes.sh — The Bourne shell command interpreter.