csh(1) — Commands
OSF
NAME
csh − C shell command interpreter
SYNOPSIS
csh [-bcefinstvVxX] [argument ...]
The csh command invokes the C shell and interprets C shell commands.
FLAGS
All listed flags can be specified together, but their effects might not be compatible.
−bForces a break from option processing, causing any further shell arguments to be treated as non-option arguments. This can be used to pass options to a shell script without confusion or possible subterfuge. The shell cannot run a set-user-ID script without this flag.
−cReads commands from the (single) following argument, which must be present. Any remaining arguments are placed in argv.
−eCauses the shell to exit if any invoked command terminates abnormally or yields a nonzero exit status.
−fCauses the shell to start faster, because it neither searches for nor executes commands from the .cshrc file in the invoker’s home directory.
−iCauses the shell to be interactive and prompts for its top-level input, even if it does not appear to be coming from a terminal. Shells are interactive without this flag if their input and output are attached to terminals.
−nParses commands, but does not execute them. This aids in syntactic checking of shell scripts.
−sTakes command input from the standard input.
−tReads and executes a single line of input. You can use a \ (backslash) to escape the newline character at the end of the current line to continue onto another line.
−vSets the verbose shell variable, with the effect that command input is echoed after history substitution.
−VSets the verbose shell variable, even before .cshrc is executed.
−xSets the echo shell variable, so that commands are echoed immediately before execution.
−XSets the echo shell variable, even before .cshrc is executed.
After processing of flag arguments, if arguments remain but none of the −c, −i, −s, or −t flags was given, the first argument is taken as the name of a file of commands to be executed (i.e., a shell script). The shell opens this file, and saves its name for possible resubstitution by $0. If the first characters of the shell procedure are #!/usr/bin/csh, csh runs the specified shell to process the procedure. Otherwise, csh runs the C shell (csh). Remaining parameters initialize the argv variable.
DESCRIPTION
The C shell is an interactive command interpreter and a command programming language that uses a syntax similar to the C programming language. The shell carries out commands either from a file (called a shell script or procedure) or interactively from a terminal keyboard.
When you run csh, it begins by executing commands from the file .cshrc in your home directory, if it exists. If csh runs as a login shell, it executes commands from your $HOME/.cshrc file and your $HOME/.login file in that order. (If argument zero ($0) to the shell is a − (dash), then the shell is a login shell.)
In the normal case, the shell begins reading commands from the terminal, prompting with % (percent sign). Processing of arguments and the use of the shell to process files containing command scripts is described later.
The shell then repeatedly performs the following actions:
1.A line of command input is read and broken into words.
2.This sequence of words is placed on the command history list and then parsed.
3.Each command in the current line is executed.
When a login shell terminates, it executes commands from the file .logout in your home directory.
Shell Features
•Job control and status reporting
•Filename completion
•History substitution
•Command aliasing
•Variable substitution
•Command substitution
•Filename substitution
•Input/output redirection and control flow
•Built-in commands
Lexical Structure
A simple command is a sequence of words separated by single spaces or tabs. The shell splits input lines into words at spaces and tabs with the following exceptions:
•The characters &, |, ;, <, >, (, and ) form separate words. If doubled in &&, ||, <<, or >>, these pairs form single words.
•Parser metacharacters can be part of other words. Preceding them with a \ (backslash) prevents the shell from interpreting them as special characters. A newline preceded by a \ (backslash) is equivalent to a space.
•Strings enclosed in " " (double quotes), ‘ ‘ (grave accents), or ’ ’ (single quotes) form parts of a word; metacharacters in these strings, including spaces and tabs, do not form separate words. For more information, see the section "Quoting with Single and Double Quotes". Within pairs of ’ or " characters, you can include the newline character by preceding it with a \ (backslash).
•When the shell is not reading input from a terminal, it treats any word that begins with a # (number sign) character as a comment and ignores that word and all characters following up to the next newline character. This special meaning is prevented when the # character is preceded by a \ (backslash) or when the string is enclosed in quotes using ‘, ’, or ".
Shell Commands
A simple command is a sequence of words, the first of which (numbered 0) specifies the command to be executed. Any remaining words, with a few exceptions, are passed to that command. If the command specifies an executable file that is a compiled program, the shell immediately runs that program. If the file is marked executable but is not a compiled program, the shell assumes that it is a shell script. In this case it starts another instance of itself (a subshell), to read the file and execute the commands included in it.
A pipeline is a sequence of one or more commands separated by | (vertical bar) characters. The output of each command in a pipeline is connected to the input of the next. A list is a sequence of pipelines separated by a ; (semicolon), & (ampersand), && (two ampersands), or || (two vertical bars) and optionally ended by a ; (semicolon) or an & (ampersand). These separators and terminators have the following effects:
;Causes sequential execution of the preceding pipeline (the shell waits for the pipeline to finish).
&Causes asynchronous execution of the preceding pipeline (the shell does not wait for the pipeline to finish).
&&Causes the list following it to be executed only if the preceding pipeline returns a 0 (zero) exit value.
||Causes the list following it to be executed only if the preceding pipeline returns a nonzero exit value.
The ; (semicolon) and & (ampersand) separators have equal precedence, as do && and ||. The single-character separators have lower precedence than the double-character separators. A newline character without quotes following a pipeline functions the same as a ; (semicolon). Place any of the above in parentheses to form a simple command.
Job Control
The shell associates a job with each pipeline. It keeps a table of current jobs, printed by the built-in jobs command, and assigns them small integer numbers. When you start a job asynchronously by terminating the command with &, the shell displays a line that looks like this:
[1] 1234
This line indicates that the job number is 1 and that the job is composed of one process with the process ID of 1234. Use the built-in jobs command to see what jobs are currently running.
If you are running a job and want to do something else, you can enter the Suspend key sequence (normally <Ctrl-z>, which sends a SUSPEND signal to the current job. The shell then normally indicates that the job has been stopped, and it prints 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 then eventually bring the job back into the foreground with the foreground command fg. A SUSPEND takes effect immediately and is like the Interrupt key sequence in that pending output and unread input are discarded. A special key sequence, <Ctrl-y>, does not generate a SUSPEND signal until a program attempts to read it. This can usefully be typed ahead when you have prepared some commands for a job that you wish 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 entering the stty tostop command. If you set this tty option, 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. Use the % (percent sign) to introduce the name of a suspended job. This name can be either the job number or the command name that started the job, if this name is unique. (% can be used to refer to all background jobs, including those not suspended.)
For example, if a make process is running as job number 1, you can refer to it as %1. You can also refer to it as %make, if there is only one suspended job with a name that begins with the string make. You can also use the following characters to specify a job whose name contains string, if there is only one such job:
%?:string
Just naming a job brings it to the foreground; thus %1 is a synonym for fg %1, bringing job 1 back into the foreground. Similarly, entering %1 & resumes job 1 in the background. Thus, %ex normally restarts a suspended ex job, if there were only one suspended job whose name began with the string ex.
The shell maintains a notion of the current and previous jobs. In output pertaining to jobs, the current job is marked with a + (plus sign) and the previous job with a − (dash). The abbreviation %+ refers to the current job and %− refers to the previous job. For close analogy with the syntax of the history mechanism (described later), %% is also a synonym for the current job.
Status Reporting
The shell immediately detects when a process changes state. The shell normally informs you whenever a job becomes blocked so that no further progress is possible, but only just before it prints a prompt. This is done so that it does not otherwise disturb your work. If, however, you set the notify shell variable, the shell notifies you immediately of changes of status in background jobs. There is also a notify shell command which marks a single process so that its status changes are immediately reported. By default notify marks the current process. Simply enter notify after starting a background job to mark the job.
When you try to leave the shell while jobs are stopped, you are warned that you have stopped jobs. You can use the built-in jobs command to see what they are. If you then immediately exit the shell, or use jobs and then exit, the shell does not warn you a second time, and the suspended jobs are terminated.
Filename Completion
When the filename completion feature is enabled by setting the shell variable filec, csh interactively completes filenames and usernames from unique prefixes, when they are input from the terminal followed by the escape character (the <ESC> key or <Ctrl-[>)). For example, assume the current directory looks like this:
DSC.OLDchaosdevxmpl.c
DSC.NEWclasslibxmpl.o
benchcmdmailxmpl.out
bincmtest mbox
The input is as follows:
% vi ch<ESC>
csh completes the prefix ch to the only matching filename chaos:
vi chaos
However, given the following command line:
vi D<ESC>
csh only expands the input as follows:
vi DSC.
csh sounds the terminal bell to indicate that the expansion is incomplete, because two filenames match the prefix D.
If a partial filename is followed by the End-of-File character (shown here as <Ctrl-d>), then instead of completing the name, csh lists all filenames matching the prefix. For example, the following input causes all files beginning with D to be listed:
vi D<Ctrl-d>
DSC.NEW DSC.OLD
The input line remains unchanged.
The same system of <ESC> and End-of-File can also be used to expand partial usernames, if the word to be completed (or listed) begins with ~ (tilde). For example, entering the following command line
cd ~ro<ESC>
can produce the following 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 following command:
% set fignore = (.o .out)
typing
% vi x<escape>
results 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 filenames by <Ctrl-d>. All files are listed regardless of their suffixes.
History Substitution
History substitution places 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. History substitutions begin with the ! (exclamation point) character and can begin anywhere on the command line, provided they do not nest (in other words, a history substitution cannot contain another history substitution). You can precede the ! with a \ (backslash) to prevent the exclamation point’s special meaning. In addition, if you place an ! (exclamation point) before a space, tab, newline, = (equal sign), or ( (left parenthesis), the exclamation point is passed unchanged. (History substitutions also occur when you begin an input line with a ^ (circumflex). This special abbreviation is described later. The shell echoes any input line containing history substitutions before it executes that command line.
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 history shell variable controls the size of the history list. You must set the history shell variable either in the .cshrc file or on the command line with the built-in set command . The previous command is always retained, however, regardless of the value of history. Commands in the history list are numbered sequentially, starting from 1. The built-in history command produces output of the type:
9 write michael
10 ex write.c
11 cat oldwrite.c
12 diff ∗write.c
The command strings are shown with their event numbers. It is not usually necessary to use event numbers to refer to events, but you can have the current event number displayed as part of your system prompt by placing an ! (exclamation point) in the prompt string assigned to the prompt variable.
A full history reference contains an event specification, a word designator, and one or more modifiers in the following general format:
event[:]word:modifier[:modifier]...
Note that only one word can be modified. A string that contains spaces is not allowed.
In the previous sample of history command output, the current event number is 13. Using this example, the following refer to previous events:
!10Refers to event number 10.
!-2Refers to event number 11 (the current event minus 2).
!dRefers to a command word beginning with d (in this case, event number 12).
!?mic?Refers to a command word that contains the string mic (in this case, event number 9).
These forms, without further modification, simply reintroduce the words of the specified events, each separated by a single space. As a special case, !! refers to the previous command. (The !! command alone on an input line reruns the previous command.)
To select words from an event, follow the event specification by a : (colon) and one of the following word designators. The words of an input line are numbered sequentially, starting from 0, with the first (usually command) word being 0, the second word (first argument) being 1, and so on. The basic word designators are as follows:
0First (command) word
nnth argument
^First argument, that is, 1
$Last argument
%Word matched by (the immediately preceding) ?string? history search
x−yRange of words
−yAbbreviates 0−y
∗Abbreviates ^−$, or nothing if only one word in event
x∗Abbreviates x− $
x−Like x∗, but omits the last word ($)
You can omit the : (colon) separating the event specification from the word designator if the word designator begins with a ^, $, ∗, −, or %. You can also place a sequence of modifiers, each preceded by a : (colon), after the optional word designator. The following modifiers are defined:
&Repeats the previous substitution.
eRemoves all but the trailing extension .xxx.
gApplies the change globally, prefixing another modifer e.g. g&.
hRemoves a trailing pathname extension, leaving the head.
pPrints the new command, but does not execute it.
qQuotes the substituted words, thus preventing further substitutions.
rRemoves a trailing .xxx component, leaving the root name.
s/l/r/Substitutes l for r. It is an error for no word to be applicable.
tRemoves all leading pathname components, leaving the tail.
xLike q, but breaks into words at space, tab or newline.
Unless the modifier is preceded by a g, the change is applied only to the first modifiable word.
The l (left) side of a substitution is not a pattern in the sense of a string recognized by an editor; rather, it is a word, a single unit without spaces. Normally, a / (slash) delimits the word (l) and its replacement (r). However, you can use any character as the delimiter if you precede that character with a \ (backslash). Thus, in the following example the = character becomes the delimiter, allowing you to include the / in your word:
s\=/usr/myfile\=/usr/yourfile\=
If you include an & (ampersand) in the replacement, it is replaced by the text from the left-hand side (l). A null l side is replaced by either the last substitution or by the last string used in the contextual scan !?string?. You can omit the trailing delimiter (/) if a newline character follows immediately.
A history reference can be given without an event specification. For example, !$ refers to the last argument of the previous command. If a history reference without an event specification is not the first history reference on the line, it refers to the previous history reference on the line and not to a previous event. For example, in !?foo?^ !$, !?foo?^ gives the first argument of the command matching ?foo?, and the !$ gives the last argument of that same command, not the last argument of the previous command (as it would if it were on a line by itself).
A special abbreviation of a history reference occurs when the first nonspace character of an input line is a ^ (circumflex). This is equivalent to !:s^, providing a convenient shorthand for substitutions on the text of the previous line. Thus, ^lb^lib corrects the spelling of lib in the previous command. Finally, a history substitution can be enclosed in { } (braces) to insulate it from the characters that follow. Thus, after ls −ld ~paul you might specify !{l}a to do ls −ld ~paula, or !la to rerun a command starting with la.
Quoting with Single and Double Quotes
Enclose strings in single and double quotes to prevent all or some of the substitutions that remain. Enclosing strings in ’ ’ (single quotes) prevents any further interpretation. Enclosing strings in " " (double quotes) allows further expansion. In both cases, the text that results becomes (all or part of) a single word. Only in one special case does a string quoted by " yield parts of more than one word; strings quoted by ’ ’ never do (see Command Substitution).
Alias Substitution
The shell maintains a list of aliases that the alias and unalias built-in commands can establish, display, and modify. After the shell scans a command line, it divides the line into distinct commands and checks the first word of each command, left to right, to see if it has an alias. If it does, the shell uses the history mechanism (see History Substitution) to replace the text of the alias with the text of the command it stands for. The words that result replace the command and argument list. If no reference is made to the history list, the argument list is left unchanged.
Thus, if the alias for ls is ls −l, the shell replaces the command ls /usr with ls −l /usr. The argument list is left unchanged because there is no reference to the history list in the command with an alias. Similarly, if the alias for lookup is grep \!^ /etc/passwd, then lookup bill maps to grep bill /etc/passwd.
Here \!^ refers to the history list and the shell replaces it with the first argument in the input line, in this case bill. Note that you can use special pattern-matching characters in an alias. Thus, the line:
alias lprint ’pr \!∗ | lpr’
makes a command that formats its arguments to the line printer. The ! (exclamation point) is protected from the shell in the alias so that it is not expanded until pr runs.
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. If the first word of the new text is the same as the old, looping is prevented by flagging it to terminate the alias process. Other loops are detected and cause an error.
Variable Substitution
The shell maintains a set of variables, each of which has as its 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 is an image of the shell variable list, and words that comprise the value of this variable are referred to in special ways.
You can duplicate and change the values of variables by using the set and unset commands. Of the variables referred to by the shell, a number are toggles (variables that turn on and off); the shell does not care what their value is, only whether they are set or unset. For instance, the verbose variable is a toggle that causes command input to be echoed. The setting of this variable results from the −v flag on the command line.
Other operations treat variables numerically. The @ command performs numeric calculations and the result is assigned to a variable. Variable values are, however, always represented as (zero or more) strings. For the purposes of numeric operations, the null string is considered to be 0 (zero), and the second and subsequent words of multiword values are ignored.
After the input line is parsed and alias substitution is performed, and before each command is executed, variable substitution is performed, keyed by $ (dollar sign) characters. You can prevent this expansion by preceding the $ with a \ (backslash) except within " " (double quotes), where it always occurs, and within ’ ’ (single quotes), where it never occurs. Strings quoted by ‘ ‘ (grave accents) are interpreted later (see Command Substitution), so $ variable substitution does not occur until later, if at all. A $ is passed unchanged if followed by a space, tab, or newline.
Input/output redirections are recognized before variable expansion and are expanded separately. Otherwise, the command name and complete argument list are expanded together. Therefore, it is 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 can themselves eventually be command and filename substituted. Within pairs of double quotes, 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 spaces. When you apply the :q modifier to a substitution, the variable expands to multiple words. The individual words are separated by spaces and quoted to prevent later command or filename substitution.
The following notation allows you to introduce variable values into the shell input. Except as noted, it is an error to reference a variable that is not set.
$name
${name}
Are replaced by the words assigned to the variable name, each separated by a space. Braces insulate name from following characters that would otherwise be part of it. Shell variable names begin with a letter and consist of up to 20 letters and digits, including the underscore character. If name is not a shell variable but is set in the environment, then that value is returned. Be aware that the : (colon) modifiers and the other forms given below are not available in this case.
$name[selector]
${name[selector]}
Can be used to select only some of the words from the value of name. The selector is subjected to $ variable substitution and can consist of a single number or two numbers separated by a − (dash). The first word of a variable’s string value is numbered 1. If the first number of a range is omitted, it defaults to 1. If the last member of a range is omitted, it defaults to $#name. The ∗ (asterisk) selects all words. It is not an error for a range to be empty if the second argument is omitted or in range.
$#name
${#name}
Gives the number of words in the variable. This can be used as a [selector] (see previous notation).
$0Substitutes the name of the file from which command input is being read. An error occurs if the name is not known.
$number
${number}
Equivalent to $argv[number].
$∗Equivalent to $argv[∗].
You can apply the modifiers :gh, :gt, :gr, :h, :t, :r, :q and :x to the preceding substitutions. If { } (braces) appear in the command form, the modifiers must appear within the braces. Note that the current implementation allows only one : (colon) modifier on each $ variable expansion.
The following substitutions cannot be changed with : modifiers.
$?name
${?name}
Substitutes the string 1 if name is set, 0 if it is not.
$?0Substitutes 1 if the current input filename is known, 0 if it is not.
$$Substitutes the (decimal) process number of the (parent) shell.
$<Substitutes a line from the standard input, with no further interpretation. Use it to read from the keyboard in a shell script.
Command and Filename Substitution
The shell performs command and filename substitution selectively on the arguments of built-in commands. This means that it does not expand those parts of expressions that are not evaluated. For commands that are not internal (i.e., built in) to the shell, the shell substitutes the command name separately from the argument list. This occurs very late, after the shell performs input/output redirection, and in a child of the main shell.
Command Substitution
The shell performs command substitution on a command string enclosed in ‘ ‘ (grave accents). The shell normally breaks the output from such a command into separate words at spaces, tabs and newline characters, with null words being discarded; this text then replaces the original command string. Within strings surrounded by " " (double quotes), the shell treats only the newline character as a word separator, thus preserving spaces and tabs.
In any case, the single final newline character 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.
Filename Substitution
If a word contains any of the characters ∗, ?, [, or { or begins with a ~ (tilde), then that word is a candidate for filename substitution, also known as globbing. This word is then regarded as a pattern, and replaced with an sorted list of filenames that match the pattern. The current collating sequence is used, which can be specified by the LC_COLLATE or LANG environment variable.
In a list of words specifying filename substitution, it is an error for no pattern to match an existing filename, but it is not required that each pattern match. Only the character-matching symbols (metacharacters) ∗, ? and [ imply pattern matching; the characters ~ and { are more like abbreviations.
In matching filenames, the . (dot) character at the beginning of a filename or immediately following a / (slash), as well as the / character, must be matched explicitly. The ∗ (asterisk) character matches any string of characters, including the null string. The ? (question mark) character matches any single character. The sequence [abcd] matches any one of the enclosed characters. Within [ ], a lexical range of characters can be indicated by two characters separated by a − (dash), as in [a-z]. The characters that match this pattern are defined by the current collating sequence. The collating sequence is determined by the value of the LC_COLLATE environment variable.
The ~ (tilde) character at the beginning of a filename is used to refer to home directories. Standing alone, the ~ expands to your home directory as reflected in the value of the home shell variable. When followed by a name that consists of letters, digits, and − (dash) characters, the shell searches for a user with that name and substitutes that user’s home directory. Thus, ~ken might expand to /usr/ken and ~ken/chmach to /usr/ken/chmach. If the ~ (tilde) character is followed by a character other than a letter or / (slash) or does not appear at the beginning of a word, it is left undisturbed.
The pattern a{b,c,d}e is a shorthand for abe ace ade. Left-to-right order is preserved, with the results of the matches being sorted separately at a low level to preserve this order. This construct can be nested. Thus, the shell expands:
~source/s1/{oldls,ls}.c
to the filenames:
/usr/source/s1/oldls.c /usr/source/s1/ls.c
The preceding example assumes the home directory for source is /usr/source. (Note that these files may or may not exist.)
Similarly, the shell expands:
../{memo,∗box}
to the paths:
../memo ../box ../mbox
(Note that memo was not sorted with the results of matching ∗box.) As a special case, {, }, and {} are passed undisturbed.
Redirecting Input and Output
You can redirect the standard input and standard output of a command with the following syntax:
< fileOpens file (which is first variable, command and filename expanded) as the standard input.
<< word
Reads the shell input up to a line that is identical to word. word is not subjected to variable, filename or command substitution; each input line is compared to word before any substitutions are done on this input line. Unless a quoting character (\, ", ‘, or ’) appears in word, the shell performs variable and command substitution on the intervening lines, allowing \ to quote $, \, and ‘. Commands that are substituted have all spaces, tabs, and newline characters preserved, except for the final newline character, which is dropped. The resulting text is placed in an anonymous temporary file and given to the command as standard input.
> file
>! file
>& file
>&! fileUses file as standard output. If the file does not exist, it is created; if the file exists, it is truncated, and its previous contents are lost. If the noclobber shell variable is set, then the file must not exist or be a character special file (for example, a terminal or /dev/null) or an error results. This helps prevent the accidental destruction of files. In this case, use the ! (exclamation point) forms to suppress this check. The forms involving & (ampersand) route the diagnostic output into the specified file as well as the standard output. file is expanded in the same way as < input filenames.
>> file
>>& file
>>! file
>>&! file
Uses file as standard output like > but places output at the end of the file. If the noclobber shell variable is set, it is an error for the file not to exist unless one of the ! forms is given. Otherwise, it is similar to >.
A command receives the environment in which the shell was invoked, as changed 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. Use the << mechanism to present inline data. This lets shell command files function as components of pipelines and lets the shell read its input in blocks. Note that the default standard input for a command run detached is not changed to be the empty file /dev/null; rather the standard input remains as the original standard input of the shell.
To redirect diagnostic output through a pipe with the standard output, use the form |& (vertical bar, ampersand) rather than | (vertical bar) alone.
Control Flow
The shell contains a number of commands that can be used to 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.
If the shell input is not searchable, the shell buffers input whenever a loop is being read and searches the internal buffer to do the rereading implied by the loop. (To the extent that this allows, backward gotos succeed on inputs that you cannot search.)
Built-In Commands
Built-in commands are executed within the shell. If a built-in command occurs as any component of a pipeline except the last, it is executed in a subshell.
alias [name [word_list]]
If no arguments are specified, displays all aliases. If name is specified, displays the alias for name. If a word_list is also specified, alias assigns the specified word_list as the alias of name. The name argument cannot be alias or unalias.
bg [%job ...]
Puts the current or specified jobs into the background, continuing them if they were stopped.
breakCauses execution to resume after the end of the nearest enclosing foreach or while. The remaining commands on the current line are executed. Multilevel breaks are therefore possible by writing them all on one line.
breaksw
Causes a break from a switch; resumes after the endsw.
case label:
Defines a label in a switch statement. (See switch.)
cd [directory]
chdir [directory]
Changes the shell’s working directory to directory. If no argument is given, it changes to your home directory. If directory is not found as a subdirectory of the current directory (and does not begin with /, ./ or ../), then each component of the cdpath shell variable is checked to see if it has a subdirectory directory. Finally, if all else fails, but directory is a shell variable whose value begins with /, this is tried to see if it is a directory.
continue
Continues execution of the nearest enclosing while or foreach. The rest of the commands on the current line are executed.
default:Labels the default case in a switch statement. The default should come after all case labels.
dirsDisplays the directory stack; the top of the stack is at the left, the first directory in the stack being the current directory.
echo [-n] word_list
Writes the specified words to the shell’s standard output, separated by spaces, and terminated with a newline character, unless the −n flag is specified.
else
end
endif
endswSee the description of foreach, if, switch, and while below.
eval argument ...
Reads arguments as input to the shell and executes the resulting commands in the context of the current shell. This is usually used to execute commands generated as the result of command or variable substitution, since parsing occurs before these substitutions.
exec command
Executes the specified command in place of the current shell.
exit [(expression)]
Exits the shell with either the value of the status shell variable, if no expression is specified, or with the value of the specified expression.
fg [%job ...]
Brings the current or specified jobs into the foreground, continuing them if they were stopped.
foreach name (word_list) ...
endSets the variable name to each member of word_list successively and executes the sequence of commands between the foreach command and the matching end. (foreach and end commands must appear alone on separate lines.) Use the built-in continue command to continue the loop and the built-in break command to terminate it prematurely. When this command is read from the terminal, the loop is read once, prompting with ? before any statement in the loop is executed. If you make a mistake in entering a loop at the terminal, it can be corrected before you run the loop. Commands within loops prompted for by ? are not placed in the history list.
glob word_list
Functions like echo, but does not recognize \ (backslash) escapes and delimits words by null characters in the output. Useful if you want to use the shell to perform filename substitution to expand a list of words.
goto word
Performs filename and command expansion on the specified word to yield a string of the form label:. The shell rewinds its input as much as possible and searches for a line of the form label:, possibly preceded by spaces or tabs. Execution continues after the line specified by word.
history [−r | −h] [[number]]
Displays the history event list; the oldest events are displayed first. If you specify a number, only the number most recent events are displayed. The −r flag reverses the display order to the most recent first, rather than the oldest first. The −h flag displays the history list without leading numbers. Use this to produce files suitable for sourcing using the −h flag to source.
if (expression) command
Executes the single command (including its arguments) if the specified expression evaluates true. Variable substitution on command happens early, at the same time it does for the rest of the if command. The command argument must be a simple command (rather than a pipeline, command list, or parenthesized command list). Note that input/output redirection occurs even if expression is false and command is not executed.
if (expression) then ...
else if (expression2) then ...
else ...
endifIf expression is true, executes the commands following the first then up to the first else; otherwise, if expression2 is true, executes the commands following the second then up to the second else. Any number of else−if pairs are possible; only one endif is needed. The else part is optional. (The words else and endif must appear at the beginning of input lines. The if command must appear alone on its input line or after an else.)
inlib library_name
Installs the specified shared library into the shell’s private table of installed libraries. This makes the library available for resolution of unresolved symbols in commands subsequently executed from this shell.
jobs
jobs −lLists the active jobs; with the −l flag, lists process IDs in addition to job numbers.
kill %job
kill -sig %job ...
kill PID
kill -sig PID ...
kill −lSends either the TERM (terminate) signal or the specified signal to the jobs or processes that you specify. Signals are either given by number or by name (as given in /usr/include/signal.h, stripped of the prefix SIG). The signal names are listed by kill −l. There is no default job; specifying kill with no job or PID does not send a signal to the current job. If the signal being sent is SIGTERM (terminate) or SIGHUP (hangup), then the job or process is sent a SIGCONT (continue) signal as well.
limit [resource [maximum_use]]
limit −h
limit −h resource
limit −h resource maximum_use
Limits the usage by the current process and each process it creates not to (individually) exceed maximum_use on the specified resource. If no maximum_use is given, then the current limit is displayed; if no resource is given, then all limitations are given. If the −h flag is given, the hard limits are used instead of the current limits. The hard limits impose a ceiling on the values of the current limits. Only the superuser can raise the hard limits, but a user can lower or raise the current limits within the legal range. Controllable resources currently include cputime (the maximum number of CPU seconds to be used by each process), filesize (the largest single file that can be created), datasize (the maximum growth of the data region allowed beyond the end of the program text), stacksize (the maximum size of the automatically extended stack region), and coredumpsize (the size of the largest core dump that is created). The maximumuse can be specified as a (floating-point or integer) number followed by a scale factor: k or kilobytes (1024 bytes), m or megabytes, or b or blocks (the units used by the ulimit system call). For both resource names and scale factors, unambiguous prefixes of the names suffice. filesize can be lowered by an instance of csh, but can only be raised by an instance whose effective user ID is root. For more information, refer to the documentation for the ulimit system call.
loginTerminates a login shell and replaces it with an instance of /usr/bin/login. This is one way to log off (included for compatibility with sh).
logoutTerminates a login shell. Especially useful if ignoreeof is set.
newgrp [-] [group]
Changes the primary group identification of the current shell process to group. If you specify -, newgrp changes the login environment to the login environment of the new group. If you do not specify a group, newgrp changes the group identification to that specified for the current user in the /etc/passwd file. newgrp recognizes group names only; it does not recognize group ID numbers. Only a user with superuser authority can change the primary group of the shell to one to which that user does not belong. Any active user-generated shell is terminated when the newgrp command is used.
nice
nice +number
nice command
nice +number command
The first form sets the priority of commands run in this shell to 4. The second form sets the priority to the specified number. The final two forms run command at priority 4 and number, respectively. The greater the number, the less CPU the process gets. The superuser can specify negative priority by using nice with a negative number. The command is always executed in a subshell, and the restrictions placed on commands in simple if statements apply.
nohup
nohup command
The first form causes hangups to be ignored for the remainder of the shell script. The second form causes the specified command to be run with hangups ignored. To run a pipeline or list of commands with this form, put the pipeline or list in a shell script, give the script execute permission, and use the shell script as the command. All processes run in the background with & are effectively protected from being sent a hangup signal when you log off, but are still subject to explicitly sent hangups unless nohup is used.
notify
notify %job ...
Causes the shell to notify you asynchronously when the status of the current or specified jobs changes. Normally, notification is presented immediately before the shell prompt. This is automatic if the notify shell variable is set.
onintr
onintr −
onintr label
Controls the action of the shell on Interrupts. The first form restores the default action of the shell on Interrupts, which is to terminate shell scripts or to return to the terminal command input level. The second form causes all Interrupts to be ignored. The third form causes the shell to execute a goto label when it receives an Interrupt or when a child process terminates due to an interruption. In any case, if the shell is running detached and Interrupts are being ignored, all forms of onintr have no meaning and Interrupts continue to be ignored by the shell and all invoked commands.
popd
popd +number
Pops the directory stack (removes the top entry), changing directories to the new top directory. With a +number argument, popd discards the number entry in the stack. The elements of the directory stack are numbered from the top, starting at 0.
pushd
pushd name
pushd +n
Changes to the directory that comes to the top of the stack. With no arguments, pushd exchanges the top two elements of the directory stack. With a name argument, pushd changes to the new directory (that is, cd) and pushes the old current working directory (given in the cwd shell variable) onto the directory stack. With a numeric argument, pushd rotates the number argument of the directory stack around to be the top element and changes directory to it. The members of the directory stack are numbered from the top, starting at 0.
rehashCauses the internal hash table of the contents of the directories in the path shell variable to be recomputed. This is needed if new commands are added to directories in path while you are logged in. This should be necessary only if commands are added to one of your own directories, or if someone changes the contents of one of the system directories.
repeat count command
Executes the specified command, which is subject to the same restrictions as the if statement, count times. Note that input/output redirections occur exactly once, even if count is 0.
rmlib library_name
Removes the specified shared library from the shell’s private table of installed libraries. This library is no longer available for resolution of unresolved symbols in commands executed from this shell.
set
set name
set name=word
set name[index]=word
set name=(word_list)
The first form of the command displays the value of all shell variables. Variables that have values other than a single word are displayed as a parenthesized word list. The second form sets name to the null string. The third form sets name to the single word. The fourth form sets the indexth component of name to word; this component must already exist. The final form sets name to the list of words in word_list. In all cases, the value is command and filename expanded. These arguments can be repeated to set multiple values in a single set command. Note however, that variable expansion happens for all arguments before any setting occurs.
setenv name value
Sets the value of the environment variable name to be value, a single string. The most commonly used environment variables USER, TERM, HOME, and PATH are automatically imported to and exported from the csh variables user, term, and path, so there is no need to use setenv. If you modify the LC_COLLATE or LANG environment variables, the current international character support environment and collating sequence are changed as specified for subsequent commands executed from the shell.
shift [variable]
Shifts to the left the members of argv (discarding argv[1]) or the specified variable. An error occurs if argv is not set or has less than one word as its value.
source [−h] name
Causes the shell to read commands from name. You can nest source commands. However, if they are nested too deeply, the shell can run out of file descriptors. An error in a source at any level terminates all nested source commands. Normally, input during source commands is not placed on the history list. The −h flag causes the commands to be placed in the history list without being executed.
stop
stop %job ...
Stops the current or specified job that is executing in the background.
suspend
Causes the shell to stop in its tracks, much as if it had been sent a SUSPEND signal. This is most often used to stop shells that are started by su.
switch (string)
case string1: ...
breaksw ...
default: ...
breaksw
endswSuccessively matches each case label against string, which is first command and filename expanded. Use the pattern-matching characters ∗, ?, and [...] in the case labels, which are variable expanded. If none of the labels match before a default label is found, then execution begins after the default label. Each case label and the default label must appear at the beginning of a line. The breaksw command causes execution to continue after the endsw command. Otherwise, control can fall through case labels and the default labels, as in C. If no label matches and there is no default, execution continues after the endsw command.
time
time command
With no argument, displays a summary of time used by this shell and its children. If arguments are given, the specified command is timed and a time summary (as described under the time shell variable) is displayed. If necessary, an extra shell is created to display the time when the command completes.
umask
umask value
Displays the file creation mask (first form) or sets it to the specified value (second form). The mask is given as an octal value. Common values for the mask are 002, giving all access to the owner and group and read and execute access to others, or 022, giving all access to the owner and read and execute access to users in the group or others.
unalias pattern
Discards all aliases with names that match pattern. Thus, all aliases are removed by unalias ∗. The absence of aliases that match pattern does not cause an error.
unhashDisables the use of the internal hash table to speed location of executed programs.
unlimit [resource]
unlimit −h
unlimit −h resource
Removes the limitation on resource. If no resource is specified, then all resource limitations are removed. If −h is given, the corresponding hard limits are removed. Only the superuser can do this.
unset pattern
Removes all variables with names that match pattern. Use unset ∗ to remove all variables. The absence of variables that match pattern is not an error.
unsetenv pattern
Removes all variables with names that match pattern from the environment. See also the setenv command (discussed earlier in this list) and the printenv command reference page.
waitWaits for all background jobs. If the shell is interactive, an Interrupt can disrupt the wait, at which time the shell displays the names and job numbers of all jobs known to be outstanding.
while (expression) ...
endWhen expression evaluates as nonzero, executes the commands between the while and the matching end. You can use the break command to terminate the loop prematurely and the continue command to continue the loop. (The while and end must appear alone on their input lines.) If the input is a terminal, prompting occurs the first time through the loop, as for the foreach statement.
%jobBrings the specified job into the foreground.
%job &Continues the specified job in the background.
@
@ name = expression
@ name[index] = expression
The first form displays the values of all the shell variables. The second form sets the specified name to the value of expression. If the expression contains <, >, &, or |, at least this part of the expression must be placed within ( ) (parentheses). The third form assigns the value of expression to the indexth argument of name. Both name and its indexth component must already exist. C operators, such as ∗= and +=, are available. The space separating the name from the assignment operator is optional. Spaces are, however, mandatory in separating components of expression, which would otherwise be single words. Special postfix ++ and − − operators increment and decrement name, respectively, e.g. @ i++.
Expressions
The built-in commands @, exit, if, and while accept expressions that include operators similar to those of C, with the same precedence. The following operators are available:
( )
~
!
∗/%
+-
<<>>
<=>=<>
==!==~!~
&
^
|
&&
||
In the preceding list, operators of equal precedence appear on the same line, below those lines containing operators (if any) that have greater precedence, and above those lines containing operators having lesser precedence. The ==, !=, =~, and !~ operators compare their arguments as strings; all others operate on numbers. The =~ and !~ operators are similar to != and ==, except that the rightmost side is a pattern against which the left-hand 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 result 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 next to components of expressions that are syntactically significant to the parser (& | < > ( ) ). Surround expression components with spaces.
Also available in expressions as primitive operands are command executions enclosed in { and } and file inquiries of the form −l name where l is one of the following:
rRead access
wWrite access
xExecute access
eExistence
oOwnership
zZero size
fPlain file
dDirectory
The specified file is command and filename 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, that is, 0. Command executions succeed, returning true (1), if the command exits with status 0; otherwise, they fail, returning false (0). If more detailed status information is required, execute the command outside of an expression and examine the status shell variable.
Predefined 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; the remaining variables maintain their settings unless you explicitly reset them.
The csh command copies the USER environment variable 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 PATH environment variable is handled similarly; it is not necessary to worry about their settings other than in the .cshrc file, because inferior csh processes import the definition of path from the environment, and export it again if you then change it.
argvIs set to the arguments to the shell. It is from this variable that positional parameters are substituted, for example, $1 is replaced by $argv[1], and so on.
cdpathGives a list of alternate directories searched to find subdirectories in chdir commands.
cwdIs set to the full pathname of the current directory.
echoCauses each command and its arguments to be echoed just before it is executed. It is set when the −x command line flag is specified. For nonbuilt-in commands, all expansions occur before echoing. Built-in commands are echoed before command and filename substitution, since these substitutions are then done selectively.
filecEnables filename completion.
histchars
Changes the characters used in history substitution when given a string value. The first character of its value is used as the history substitution character, replacing the default character ! (exclamation point). The second character of its value replaces the character ^ (circumflex) in quick substitutions.
historyControls the size of the history list when given a numeric value. Any command that was referenced in this many events is not discarded. Values of history that are too large can run the shell out of memory. The last executed command is always saved on the history list.
homeDefines the home directory of the invoker, initialized from the environment. The filename expansion of ~ (tilde) refers to this variable.
ignoreeof
Causes the shell to ignore End-of-File from input devices that are terminals. This prevents shells from accidentally being killed when they read an End-of-File character.
LANGSpecifies the locale of your system, which is comprised of three parts: language, territory, and codeset. The default locale is the C locale, which specifies the value English for language, U.S. for territory, and ASCII for codeset.
LC_COLLATE
Specifies the collating sequence to use when sorting names and when character ranges occur in patterns. The default value is the collating sequence for American English.
LC_CTYPE
Specifies the character classification information to use on your system. The default value is American English.
LC_MESSAGES
Specifies the language in which system messages appear, and the language that the system expects for user input of yes and no strings. The default value is American English.
LC_MONETARY
Specifies the monetary format for your system. The default value is the monetary format for American English.
LC_NUMERIC
Specifies the numeric format for your system. The default value is the numeric format for American English.
LC_TIME
Specifies the date and time format for your system. The default value is the date and time format for American English.
mailSpecifies the files where the shell checks for mail. This is done after each command completion, which results in a prompt if a specified interval has elapsed. The shell displays the message You have new mail if the file exists with an access time not greater than its modification time. If the first word of the value of mail is numeric, it specifies a different mail checking interval (in seconds) than the default (10 minutes). If you specify multiple mail files, the shell displays the message New mail in file when there is mail in file.
NLSPATH
Specifies a list of directories to search to find message catalogs.
noclobber
If set, places restrictions on output redirection to ensure that files are not accidentally destroyed, and that >> redirections refer to existing files. (See also Redirecting Input and Output.)
noglobIf set, inhibits filename expansion. This is most useful in shell scripts that do not deal with filenames, or after a list of filenames is obtained and further expansions are not desirable.
nonomatch
If set, does not return an error for a filename expansion that does not match any existing files; rather, the primitive pattern is returned. It is still an error for the primitive pattern to be malformed, for example, echo [ still gives an error.
notifyIf set, causes the shell to notify you asynchronously of changes in job status (for example, job completion). The default is to present job status changes immediately before printing a prompt.
pathEach word of the path variable specifies a directory in which commands are to be sought for execution. A null word specifies the current directory. If no path variable is set, then only full pathnames are executed. The usual search path is the current directory and /usr/bin, but this can vary from system to system. For the superuser, the default search path is /sbin, /usr/sbin, and /usr/bin. A shell that is given neither the −c nor the −t flag normally hashes the contents of the directories in the path variable after reading .cshrc and each time the path variable is reset. If new commands are added to these directories while the shell is active, it might be necessary to give the rehash command or the new commands might not be found.
promptThe string that is printed before each command is read from an interactive terminal input. If a ! (exclamation point) appears in the string, it is replaced by the current event number. If the ! is in a quoted string, it must be preceded by a \ (backslash). The default prompt is %, # for the superuser.
savehistWhen given a numeric value, controls the number of entries of the history list that are saved in ~/.history when you log out. Any command that was referenced in this many events is saved. During startup, the shell sources ~/.history into the history list, enabling history to be saved across logins. Very large values of savehist slow down the shell during startup.
shellThe file in which the shell resides. This is used in forking shells to interpret files that have execute bits set, but that are not executable by the system. (See Nonbuilt-In Command Execution.) This is initialized to the (system-dependent) home of the shell.
statusThe status returned by the last command. If it terminated abnormally, then 0200 is added to the status. Built-in commands that fail return exit status 1; all other built-in commands set status 0.
timeControls automatic timing of commands. If set, then any command that takes more than the specified number of CPU seconds causes a line that gives user, system, and real times and a utilization percentage (a utilization percentage is the ratio of user and system times to real time) to be displayed when the command terminates. If time is set with no value, then all commands are timed.
verboseCauses the words of each command to be displayed after history substitution. Set by the −v command line flag.
Nonbuilt-In Command Execution
When a command to be executed is found not to be a built-in command, the shell attempts to execute the command with the execve() system call.
Each word in the path shell variable names a directory from which the shell attempts to execute the command. If it is given neither a −c nor a −t flag, the shell hashes the names in these directories into an internal table so that it only tries an exec in a directory if 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. If this mechanism was turned off (with 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 pathname of a file, which it then attempts to execute.
Commands in parentheses are always executed in a subshell. Thus, (cd ; pwd) ; pwd displays the home directory without changing the current directory location; whereas, cd ; pwd changes the current directory location to the home directory. Commands in parentheses 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 created to read it.
If there is an alias for shell, then the words of the alias are prefixed to the argument list to form the shell command. The first word of the alias should be the full pathname of the shell (e.g. $shell). Note that this is a special, late-occurring case of alias substitution and only allows words to be prefixed to the argument list without modification.
Signal Handling
The shell normally ignores QUIT signals. Jobs running detached (either by & or the bg or %...& commands) are immune to signals generated from the keyboard (INT, QUIT, and HUP). Other signals have the values the shell inherited from its parent. You can control the shell’s handling of interrupts and terminate signals in shell scripts with onintr. Login shells catch the SIGTERM (terminate) signal; otherwise, this signal is passed on to children from the state in the shell’s parent. In no case are interrupts allowed when a login shell is reading the .logout file.
Limitations
The following are csh limitations:
•Words can be no longer than 1024 bytes.
•Argument lists are limited to 5120 bytes.
•The number of arguments to a command that involves filename expansion is limited to 1/6th the number of characters allowed in an argument list.
•Command substitutions can 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.
•Words can also be separated by double spaces.
FILES
$HOME/.cshrcC shell startup file; read at beginning of execution by each C shell.
$HOME/.loginRead by login shell (after .cshrc) at login.
$HOME/.logoutRead by login shell at logout.
$HOME/.profileUser profile.
/tmp/sh∗Temporary file for <<.
/etc/passwdContains user information.
EXIT VALUES
For information about exit values, see the following sections: Shell Commands, Expressions, Pre-defined and Environment Variables, and FLAGS.
RELATED INFORMATION
Functions: access(2), exec(2), fork(2), ldr_install(2), ldr_remove(2), pipe(2), umask(2), wait(2).
Files: null(7).
OSF/1 User’s Guide.