On Unix-like operating systems, tcsh (pronounced “tee-see-shell” or “tee-see-ess-aysh”) is a command-line shell based on the C Shell. Its key features are programmable command completion and command-line editing.

Description

tcsh is an enhanced but completely compatible version of the Berkeley UNIX C shell, csh. It is a command language interpreter usable both as an interactive login shell and a shell script command processor. It includes a command-line editor (see The Command-Line Editor), programmable word completion (see Completion and Listing), spelling correction (see Spelling Correction), a history mechanism (see History substitution), job control (see Jobs) and a C programming language-like syntax.

  • Description
  • Syntax
  • Examples
  • Related commands
  • Linux commands help

History

tcsh was developed by Ken Greer beginning in the late 1970s at Carnegie Mellon University. The “t” in tcsh refers to TENEX, a DEC operating system featuring command-completion, which inspired Greer to create a shell with a similar feature. Work on tcsh continued with the collaboration of Mike Ellis at Fairchild A.I. Labs, and the source code for tsch was posted to a systems programming newsgroup in October 1983.

Syntax

tcsh [-bcdefFimnqstvVxX] [-Dname[=value]] [arg …]

tcsh -l

Options

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

The rest of the flag arguments are interpreted as follows:

After processing of flag arguments, 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 (script) to be executed. The shell opens this file and saves its name for possible resubstitution by “$0”. Because many systems use either the standard version 6 or version 7 shells whose shell scripts are not compatible with this shell, the shell uses such a “standard” shell to execute a script whose first character is not a “#”, i.e., that does not start with a comment.

Remaining arguments are placed in the argv shell variable.

Startup and shutdown

A login shell begins by executing commands from the system files /etc/csh.cshrc and /etc/csh.login. It then executes commands from files in the user’s home directory: first ~/.tcshrc or, if ~/.tcshrc is not found, ~/.cshrc, then ~/.history (or the value of the histfile shell variable), then ~/.login, and finally ~/.cshdirs (or the value of the dirsfile shell variable). The shell may read /etc/csh.login before instead of after /etc/csh.cshrc, and ~/.login before instead of after ~/.tcshrc or ~/.cshrc and ~/.history, if so compiled; see the version shell variable.

Non-login shells read-only /etc/csh.cshrc and ~/.tcshrc or ~/.cshrc on startup.

Check out the official Sourceforge page for examples of startup files.

Commands like stty and tset, which need run only once per login, usually go in one’s ~/.login file. Users who need to use the same set of files with both csh and tcsh can have only a ~/.cshrc which checks for the existence of the tcsh shell variable (q.v.) before using tcsh-specific commands, or can have both a ~/.cshrc and a ~/.tcshrc which sources (see the builtin command) ~/.cshrc. The rest of this manual uses “~/.tcshrc” to mean “~/.tcshrc” or, if ~/.tcshrc is not found, ~/.cshrc.

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 later. The shell repeatedly reads a line of command input, breaks it into words, places it on the command history list, parses it and executes each command in the line.

One can log out by typing “^D” on an empty line, “logout” or “login” or via the shell’s autologout mechanism (see the autologout shell variable). When a login shell terminates it sets the logout shell variable to “normal” or “automatic” as appropriate, then executes commands from the files /etc/csh.logout and ~/.logout. The shell may drop DTR on logout if so compiled; see the version shell variable.

The names of the system login and logout files vary from system to system for compatibility with different csh variants; see the Files section.

Editing

The command line editor

Command-line input can be edited using key sequences much like those used in GNU Emacs or vi. The editor is active only when the edit shell variable is set, which it is by default in interactive shells. The bindkey builtin can display and change key bindings. Emacs-style key bindings are used by default (unless the shell was compiled otherwise; see the version shell variable), but bindkey can change the key bindings to vi-style bindings en masse.

The shell always binds the arrow keys (as defined in the TERMCAP environment variable) to:

…unless doing so would alter another single-character binding. One can set the arrow key escape sequences to the empty string with settc to prevent these bindings. The ANSI/VT100 sequences for arrow keys are always bound.

Other key bindings are, for the most part, what Emacs and vi users would expect and can easily be displayed by bindkey, so there is no need to list them here. Likewise, bindkey can list the editor commands with a short description of each.

Note that editor commands do not have the same notion of a “word” as does the shell. The editor delimits words with any non-alphanumeric characters not in the shell variable wordchars, while the shell recognizes only whitespace and some of the characters with special meanings to it, listed under Lexical Structure.

Completion and listing

The shell is often able to complete words when given a unique abbreviation. Type part of a word (for example “ls /usr/lost”) and hit the Tab key to run the complete-word editor command. The shell completes the filename “/usr/lost” to “/usr/lost+found/”, replacing the incomplete word with the complete word in the input buffer. Note the “/” at the end; completion adds a “/” to the end of completed directories and a space to the end of other completed words, to speed typing and provide a visual indicator of successful completion. The addsuffix shell variable can be unset to prevent this. If no match is found (perhaps “/usr/lost+found” doesn’t exist), the terminal bell rings. If the word is already complete (perhaps there is a “/usr/lost” on your system, or perhaps you were thinking too far ahead and typed the whole thing) a “/” or space is added to the end if it isn’t already there.

set autolist

nm /usr/lib/libt[tab]

[email protected] [email protected]

nm /usr/lib/libterm

If autolist is set to “ambiguous”, choices are listed only when completion fails and adds no new characters to the word being completed.

A filename to be completed can contain variables, your or others’ home directories abbreviated with “~” (see Filename Substitution) and directory stack entries abbreviated with “=” (see Directory stack substitution). For example,

ls ~k[^D]

kahn kas kellogg

ls ~ke[tab]

ls ~kellogg/

…or for another example:

set local = /usr/local

ls $lo[tab]

ls $local/[^D]

bin/ etc/ lib/ man/ src/

ls $local/

Note that variables can also be expanded explicitly with the expand-variables editor command.

delete-char-or-list-or-eof lists at only the end of the line; in the middle of a line it deletes the character under the cursor and on an empty line it logs one out or, if ignoreeof is set, does nothing. “M-^D”, bound to the editor command list-choices, lists completion possibilities anywhere on a line, and list-choices (or any one of the related editor commands that do or don’t delete, list and/or log out, listed under delete-char-or-list-or-eof) can be bound to “^D” with the bindkey builtin command if so desired.

The complete-word-fwd and complete-word-back editor commands (not bound to any keys by default) can cycle up and down through the list of possible completions, replacing the current word with the next or previous word in the list.

The shell variable fignore can be set to a list of suffixes to be ignored by completion. Consider the following:

ls

Makefile condiments.h~ main.o side.c README main.c meal side.o condiments.h main.c~

set fignore = (.o ~)

emacs ma[^D]

main.c main.c~ main.o

emacs ma[tab]

emacs main.c

“main.c~” and “main.o” are ignored by completion (but not listing), because they end in suffixes in fignore. Note that a “" was needed in front of “~” to prevent it from being expanded to home as described under Filename substitution. fignore is ignored if only one completion is possible.

If the complete shell variable is set to “enhance”, completion ignores case and considers periods, hyphens and underscores (”.”, “-” and “_”) to be word separators and hyphens and underscores to be equivalent. If you had the following files

comp.lang.c comp.lang.perl comp.std.c++ comp.lang.c++ comp.std.c

and typed “mail -f c.l.c[tab]”, it would be completed to “mail -f comp.lang.c”, and ^D lists “comp.lang.c” and “comp.lang.c++”. “mail -f c..c++[^D]” lists “comp.lang.c++” and “comp.std.c++”. Typing “rm a–file[^D]” in the following directory

A_silly_file a-hyphenated-file another_silly_file

lists all three files, because case is ignored and hyphens and underscores are equivalent. Periods, however, are not equivalent to hyphens or underscores.

If the complete shell variable is set to “Enhance”, completion ignores case and differences between a hyphen and an underscore word separator only when the user types a lowercase character or a hyphen. Entering an uppercase character or an underscore will not match the corresponding lowercase character or hyphen word separator. Typing “rm a–file[^D]” in the directory of the previous example would still list all three files, but typing “rm A–file” would match only “A_silly_file” and typing “rm a__file[^D]” would match only “A_silly_file” and “another_silly_file” because the user explicitly used an uppercase or an underscore character.

Completion and listing are affected by other shell variables: recexact can be set to complete on the shortest possible unique match, even if more typing might result in a longer match:

fodder foo food foonly

set recexact

rm fo[tab]

only beeps, because “fo” could expand to “fod” or “foo”, but if we type another “o”,

rm foo[tab]

rm foo

the completion completes on “foo”, even though “food” and “foonly” also match. autoexpand can be set to run the expand-history editor command before each completion attempt, autocorrect can be set to spelling-correct the word to be completed (see Spelling Correction) before each completion attempt and correct can be set to complete commands automatically after one hits “return”. matchbeep can be set to make completion beep or not beep in a variety of situations, and nobeep can be set to never beep at all. nostat can be set to a list of directories and/or patterns that match directories to prevent the completion mechanism from stating those directories. listmax and listmaxrows can be set to limit the number of items and rows (respectively) that are listed without asking first. recognize_only_executables can be set to make the shell list only executables when listing commands, but it is quite slow.

Finally, the complete builtin command can tell the shell how to complete words other than filenames, commands and variables. Completion and listing do not work on glob-patterns (see Filename Substitution), but the list-glob and expand-glob editor commands perform equivalent functions for glob-patterns.

Spelling correction

The shell can sometimes correct the spelling of filenames, commands and variable names and completing and listing them.

Individual words can be spelling-corrected with the spell-word editor command (usually bound to M-s and M-S) and the entire input buffer with spell-line (usually bound to M-$). The correct shell variable can be set to “cmd” to correct the command name or “all” to correct the entire line each time return is typed, and autocorrect can be set to correct the word to be completed before each completion attempt.

When spelling correction is invoked in any of these ways and the shell thinks any part of the command line is misspelled, it prompts with the corrected line:

set correct = cmd

lz /usr/bin

CORRECT>ls /usr/bin (y|n|e|a)?

One can answer “y” or space to execute the corrected line, “e” to leave the uncorrected command in the input buffer, “a” to abort the command as if “^C” had been hit, and anything else to execute the original line unchanged.

Spelling correction recognizes user-defined completions (see the complete builtin command). If an input word in a position for which a completion is defined resembles a word in the completion list, spelling correction registers a misspelling and suggests the latter word as a correction. However, if the input word does not match any of the possible completions for that position, spelling correction does not register a misspelling.

Like completion, spelling correction works anywhere in the line, pushing the rest of the line to the right and possibly leaving extra characters to the right of the cursor.

Editor commands

“bindkey” lists key bindings and “bindkey -l” lists and briefly describes editor commands. Only new or especially interesting editor commands are described here. See emacs and vi for descriptions of each editor’s key bindings.

spelling correction is not guaranteed to work the way one intends, and is provided mostly as an experimental feature.

The character or characters that each command is bound by default is given in parentheses. “^character” means a control character and “M-character” a meta character, typed as escape-character on terminals without a meta key. Case counts, but commands that are bound to letters by default are bound to both lower and uppercase letters for convenience.

Lexical structure

The shell splits input lines into words at blanks and tabs. The special characters “&”, “|”, “;”, “<”, “>”, “(”, and “)” and the doubled characters “&&”, “||”, “«” and “»” are always separate words, whether or not they are surrounded by whitespace.

When the shell’s input is not a terminal, the character “#” is taken to begin a comment. Each “#” and the rest of the input line on which it appears is discarded before further parsing.

A special character (including a blank or tab) may be prevented from having its special meaning, and possibly made part of another word, by preceding it with a backslash (”") or enclosing it in single (’), double (") or backtick (`) quotes. When not otherwise quoted a newline preceded by a “" is equivalent to a blank, but inside quotes this sequence results in a newline.

Furthermore, all Substitutions except History substitution can be prevented by enclosing the strings (or parts of strings) where they appear with single quotes or by quoting the crucial character(s) (e.g., “$” or “`” for Variable Substitution or Command Substitution respectively) with “". Alias substitution is no exception: quoting in any way any character of a word for which an alias is defined prevents substitution of the alias. The usual way of quoting an alias is to precede it with a backslash. History substitution is prevented by backslashes but not by single quotes. Strings quoted with double or backward quotes undergo Variable substitution and Command substitution, but other substitutions are prevented.

Text inside single or double quotes becomes a single word (or part of one). Metacharacters in these strings, including blanks and tabs, do not form separate words. Only in one special case (see Command Substitution below) can a double-quoted string yield parts of more than one word; single-quoted strings never do. Backward quotes (backticks) are special: they signal Command substitution, which may result in more than one word.

Quoting complex strings, particularly strings which themselves contain quoting characters, can be confusing. Remember that quotes need not be used as they are in human writing. It may be easier to quote not an entire string, but only those parts of the string which need quoting, using different types of quoting to do so if appropriate.

The backslash_quote shell variable can be set to make backslashes always quote “", “’”, and “””. This may make complex quoting tasks easier, but it can cause syntax errors in csh scripts.

Substitutions

History substitution

Each command, or “event”, input from the terminal is saved in the history list. The previous command is always saved, and the history shell variable can be set to a number to save that many commands. The histdup shell variable can be set to not save duplicate events or consecutive duplicate events.

Saved commands are numbered sequentially from 1 and stamped with the time. It is not usually necessary to use event numbers, but the current event number can be made part of the prompt by placing an “!” in the prompt shell variable.

The shell actually saves history in expanded and literal (unexpanded) forms. If the histlit shell variable is set, commands that display and store history use the literal form.

The history builtin command can print, store in a file, restore and clear the history list at any time, and the savehist and histfile shell variables can be set to store the history list automatically on logout and restore it on login.

History substitutions introduce words from the history list into the input stream, 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 “!”. They may begin anywhere in the input stream, but they do not nest. The “!” may be preceded by a “" to prevent its special meaning; for convenience, a “!” 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 will be described later. The characters used to signal history substitution (”!” and ^) can be changed by setting the histchars shell variable. Any input line which contains a history substitution is printed before it is executed.

A history substitution may have an “event specification”, which indicates the event from which words are to be taken, a “word designator”, which selects particular words from the chosen event, and/or a “modifier”, which manipulates the selected words.

An event specification can be:

For example, consider this bit of someone’s history list:

9 8:30 nroff -man wumpus.man 10 8:31 cp wumpus.man wumpus.man.old 11 8:36 vi wumpus.man 12 8:37 diff wumpus.man.old wumpus.man

The commands are shown with their event numbers and timestamps. The current event, which we haven’t typed in yet, is event 13. “!11” and “!-2” refer to event 11. “!!” refers to the previous event, 12. “!!” can be abbreviated “!” if it’s followed by “:” (”:" is described below). “!n” refers to event 9, which begins with “n”. “!?old?” also refers to event 12, which contains “old”. Without word designators or modifiers history references expand to the entire event, so we might type “!cp” to redo the copy command or “!!|more” if the “diff” output scrolled off the top of the screen.

History references may be insulated from the surrounding text with braces if necessary. For example, “!vdoc” would look for a command beginning with “vdoc”, and, in this example, not find one, but “!{v}doc” would expand unambiguously to “vi wumpus.mandoc”. Even in braces, history substitutions do not nest.

While csh expands, for example, !3d to event 3 with the letter d appended to it, tcsh expands it to the last event beginning with 3d; only completely numeric arguments are treated as event numbers. This makes it possible to recall events beginning with numbers. To expand !3d as in csh say !{3}d.

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:

Selected words are inserted into the command line separated by single blanks. For example, the “diff” command in the previous example might have been typed as “diff !!:1.old !!:1” (using “:1” to select the first argument from the previous event) or “diff !-2:2 !-2:1” to select and swap the arguments from the “cp” command. If we didn’t care about the order of the “diff” we might have said “diff !-2:1-2” or “diff !-2:*”. The “cp” command might have been written “cp wumpus.man !#:1.old”, using “#” to refer to the current event. “!n:- hurkle.man” would reuse the first two words from the “nroff” command to say “nroff -man hurkle.man”.

The “:” separating the event specification from the word designator can be omitted if the argument selector begins with a “^”, “$”, “*”, “%” or “-”. For example, our “diff” command might have been “diff !!^.old !!^” or, equivalently, “diff !!$.old !!$”. However, if “!!” is abbreviated “!”, an argument selector beginning with “-” will be interpreted as an event specification.

A history reference may have a word designator but no event specification. It then references the previous command. Continuing our “diff” example, we could have said “diff !^.old !^” or, to get the arguments in the opposite order, only “diff !*”.

The word or words in a history reference can be edited, or “modified”, by following it with one or more modifiers, each preceded by a “:”:

Modifiers are applied to only the first modifiable word (unless “g” is used). It is an error for no word to be modifiable.

For example, the “diff” command might have been written as “diff wumpus.man.old !#^:r”, using “:r” to remove “.old” from the first argument on the same line ("!#^"). We could say “echo hello out there”, then “echo !:u” to capitalize “hello”, “echo !:au” to say it out loud, or “echo !*:agu” to really shout. We might follow “mail -s ‘I forgot my password’ rot” with “!:s/rot/root” to correct the spelling of “root” (but see Spelling correction for a different approach).

There is a special abbreviation for substitutions. “^”, when it is the first character on an input line, is equivalent to “!:s^”. Thus we might have said “^rot^root” to make the spelling correction in the previous example. This is the only history substitution which does not explicitly begin with “!”.

In csh as such, only one modifier may be applied to each history or variable expansion. In tcsh, more than one may be used, for example

% mv wumpus.man /usr/man/man1/wumpus.1

% man !$:t:r

man wumpus

In csh, the result would be “wumpus.1:r”. A substitution followed by a colon may need to be insulated from it with braces:

mv a.out /usr/games/wumpus

setenv PATH !$:h:$PATH

Bad ! modifier: $.

setenv PATH !{-2$:h}:$PATH

setenv PATH /usr/games:/bin:/usr/bin:.

The first attempt would succeed in csh but fails in tcsh, because tcsh expects another modifier after the second colon rather than “$”.

Finally, history can be accessed through the editor and through the substitutions only described. The up- and down-history, history-search-backward and -forward, i-search-back and -fwd, vi-search-back and -fwd, copy-prev-word and insert-last-word editor commands search for events in the history list and copy them into the input buffer. The toggle-literal-history editor command switches between the expanded and literal forms of history lines in the input buffer. expand-history and expand-line expand history substitutions in the current word andF in the entire input buffer respectively.

Alias substitution

The shell maintains a list of aliases which can be set, unset and printed by the alias and unalias commands. After a command line is parsed into simple commands (see Commands) the first word of each command, left-to-right, is checked to see if it has an alias. If so, the first word is replaced by the alias. If the alias contains a history reference, it undergoes History substitution as though the original command were the previous input line. If the alias does not contain a history reference, the argument list is left untouched.

Thus if the alias for “ls” were “ls -l” the command “ls /usr” would become “ls -l /usr”, the argument list here being undisturbed. If the alias for “lookup” were “grep !^ /etc/passwd” then “lookup bill” would become “grep bill /etc/passwd”. Aliases can introduce parser metasyntax. For example, “alias print ‘pr !* | lpr’” defines a “command” (“print”) which prs its arguments to the line printer.

Alias substitution is repeated until the first word of the command has no alias. If an alias substitution does not change the first word (as in the previous example) it is flagged to prevent a loop. Other loops are detected and cause an error.

Some aliases are referred to by the shell; see Special Aliases.

Variable substitution

The shell maintains a list of variables, each of which has as value a list of zero or more words. The values of shell variables can be displayed and changed with the set and unset commands. The system maintains its own list of environment variables. These can be displayed and changed with printenv, setenv and unsetenv.

Variables may be made read-only with “set -r”. Read-only variables may not be modified or unset; attempting to do so causes an error. Once made read-only, a variable cannot be made writable, so “set -r” should be used with caution. Environment variables cannot be made read-only.

Some variables are set by the shell or referred to by it. For instance, the argv variable is an image of the shell’s argument list, and words of this variable’s value are referred to in special ways. Some of the variables referred to by the shell 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 which causes command input to be echoed. The -v command line option sets this variable. Special shell variables lists all variables that are referred to by the shell.

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 subsequent words of multi-word 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 “s where it always occurs, and within ’s where it never occurs. Strings quoted by ` 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 described under History Substitution, except for “:p”, can be applied to the substitutions above. More than one may be used. Braces may be needed to insulate a variable substitution from a literal colon only as with History substitution; any modifiers must appear in the braces.

The following substitutions cannot be modified with “:” modifiers.

The editor command expand-variables, normally bound to “^X-$”, can interactively expand individual variables.

Command substitution

Command substitution is indicated by a command enclosed in backquotes (``). The output from suwch a command is broken into separate words at blanks, tabs and newlines, and null words are discarded. The output is variable and command substituted and put in place of the original string.

Command substitutions inside double quotes (”) retain blanks and tabs; only newlines force new words. The single final newline does not force a new word in any case. It is thus possible for a command substitution to yield only part of a word, even if the command outputs a complete line.

By default, the shell replaces all newline and carriage return characters in the command by spaces. If this is switched off by unsetting csubstnonl, newlines separate commands as usual.

Filename substitution

If a word contains any of the characters “*”, “?”, “[” or “{” or begins with the character “~” it is a candidate for filename substitution, also known as “globbing”. This word is then regarded as a pattern (“glob-pattern”), and replaced with an alphabetically sorted list of file names which match the pattern.

In matching file names, the character “.” at the beginning of a file name or immediately following a “/”, and the character “/” must be matched explicitly (unless either globdot or globstar or both are set). 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.

Some glob-patterns can be negated: The sequence “[^…]” matches any single character not specified by the characters and/or ranges of characters in the braces.

An entire glob-pattern can also be negated with “^”:

echo *

bang crash crunch ouch

echo ^cr*

bang ouch

Glob-patterns which do not use “?”, “*”, or “[]” or which use “{}” or “~” (below) are not negated correctly.

The metanotation “a{b,c,d}e” is a shorthand for “abe ace ade”. Left-to-right order is preserved: “/usr/source/s1/{oldls,ls}.c” expands to “/usr/source/s1/oldls.c /usr/source/s1/ls.c”. The results of matches are sorted separately at a low level to preserve this order: “../{memo,*box}” might expand to “../memo ../box ../mbox”. Note that “memo” was not sorted with the results of matching “*box”. It is not an error when this construct expands to files which do not exist, but it is possible to get an error from a command that the expanded list is passed. This construct may be nested. As a special case the words “{”, “}” and “{}” are passed undisturbed.

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 home shell variable. 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 appears elsewhere than at the beginning of a word, it is left undisturbed. A command like “setenv MANPATH /usr/man:/usr/local/man:~/lib/man” does not, therefore, do home directory substitution as one might hope.

It is an error for a glob-pattern containing “*”, “?”, “[” or “~”, with or without “^”, not to match any files. However, only one pattern in a list of glob-patterns must match a file (so that, e.g., “rm *.a *.c *.o” would fail only if there were no files in the current directory ending in “.a”, “.c”, or “.o”), and if the nonomatch shell variable is set a pattern (or list of patterns) which matches nothing is left unchanged rather than causing an error.

The globstar shell variable can be set to allow “” or “” as a file glob pattern that matches any string of characters including “/”, recursively traversing any existing sub-directories. For example, “ls .c” lists all the .c files in the current directory tree. If used by itself, it will match zero or more sub-directories (e.g., “ls /usr/include//time.h” lists any file named “time.h” in the /usr/include directory tree; “ls /usr/include/time.h” will match any file in the /usr/include directory tree ending in “time.h”; and “ls /usr/include/time.h” will match any .h file with “time” either in a subdirectory name or in the file name itself). To prevent problems with recursion, the “” glob-pattern will not descend into a symbolic link containing a directory. To override this, use “**”

The noglob shell variable can be set to prevent substitution, and the expand-glob editor command, normally bound to “^X-*”, can interactively expand individual file name substitutions.

Directory stack substitution

The directory stack is a list of directories, numbered from zero, used by the pushd, popd and dirs builtin commands. dirs can print, store in a file, restore and clear the directory stack at any time, and the savedirs and dirsfile shell variables can be set to store the directory stack automatically on logout and restore it on login. The dirstack shell variable can be examined to see the directory stack and set to put arbitrary directories into the directory stack.

The character “=” followed by one or more digits expands to an entry in the directory stack. The special case “=-” expands to the last directory in the stack. For example,

dirs -v

0 /usr/bin 1 /usr/spool/uucp 2 /usr/accts/sys

echo =1

/usr/spool/uucp

echo =0/calendar

/usr/bin/calendar

echo =-

/usr/accts/sys

The noglob and nonomatch shell variables and the expand-glob editor command apply to directory stack and file name substitutions.

Other substitutions

There are several more transformations involving file names, not strictly related to the above but mentioned here for completeness. Any file name may be expanded to a full path when the symlinks variable is set to “expand”. Quoting prevents this expansion, and the normalize-path editor command does it on demand. The normalize-command editor command expands commands in PATH into full paths on demand. Finally, cd and pushd interpret “-” as the old working directory (equivalent to the shell variable owd). This is not a substitution at all, but an abbreviation recognized by only those commands. Nonetheless, it too can be prevented by quoting.

Commands

The next three sections describe how the shell executes commands and deals with their input and output.

Simple commands, pipelines and sequences

A simple command is a sequence of words, the first of which specifies the command to be executed. A series of simple commands joined by “|” characters forms a pipeline. The output of each command in a pipeline is connected to the input of the next.

Simple commands and pipelines may be joined into sequences with “;”, and will be executed sequentially. Commands and pipelines can also be joined into sequences with “||” or “&&”, indicating, as in the C language, that the second is to be executed only if the first fails or succeeds respectively.

A simple command, pipeline or sequence may be placed in parentheses, “()”, to form a simple command, which may in turn be a component of a pipeline or sequence. A command, pipeline or sequence can be executed without waiting for it to terminate by following it with an “&”.

Builtin and non-builtin command execution

Builtin commands are executed in the shell. If any component of a pipeline except the last is a builtin command, the pipeline is executed in a subshell.

Parenthesized commands are always executed in a subshell.

(cd; pwd); pwd

This command 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 often used to prevent cd from affecting the current shell.

When a command to be executed is found not to be a builtin command the shell attempts to execute the command via the execve system command. Each word in the variable path names a directory where the shell looks for the command. If the shell is not given a -f option, the shell hashes the names in these directories into an internal table so that it will try an execve in only a directory where there is a possibility that the command resides there. This greatly speeds command location when a large number of directories are present in the search path. This hashing mechanism is not used:

  • If hashing is turned explicitly off via unhash.
  • If the shell was given a -f argument.
  • For each directory component of path which does not begin with a “/”.
  • If the command contains a “/”.

In the above four cases the shell concatenates each component of the path vector with the given command name to form a path name of a file which it then attempts to execute it. If execution is successful, the search stops.

If the file has execute permissions but is not an executable to the system (i.e., it is neither an executable binary nor a script that specifies its interpreter), then it is assumed to be a file containing shell commands and a new shell is spawned to read it. The shell special alias may be set to specify an interpreter other than the shell itself.

On systems which do not understand the “#!” script interpreter convention the shell may be compiled to emulate it; see the version shell variable. If so, the shell checks the first line of the file to see if it’s of the form “#!interpreter arg …”. If it is, the shell starts the interpreter with the given args and feeds the file to it on standard input.

Input/output

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

A command receives the environment where 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; rather 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 the empty file /dev/null, but 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 will be notified (see Jobs).

Diagnostic output may be directed through a pipe with the standard output. Use the form “|&” rather than only “|”.

The shell cannot presently redirect diagnostic output without also redirecting standard output, but “(command > output-file) >& error-file” is often an acceptable workaround. Either output-file or error-file may be “/dev/tty” to send output to the terminal.

Features

Control flow

The shell contains many commands which 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, due to 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 gotos will succeed on non-seekable inputs.

Expressions

The if, while and exit builtin commands use expressions with a common syntax. The expressions can include any of the operators described in the next three sections. Note that the @ builtin command has its own separate syntax.

Logical, arithmetical and comparison operators

These operators are similar to those of C and have the same precedence. They include:

|| && | ^ &

!= =~ !~ <=

= <

«

+

* / % ! ~ ( )

Here the precedence increases down the list, “==” “!=” “=~” 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 glob-pattern (see Filename Substitution) against which the left operand is matched. This reduces the need for use of the switch builtin command in shell scripts when all that is really needed is pattern matching.

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 (”&” “|” “<” “>” “(” “)”) they should be surrounded by spaces.

Command exit status

Commands can be executed in expressions and their exit status returned by enclosing them in braces ("{}"). Remember that the braces should be separated from the words of the command by spaces. 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 of an expression and the status shell variable examined.

File inquiry operators

Some of these operators perform true/false tests on files and related objects. They are of the form -op file, where op is one of the following:

file is command- and filename-expanded and then tested to see if it has the specified relationship to the real user. If file does not exist or is inaccessible or, for the operators indicated by “*”, if the specified file type does not exist on the current system, then all enquiries return false, i.e., “0”.

These operators may be combined for conciseness: “-xy file” is equivalent to “-x file && -y file”. For example, “-fx” is true (returns “1”) for plain executable files, but not for directories.

L may be used in a multiple-operator test to apply subsequent operators to a symbolic link rather than to the file that the link points. For example, “-lLo” is true for links owned by the invoking user. Lr, Lw and Lx are always true for links and false for non-links. L has a different meaning when it is the last operator in a multiple-operator test; see below.

It is possible but not useful, and sometimes misleading, to combine operators which expect file to be a file with operators which do not (e.g., X and t). Following L with a non-file operator can lead to particularly strange results.

Other operators return other information, i.e., not only “0” or “1”. They have the same format as before; op may be one of

Only one of these operators may appear in a multiple-operator test, and it must be the last. Note that L has a different meaning at the end of and elsewhere in a multiple-operator test. Because “0” is a valid return value for many of these operators, they do not return “0” when they fail: most return “-1”, and F returns “:”.

If the shell is compiled with POSIX defined (see the version shell variable), the result of a file inquiry is based on the permission bits of the file and not on the result of the access system call. For example, if one tests a file with -w whose permissions would ordinarily allow writing but that is on a file system mounted read-only, the test will succeed in a POSIX shell but fail in a non-POSIX shell.

File inquiry operators can also be evaluated with the filetest builtin command.

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 which looks like

[1] 1234

indicating 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 the suspend key (usually ^Z), which sends a STOP signal to the current job. The shell will then normally indicate that the job was “Suspended” and print another prompt. If the listjobs shell variable is set, all jobs are listed like the jobs builtin command; if it’s set to “long” the listing will be in long format, like “jobs -l”. You can then manipulate the state of the suspended job. You can put it in the “background” with the bg command or run some other commands and eventually bring the job back into the “foreground” with fg. (See also the run-fg-editor editor command.) A “^Z” takes effect immediately and is like an interrupt in that pending output and unread input are discarded when it is typed. The wait builtin command causes the shell to wait for all background jobs to complete.

The “^]” key sends a delayed suspend signal, which does not generate a STOP signal until a program attempts to read it, to the current job. This can usefully be typed ahead when you have prepared some commands for a job which you want to stop after it has read them. The “^Y” key performs this function in csh; in tcsh, “^Y” is an editing command.

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; thus “%1” is a synonym for “fg %1”, bringing job 1 back into the foreground. Similarly, saying “%1 &” resumes job 1 in the background, like “bg %1”. A job can also be named by an unambiguous prefix of the string typed in to start it: “%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” to specify 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 the output of jobs, the current job is marked with a “+” and the previous job with a “-”. The abbreviations “%+”, “%”, and (by analogy with the syntax of the history mechanism) “%%” all refer to the current job, and “%-” refers to the previous job.

The job control mechanism requires that the stty option “new” be set on some systems. 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 and the setty builtin command 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 will notify you immediately of changes of status in background jobs. There is also a shell command notify which marks a single process so that its status changes will be 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 will be warned that “There are suspended jobs.” You may use the jobs command to see what they are. If you do this or immediately try to exit again, the shell will not warn you a second time, and the suspended jobs will be terminated.

Automatic, periodic and timed events

There are various ways to run commands and take other actions automatically at various times in the “life cycle” of the shell. They are summarized here, and described in detail under the appropriate Builtin Commands, Special Shell Variables and Special Aliases.

The sched builtin command puts commands in a scheduled-event list, to be executed by the shell at a given time.

The beepcmd, cwdcmd, periodic, precmd, postcmd, and jobcmd Special aliases can be set, respectively, to execute commands when the shell wants to ring the bell, when the working directory changes, every tperiod minutes, before each prompt, before each command gets executed, after each command gets executed, and when a job is started or is brought into the foreground.

The autologout shell variable can be set to log out or lock the shell after a given number of minutes of inactivity.

The mail shell variable can be set to check for new mail periodically.

The printexitvalue shell variable can be set to print the exit status of commands which exit with a status other than zero.

The rmstar shell variable can be set to ask the user, when “rm *” is typed, if that is really what was meant.

The time shell variable can be set to execute the time builtin command after the completion of any process that takes more than a given number of CPU seconds.

The watch and who shell variables can be set to report when selected users log in or out, and the log builtin command reports on those users at any time.

Native language system support

The shell is eight bit clean (if so compiled; see the version shell variable) and thus supports character sets needing this capability. NLS support differs depending on whether or not the shell was compiled to use the system’s NLS (again, see version). In either case, 7-bit ASCII is the default character code (e.g., the classification of which characters are printable) and sorting, and changing the LANG or LC_CTYPE environment variables causes a check for possible changes in these respects.

When using the system’s NLS, the setlocale function is called to determine appropriate character code/classification and sorting (e.g., a “en_CA.UTF-8” would yield “UTF-8” as a character code). This function often examines the LANG and LC_CTYPE environment variables; refer to the system documentation for further details. When not using the system’s NLS, the shell simulates it by assuming that the ISO 8859-1 character set is used whenever either of the LANG and LC_CTYPE variables are set, regardless of their values. Sorting is not affected for the simulated NLS.

Also, with both real and simulated NLS, all printable characters in the range \200-\377, i.e., those that have M-char bindings, are automatically rebound to self-insert-command. The corresponding binding for the escape-char sequence, if any, is left alone. These characters are not rebound if the NOREBIND environment variable is set. This may be useful for the simulated NLS or a primitive real NLS which assumes full ISO 8859-1. Otherwise, all M-char bindings in the range \240-\377 are effectively undone. Explicitly rebinding the relevant keys with bindkey is of course still possible.

Unknown characters (i.e., those that are neither printable nor control characters) are printed in the format \nnn. If the tty is not in 8 bit mode, other 8 bit characters are printed by converting them to ASCII and using standout mode. The shell never changes the 7/8 bit mode of the tty and tracks user-initiated changes of 7/8 bit mode. NLS users (or, for that matter, those who want to use a meta key) may need to explicitly set the tty in 8 bit mode through the appropriate stty command in, e.g., the ~/.login file.

OS variant support

Some new builtin commands are provided to support features in particular operating systems. All are described in detail in the Builtin Commands section.

On systems that support TCF (aix-ibm370, aix-ps2), getspath and setspath get and set the system execution path, getxvers and setxvers get and set the experimental version prefix and migrate migrates processes between sites. The jobs builtin prints the site on which each job is executing.

Under BS2000, bs2cmd executes commands of the underlying BS2000/OSD operating system.

Under Domain/OS, inlib adds shared libraries to the current environment, rootnode changes the rootnode and ver changes the systype.

Under Mach, setpath is equivalent to Mach’s setpath.

Under Masscomp/RTU and Harris CX/UX, universe sets the universe.

Under Harris CX/UX, ucb or att runs a command under the specified universe.

Under Convex/OS, warp prints or sets the universe.

The VENDOR, OSTYPE and MACHTYPE environment variables indicate respectively the vendor, operating system and machine type (microprocessor class or machine model) of the system on which the shell thinks it is running. These are particularly useful when sharing one’s home directory between several types of machines; one can, for example,

set path = (~/bin.$MACHTYPE /usr/ucb /bin /usr/bin .)

in one’s ~/.login and put executables compiled for each machine in the appropriate directory.

The version shell variable indicates what options were chosen when the shell was compiled.

Note also the newgrp builtin, the afsuser and echo_style shell variables and the system-dependent locations of the shell’s input files (see Files).

Signal handling

Login shells ignore interrupts when reading the file ~/.logout. The shell ignores quit signals unless started with -q. Login shells catch the terminate signal, but non-login shells inherit the terminate behavior from their parents. Other signals have the values which the shell inherited from its parent.

In shell scripts, the shell’s handling of interrupt and terminate signals can be controlled with onintr, and its handling of hangups can be controlled with hup and nohup.

The shell exits on a hangup (see also the logout shell variable). By default, the shell’s children do too, but the shell does not send them a hangup when it exits. hup arranges for the shell to send a hangup to a child when it exits, and nohup sets a child to ignore hangups.

Terminal management

The shell uses three different sets of terminal (“tty”) modes: “edit”, used when editing, “quote”, used when quoting literal characters, and “execute”, used when executing commands. The shell holds some settings in each mode constant, so commands which leave the tty in a confused state do not interfere with the shell. The shell also matches changes in the speed and padding of the tty. The list of tty modes that are kept constant can be examined and modified with the setty builtin. Note that although the editor uses CBREAK mode (or its equivalent), it takes typed-ahead characters.

The echotc, settc and telltc commands can manipulate and debug terminal capabilities from the command line.

On systems that support SIGWINCH or SIGWINDOW, the shell adapts to window resizing automatically and adjusts the environment variables LINES and COLUMNS if set. If the environment variable TERMCAP contains li# and co# fields, the shell adjusts them to reflect the new window size.

Builtin commands

Special aliases

If set, each of these aliases executes automatically at the indicated time. They are all initially undefined.

complete cd ‘p/1/d/’

co[^D]

complete compress

complete -co* ‘p/0/(compress)/’

co[^D]

compress

complete find ’n/-user/u/’

complete cc ‘c/-I/d/’

complete alias ‘p/1/a/’

complete man ‘p/*/c/’

complete set ‘p/1/s/’

complete true ‘p/1/x:Truth has no options./’

complete ftp ‘p/1/$hostnames/’

set hostnames = (rtfm.mit.edu tesla.ee.cornell.edu)

ftp [^D]

rtfm.mit.edu tesla.ee.cornell.edu

ftp [^C]

set hostnames = (rtfm.mit.edu tesla.ee.cornell.edu uunet.uu.net)

rtfm.mit.edu tesla.ee.cornell.edu uunet.uu.net

complete kill ‘p/*/ps | awk \{print\ \$1\}/’

kill -9 [^D]

23113 23377 23380 23406 23429 23529 23530 PID

complete dbx ‘p/2/(core)/’ ‘p/*/c/’

complete cc ‘p//f:.[cao]/’

complete rm ‘p//f:^.{c,h,cc,C,tex,1,man,l,y}/’

complete elm [email protected][email protected]:$HOME/Mail/@

complete finger ‘c/*@/$hostnames/’ ‘p/1/u/@’

complete find
’n/-name/f/’ ’n/-newer/f/’ ’n/-{,n}cpio/f/’
’n/-exec/c/’ ’n/-ok/c/’ ’n/-user/u/’
’n/-group/g/’ ’n/-fstype/(nfs 4.2)/’
’n/-type/(b c d f l p s)/’
‘c/-/(name newer cpio ncpio exec ok user
group fstype type atime ctime depth inum
ls mtime nogroup nouser perm print prune
size xdev)/’
‘p/*/d/’

set history=echotc lines

@ history–

set tosl="echotc ts 0"

set frsl="echotc fs"

echo -n “$tosl”;date; echo -n “$frsl”

sched 11:00 echo It's eleven o'clock.

sched 5pm set prompt=’[%h] It's after 5; go home’

sched +2:15 /usr/lib/uucp/uucico -r1 -sother

sched

1 Wed Apr 4 15:42 /usr/lib/uucp/uucico -r1 -sother2 Wed Apr 4 17:00 set prompt=[%h] It’s after 5; go home

sched -2

1 Wed Apr 4 15:42 /usr/lib/uucp/uucico -r1 -sother

Special shell variables

The variables described in this section have special meaning to the shell. The shell sets addsuffix, argv, autologout, csubstnonl, command, echo_style, edit, gid, group, home, loginsh, oid, path, prompt, prompt2, prompt3, shell, shlvl, tcsh, term, tty, uid, user and version at startup; they do not change after that unless changed by the user. The shell updates cwd, dirstack, owd and status when necessary, and sets logout on logout.

alias cwdcmd ’echo -n “^[]2;${HOST}:$cwd ^G”’

alias cwdcmd ’echo -n “^[]2;${HOST}:$cwd^G^[]1;${HOST}^G”’

alias jobcmd ’echo -n “^[]2;!#:q^G”’

alias helpcommand ‘!:1 –help’

set tperiod = 30

alias periodic checknews

alias precmd date

alias postcmd ’echo -n “^[]2;!#:q^G”’

The shell synchronizes group, home, path, shlvl, term and user with the environment variables of the same names: whenever the environment variable changes the shell changes the corresponding shell variable to match (unless the shell variable is read-only) and vice versa. Note that although cwd and PWD have identical meanings, they are not synchronized in this manner, and that the shell automatically interconverts the different formats of path and PATH.

Environment

Files

Examples

To start tcsh from within another shell, run the command:

echo pwd $argv > ~/._pause; %

set dspmbyte = 0000….(256 bytes)….0000

set prompt = “%m [%h] %B[%@]%b [%/] you rang? "

tut [37] [2:54pm] [/usr/accts/sys] you rang? _

cd /tmp

mkdir from from/src to

ln -s from/src to/dst

cd /tmp/to/dst; echo $cwd

/tmp/to/dst

cd ..; echo $cwd

/tmp/from

/tmp/from/src

/tmp/to

cd “..”; echo $cwd

/bin/echo ..

/bin/echo “..”

..

set watch = (george ttyd1 any console $user any)

set watch = (1 any any)

tcsh

Now let’s write a simple tcsh script, and run it.

Let’s begin by creating a new file with the vi editor. Let’s call it “fileinfo”:

vi fileinfo

This will launch the vi editor and place you in a new file called fileinfo. (For more info about vi, see our vi documentation). Press i to enter insert mode, and enter the following script:

#!/bin/tcsh

Usage: fileinfo name

If there are no arguments, print a help message.

if ( $#argv == 0 ) then echo “Usage: fileinfo name” exit endif

If the first argument is not a file that exists, exit.

if ( ! -e $1 ) then echo “Error: File $1 does not exist” exit endif

List ls file info:

echo "” echo “File list info:” ls -l $1 # list file info

Show how many lines in the file:

echo "" echo “Numer of lines:” wc -l $1 # count words in this file

And what type of file it is:

echo "" echo “File type:” file $1

When you’re done, press Esc to exit insert mode, and type the command :w to save the file. You can then type :q to exit vi.

The script above takes a file name as an argument, and prints information about that file, including how many lines in the file (using the wc command), and what type of file it is (using the file command).

Let’s make the script executable with the chmod command:

chmod +x fileinfo

… and now let’s test it, by getting information about the script file itself. As always since the script we want to run is not in our PATH environment variable, we run the file by prefixing it with the directory name: in this case, the current directory, “./”. As our argument, we specify the script name (which does not need the directory prefix).

./fileinfo fileinfo

And here is the output:

File list info: -rwxr-xr-x 1 username username 315 May 21 09:42 fileinfo Numer of lines: 19 fileinfo File type: fileinfo: Tenex C shell script, ASCII text executable

bash — The Bourne Again shell command interpreter.csh — The C shell command interpreter.ksh — The Korn shell command interpreter.sh — The Bourne shell command interpreter.