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