1 .\" Copyright (c) 1980, 1993
2 .\" The Regents of the University of California. All rights reserved.
4 .\" Redistribution and use in source and binary forms, with or without
5 .\" modification, are permitted provided that the following conditions
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.
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
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 $
38 Shell control structures and command scripts
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,
46 We here detail those features of the shell useful to the writers of such
51 It is important to first note what shell scripts are
54 There is a program called
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
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
67 This format is superior and preferable to maintaining a group of shell
68 procedures to maintain these files.
70 Similarly when working on a document a
72 may be created which defines how different versions of the document
73 are to be created and which options of
79 Invocation and the argv variable
83 command script may be interpreted by saying
89 is the name of the file containing a group of
92 `\&...' is replaced by a sequence of arguments.
93 The shell places these arguments in the variable
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.
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
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
118 Variable substitution
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.
131 when placed in a command script would cause the current value of the
134 to be echoed to the output of the shell script.
137 to be unset at this point.
139 A number of notations are provided for accessing components and attributes
145 expands to `1' if name is
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.
158 expands to the number of elements in the variable
171 Undefined variable: argv.
175 It is also possible to access the components of a variable
176 which has several values.
181 gives the first component of
183 or in the example above `a'.
193 would give `a b'. Other notations useful in shell scripts are
199 is an integer as a shorthand for
209 which is a shorthand for
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.
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.
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.
238 One minor difference between `$\fIn\fR\|' and `$argv[\fIn\fR\|]'
239 should be noted here.
242 will yield an error if
247 will never yield an out of range subscript error.
248 This is for compatibility with the way older shells handled parameters.
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
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.
260 In order for interesting shell scripts to be constructed it
261 must be possible to evaluate expressions in the shell based on the
263 In fact, all the arithmetic operations of the language C are available
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.
273 The shell also allows file enquiries of the form
277 where `?' is replace by a number of single characters.
278 For instance the expression primitive
282 tell whether the file
285 Other primitives test for read, write and execute access to the file,
286 whether it is a directory, or has non-zero length.
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
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.
300 For a full list of expression components available see the manual
301 section for the shell.
305 A sample shell script which makes use of the expression mechanism
306 of the shell and some of its control structure follows:
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
317 if ($i !~ *.c) continue # not a .c file so do nothing
319 if (! \-r ~/backup/$i:t) then
320 echo $i:t not in backup... not cp\e\'ed
324 cmp \-s $i ~/backup/$i:t # to set $status
326 if ($status != 0) then
327 echo new backup of $i
333 This script makes use of the
335 command, which causes the shell to execute the commands between the
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
343 to stop executing the loop
346 to prematurely terminate one iteration
350 loop the iteration variable
351 (\fIi\fR in this case)
352 has the value at the last iteration.
356 here to prevent filename expansion of the members of
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.
364 The other control construct used here is a statement of the form
366 \fBif\fR ( expression ) \fBthen\fR
371 The placement of the keywords here is
373 flexible due to the current implementation of the shell.\(dg
375 \(dgThe following two formats are not currently acceptable to the shell:
379 \fBif\fR ( expression ) # \fBWon't work!\fR
391 \fBif\fR ( expression ) \fBthen\fR command \fBendif\fR # \fBWon't work\fR
396 The shell does have another form of the if statement of the form
398 \fBif\fR ( expression ) \fBcommand\fR
402 \fBif\fR ( expression ) \e
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
410 precede the end-of-line.
414 statements above also admit a sequence of
416 pairs followed by a single
422 \fBif\fR ( expression ) \fBthen\fR
424 \fBelse\fR \fBif\fR (expression ) \fBthen\fR
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
446 /mnt/foo.bar /mnt/foo bar
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
456 These modifiers are fully described in the
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
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.
479 does not do what one would expect.
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
485 This character can be quoted using `\'' or `\e' to place it in
488 Other control structures
490 The shell also has control structures
494 similar to those of C.
497 \fBwhile\fR ( expression )
503 \fBswitch\fR ( word )
521 For details see the manual section for
523 C programmers should note that we use
534 A common mistake to make in
546 statement, with labels looking like they do in C, i.e.:
553 Supplying input to commands
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
562 Thus we need a metanotation for supplying inline data to commands in
564 As an example, consider this script which runs the editor to
565 delete leading blanks from the lines in each argument file:
568 # deblank \-\- remove leading blanks
578 The notation `<< \'EOF\''
579 means that the standard input for the
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
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',
596 but quoting the `EOF' terminator is a more reliable way of achieving the
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
610 is a label in our program.
611 If an interrupt is received the shell will do a
613 and we can remove the temporary files and then do an
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
621 e.g. to exit with status `1'.
625 There are other features of the shell useful to writers of shell
631 options and the related
635 command line options can be used to help trace the actions of the shell.
638 option causes the shell only to read commands and not to execute
639 them and may sometimes be of use.
641 One other thing to note is that
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.
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