Initial import from FreeBSD RELENG_4:
[dragonfly.git] / bin / csh / USD.doc / csh.3
1 .\" Copyright (c) 1980, 1993
2 .\"     The Regents of the University of California.  All rights reserved.
3 .\"
4 .\" Redistribution and use in source and binary forms, with or without
5 .\" modification, are permitted provided that the following conditions
6 .\" are met:
7 .\" 1. Redistributions of source code must retain the above copyright
8 .\"    notice, this list of conditions and the following disclaimer.
9 .\" 2. Redistributions in binary form must reproduce the above copyright
10 .\"    notice, this list of conditions and the following disclaimer in the
11 .\"    documentation and/or other materials provided with the distribution.
12 .\" 3. All advertising materials mentioning features or use of this software
13 .\"    must display the following acknowledgement:
14 .\"     This product includes software developed by the University of
15 .\"     California, Berkeley and its contributors.
16 .\" 4. Neither the name of the University nor the names of its contributors
17 .\"    may be used to endorse or promote products derived from this software
18 .\"    without specific prior written permission.
19 .\"
20 .\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 .\" ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 .\" SUCH DAMAGE.
31 .\"
32 .\"     @(#)csh.3       8.1 (Berkeley) 6/8/93
33 .\" $FreeBSD: src/bin/csh/USD.doc/csh.3,v 1.6.2.1 2001/07/22 11:32:15 dd Exp $
34 .\"
35 .nr H1 2
36 .NH
37 Shell control structures and command scripts
38 .NH 2
39 Introduction
40 .PP
41 It is possible to place commands in files and to cause shells to be
42 invoked to read and execute commands from these files,
43 which are called
44 .I "shell scripts."
45 We here detail those features of the shell useful to the writers of such
46 scripts.
47 .NH 2
48 Make
49 .PP
50 It is important to first note what shell scripts are
51 .I not
52 useful for.
53 There is a program called
54 .I make
55 which is very useful for maintaining a group of related files
56 or performing sets of operations on related files.
57 For instance a large program consisting of one or more files
58 can have its dependencies described in a
59 .I makefile
60 which contains definitions of the commands used to create these
61 different files when changes occur.
62 Definitions of the means for printing listings, cleaning up the directory
63 in which the files reside, and installing the resultant programs
64 are easily, and most appropriately placed in this
65 .I makefile.
66 This format is superior and preferable to maintaining a group of shell
67 procedures to maintain these files.
68 .PP
69 Similarly when working on a document a
70 .I makefile
71 may be created which defines how different versions of the document
72 are to be created and which options of
73 .I nroff
74 or
75 .I troff
76 are appropriate.
77 .NH 2
78 Invocation and the argv variable
79 .PP
80 A
81 .I csh
82 command script may be interpreted by saying
83 .DS
84 % csh script ...
85 .DE
86 where
87 .I script
88 is the name of the file containing a group of
89 .I csh
90 commands and
91 `\&...' is replaced by a sequence of arguments.
92 The shell places these arguments in the variable
93 .I argv
94 and then begins to read commands from the script.
95 These parameters are then available through the same mechanisms
96 which are used to reference any other shell variables.
97 .PP
98 If you make the file
99 `script'
100 executable by doing
101 .DS
102 chmod 755 script
103 .DE
104 and place a shell comment at the beginning of the shell script
105 (i.e. begin the file with a `#' character)
106 then a `/bin/csh' will automatically be invoked to execute `script' when
107 you type
108 .DS
109 script
110 .DE
111 If the file does not begin with a `#' then the standard shell
112 `/bin/sh' will be used to execute it.
113 This allows you to convert your older shell scripts to use
114 .I csh
115 at your convenience.
116 .NH 2
117 Variable substitution
118 .PP
119 After each input line is broken into words and history substitutions
120 are done on it, the input line is parsed into distinct commands.
121 Before each command is executed a mechanism know as
122 .I "variable substitution"
123 is done on these words.
124 Keyed by the character `$' this substitution replaces the names
125 of variables by their values.
126 Thus
127 .DS
128 echo $argv
129 .DE
130 when placed in a command script would cause the current value of the
131 variable
132 .I argv
133 to be echoed to the output of the shell script.
134 It is an error for
135 .I argv
136 to be unset at this point.
137 .PP
138 A number of notations are provided for accessing components and attributes
139 of variables.
140 The notation
141 .DS
142 $?name
143 .DE
144 expands to `1' if name is
145 .I set
146 or to `0'
147 if name is not
148 .I set.
149 It is the fundamental mechanism used for checking whether particular
150 variables have been assigned values.
151 All other forms of reference to undefined variables cause errors.
152 .PP
153 The notation
154 .DS
155 $#name
156 .DE
157 expands to the number of elements in the variable
158 .I name.
159 Thus
160 .DS
161 % set argv=(a b c)
162 % echo $?argv
163 1
164 % echo $#argv
165 3
166 % unset argv
167 % echo $?argv
168 0
169 % echo $argv
170 Undefined variable: argv.
171 %
172 .DE
173 .PP
174 It is also possible to access the components of a variable
175 which has several values.
176 Thus
177 .DS
178 $argv[1]
179 .DE
180 gives the first component of
181 .I argv
182 or in the example above `a'.
183 Similarly
184 .DS
185 $argv[$#argv]
186 .DE
187 would give `c',
188 and
189 .DS
190 $argv[1\-2]
191 .DE
192 would give `a b'. Other notations useful in shell scripts are
193 .DS
194 $\fIn\fR
195 .DE
196 where
197 .I n
198 is an integer as a shorthand for
199 .DS
200 $argv[\fIn\fR\|]
201 .DE
202 the
203 .I n\|th
204 parameter and
205 .DS
206 $*
207 .DE
208 which is a shorthand for
209 .DS
210 $argv
211 .DE
212 The form
213 .DS
214 $$
215 .DE
216 expands to the process number of the current shell.
217 Since this process number is unique in the system it can
218 be used in generation of unique temporary file names.
219 The form
220 .DS
221 $<
222 .DE
223 is quite special and is replaced by the next line of input read from
224 the shell's standard input (not the script it is reading).  This is
225 useful for writing shell scripts that are interactive, reading
226 commands from the terminal, or even writing a shell script that
227 acts as a filter, reading lines from its input file.
228 Thus the sequence
229 .DS
230 echo 'yes or no?\ec'
231 set a=($<)
232 .DE
233 would write out the prompt `yes or no?' without a newline and then
234 read the answer into the variable `a'.  In this case `$#a' would be
235 `0' if either a blank line or end-of-file (^D) was typed.
236 .PP
237 One minor difference between `$\fIn\fR\|' and `$argv[\fIn\fR\|]'
238 should be noted here.
239 The form
240 `$argv[\fIn\fR\|]'
241 will yield an error if
242 .I n
243 is not in the range
244 `1\-$#argv'
245 while `$n'
246 will never yield an out of range subscript error.
247 This is for compatibility with the way older shells handled parameters.
248 .PP
249 Another important point is that it is never an error to give a subrange
250 of the form `n\-'; if there are less than
251 .I n
252 components of the given variable then no words are substituted.
253 A range of the form `m\-n' likewise returns an empty vector without giving
254 an error when \fIm\fR exceeds the number of elements of the given variable,
255 provided the subscript \fIn\fR is in range.
256 .NH 2
257 Expressions
258 .PP
259 In order for interesting shell scripts to be constructed it
260 must be possible to evaluate expressions in the shell based on the
261 values of variables.
262 In fact, all the arithmetic operations of the language C are available
263 in the shell
264 with the same precedence that they have in C.
265 In particular, the operations `==' and `!=' compare strings
266 and the operators `&&' and `|\|\||' implement the boolean and/or operations.
267 The special operators `=~' and `!~' are similar to `==' and `!=' except
268 that the string on the right side can have pattern matching characters
269 (like *, ? or []) and the test is whether the string on the left matches
270 the pattern on the right.
271 .PP
272 The shell also allows file enquiries of the form
273 .DS
274 \-? filename
275 .DE
276 where `?' is replace by a number of single characters.
277 For instance the expression primitive
278 .DS
279 \-e filename
280 .DE
281 tell whether the file
282 `filename'
283 exists.
284 Other primitives test for read, write and execute access to the file,
285 whether it is a directory, or has non-zero length.
286 .PP
287 It is possible to test whether a command terminates normally,
288 by a primitive of the
289 form `{ command }' which returns true, i.e. `1' if the command
290 succeeds exiting normally with exit status 0, or `0' if the command
291 terminates abnormally or with exit status non-zero.
292 If more detailed information about the execution status of a command
293 is required, it can be executed and the variable `$status' examined
294 in the next command.
295 Since `$status' is set by every command, it is very transient.
296 It can be saved if it is inconvenient to use it only in the single
297 immediately following command.
298 .PP
299 For a full list of expression components available see the manual
300 section for the shell.
301 .NH 2
302 Sample shell script
303 .PP
304 A sample shell script which makes use of the expression mechanism
305 of the shell and some of its control structure follows:
306 .DS
307 % cat copyc
308 #
309 # Copyc copies those C programs in the specified list
310 # to the directory ~/backup if they differ from the files
311 # already in ~/backup
312 #
313 set noglob
314 foreach i ($argv)
315
316         if ($i !~ *.c) continue  # not a .c file so do nothing
317
318         if (! \-r ~/backup/$i:t) then
319                 echo $i:t not in backup... not cp\e\'ed
320                 continue
321         endif
322
323         cmp \-s $i ~/backup/$i:t # to set $status
324
325         if ($status != 0) then
326                 echo new backup of $i
327                 cp $i ~/backup/$i:t
328         endif
329 end
330 .DE
331 .PP
332 This script makes use of the
333 .I foreach
334 command, which causes the shell to execute the commands between the
335 .I foreach
336 and the matching
337 .I end
338 for each of the values given between `(' and `)' with the named
339 variable, in this case `i' set to successive values in the list.
340 Within this loop we may use the command
341 .I break
342 to stop executing the loop
343 and
344 .I continue
345 to prematurely terminate one iteration
346 and begin the next.
347 After the
348 .I foreach
349 loop the iteration variable
350 (\fIi\fR in this case)
351 has the value at the last iteration.
352 .PP
353 We set the variable
354 .I noglob
355 here to prevent filename expansion of the members of
356 .I argv.
357 This is a good idea, in general, if the arguments to a shell script
358 are filenames which have already been expanded or if the arguments
359 may contain filename expansion metacharacters.
360 It is also possible to quote each use of a `$' variable expansion,
361 but this is harder and less reliable.
362 .PP
363 The other control construct used here is a statement of the form
364 .DS
365 \fBif\fR ( expression ) \fBthen\fR
366         command
367         ...
368 \fBendif\fR
369 .DE
370 The placement of the keywords here is
371 .B not
372 flexible due to the current implementation of the shell.\(dg
373 .FS
374 \(dgThe following two formats are not currently acceptable to the shell:
375 .sp
376 .in +5
377 .nf
378 \fBif\fR ( expression )         # \fBWon't work!\fR
379 \fBthen\fR
380         command
381         ...
382 \fBendif\fR
383 .fi
384 .in -5
385 .sp
386 and
387 .sp
388 .in +5
389 .nf
390 \fBif\fR ( expression ) \fBthen\fR command \fBendif\fR          # \fBWon't work\fR
391 .in -5
392 .fi
393 .FE
394 .PP
395 The shell does have another form of the if statement of the form
396 .DS
397 \fBif\fR ( expression ) \fBcommand\fR
398 .DE
399 which can be written
400 .DS
401 \fBif\fR ( expression ) \e
402         command
403 .DE
404 Here we have escaped the newline for the sake of appearance.
405 The command must not involve `\||\|', `&' or `;'
406 and must not be another control command.
407 The second form requires the final `\e' to
408 .B immediately
409 precede the end-of-line.
410 .PP
411 The more general
412 .I if
413 statements above also admit a sequence of
414 .I else\-if
415 pairs followed by a single
416 .I else
417 and an
418 .I endif,
419 e.g.:
420 .DS
421 \fBif\fR ( expression ) \fBthen\fR
422         commands
423 \fBelse\fR \fBif\fR (expression ) \fBthen\fR
424         commands
425 \&...
426
427 \fBelse\fR
428         commands
429 \fBendif\fR
430 .DE
431 .PP
432 Another important mechanism used in shell scripts is the `:' modifier.
433 We can use the modifier `:r' here to extract a root of a filename or
434 `:e' to extract the
435 .I extension.
436 Thus if the variable
437 .I i
438 has the value
439 `/mnt/foo.bar'
440 then
441 .sp
442 .in +5
443 .nf
444 % echo $i $i:r $i:e
445 /mnt/foo.bar /mnt/foo bar
446 %
447 .sp
448 .in -5
449 .fi
450 shows how the `:r' modifier strips off the trailing `.bar' and the
451 the `:e' modifier leaves only the `bar'.
452 Other modifiers will take off the last component of a pathname leaving
453 the head `:h' or all but the last component of a pathname leaving the
454 tail `:t'.
455 These modifiers are fully described in the
456 .I csh
457 manual pages in the User's Reference Manual.
458 It is also possible to use the
459 .I "command substitution"
460 mechanism described in the next major section to perform modifications
461 on strings to then reenter the shell's environment.
462 Since each usage of this mechanism involves the creation of a new process,
463 it is much more expensive to use than the `:' modification mechanism.\(dd
464 .FS
465 \(dd It is also important to note that
466 the current implementation of the shell limits the number of `:' modifiers
467 on a `$' substitution to 1.
468 Thus
469 .sp
470 .nf
471 .in +5
472 % echo $i $i:h:t
473 /a/b/c /a/b:t
474 %
475 .in -5
476 .fi
477 .sp
478 does not do what one would expect.
479 .FE
480 Finally, we note that the character `#' lexically introduces a shell
481 comment in shell scripts (but not from the terminal).
482 All subsequent characters on the input line after a `#' are discarded
483 by the shell.
484 This character can be quoted using `\'' or `\e' to place it in
485 an argument word.
486 .NH 2
487 Other control structures
488 .PP
489 The shell also has control structures
490 .I while
491 and
492 .I switch
493 similar to those of C.
494 These take the forms
495 .DS
496 \fBwhile\fR ( expression )
497         commands
498 \fBend\fR
499 .DE
500 and
501 .DS
502 \fBswitch\fR ( word )
503
504 \fBcase\fR str1:
505         commands
506         \fBbreaksw\fR
507
508 \& ...
509
510 \fBcase\fR strn:
511         commands
512         \fBbreaksw\fR
513
514 \fBdefault:\fR
515         commands
516         \fBbreaksw\fR
517
518 \fBendsw\fR
519 .DE
520 For details see the manual section for
521 .I csh.
522 C programmers should note that we use
523 .I breaksw
524 to exit from a
525 .I switch
526 while
527 .I break
528 exits a
529 .I while
530 or
531 .I foreach
532 loop.
533 A common mistake to make in
534 .I csh
535 scripts is to use
536 .I break
537 rather than
538 .I breaksw
539 in switches.
540 .PP
541 Finally,
542 .I csh
543 allows a
544 .I goto
545 statement, with labels looking like they do in C, i.e.:
546 .DS
547 loop:
548         commands
549         \fBgoto\fR loop
550 .DE
551 .NH 2
552 Supplying input to commands
553 .PP
554 Commands run from shell scripts receive by default the standard
555 input of the shell which is running the script.
556 This is different from previous shells running
557 under \s-2UNIX\s0.  It allows shell scripts to fully participate
558 in pipelines, but mandates extra notation for commands which are to take
559 inline data.
560 .PP
561 Thus we need a metanotation for supplying inline data to commands in
562 shell scripts.
563 As an example, consider this script which runs the editor to
564 delete leading blanks from the lines in each argument file:
565 .DS
566 % cat deblank
567 # deblank \-\- remove leading blanks
568 foreach i ($argv)
569 ed \- $i << \'EOF\'
570 1,$s/^[ ]*//
571 w
572 q
573 \&\'EOF\'
574 end
575 %
576 .DE
577 The notation `<< \'EOF\''
578 means that the standard input for the
579 .I ed
580 command is to come from the text in the shell script file
581 up to the next line consisting of exactly `\'EOF\''.
582 The fact that the `EOF' is enclosed in `\'' characters, i.e. quoted,
583 causes the shell to not perform variable substitution on the
584 intervening lines.
585 In general, if any part of the word following the `<<' which the
586 shell uses to terminate the text to be given to the command is quoted
587 then these substitutions will not be performed.
588 In this case since we used the form `1,$' in our editor script
589 we needed to insure that this `$' was not variable substituted.
590 We could also have insured this by preceding the `$' here with a `\e',
591 i.e.:
592 .DS
593 1,\e$s/^[ ]*//
594 .DE
595 but quoting the `EOF' terminator is a more reliable way of achieving the
596 same thing.
597 .NH 2
598 Catching interrupts
599 .PP
600 If our shell script creates temporary files, we may wish to catch
601 interruptions of the shell script so that we can clean up
602 these files.
603 We can then do
604 .DS
605 onintr label
606 .DE
607 where
608 .I label
609 is a label in our program.
610 If an interrupt is received the shell will do a
611 `goto label'
612 and we can remove the temporary files and then do an
613 .I exit
614 command (which is built in to the shell)
615 to exit from the shell script.
616 If we wish to exit with a non-zero status we can do
617 .DS
618 exit(1)
619 .DE
620 e.g. to exit with status `1'.
621 .NH 2
622 What else?
623 .PP
624 There are other features of the shell useful to writers of shell
625 procedures.
626 The
627 .I verbose
628 and
629 .I echo
630 options and the related
631 .I \-v
632 and
633 .I \-x
634 command line options can be used to help trace the actions of the shell.
635 The
636 .I \-n
637 option causes the shell only to read commands and not to execute
638 them and may sometimes be of use.
639 .PP
640 One other thing to note is that
641 .I csh
642 will not execute shell scripts which do not begin with the
643 character `#', that is shell scripts that do not begin with a comment.
644 Similarly, the `/bin/sh' on your system may well defer to `csh'
645 to interpret shell scripts which begin with `#'.
646 This allows shell scripts for both shells to live in harmony.
647 .PP
648 There is also another quotation mechanism using `"' which allows
649 only some of the expansion mechanisms we have so far discussed to occur
650 on the quoted string and serves to make this string into a single word
651 as `\'' does.
652 .bp