2 .\" Copyright (c) 1980, 1993
3 .\" The Regents of the University of California. All rights reserved.
5 .\" Redistribution and use in source and binary forms, with or without
6 .\" modification, are permitted provided that the following conditions
8 .\" 1. Redistributions of source code must retain the above copyright
9 .\" notice, this list of conditions and the following disclaimer.
10 .\" 2. Redistributions in binary form must reproduce the above copyright
11 .\" notice, this list of conditions and the following disclaimer in the
12 .\" documentation and/or other materials provided with the distribution.
13 .\" 4. Neither the name of the University nor the names of its contributors
14 .\" may be used to endorse or promote products derived from this software
15 .\" without specific prior written permission.
17 .\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18 .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 .\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21 .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 .\" @(#)csh.3 8.1 (Berkeley) 6/8/93
34 Shell control structures and command scripts
38 It is possible to place commands in files and to cause shells to be
39 invoked to read and execute commands from these files,
42 We here detail those features of the shell useful to the writers of such
47 It is important to first note what shell scripts are
50 There is a program called
52 which is very useful for maintaining a group of related files
53 or performing sets of operations on related files.
54 For instance a large program consisting of one or more files
55 can have its dependencies described in a
57 which contains definitions of the commands used to create these
58 different files when changes occur.
59 Definitions of the means for printing listings, cleaning up the directory
60 in which the files reside, and installing the resultant programs
61 are easily, and most appropriately placed in this
63 This format is superior and preferable to maintaining a group of shell
64 procedures to maintain these files.
66 Similarly when working on a document a
68 may be created which defines how different versions of the document
69 are to be created and which options of
75 Invocation and the argv variable
79 command script may be interpreted by saying
85 is the name of the file containing a group of
88 `\&...' is replaced by a sequence of arguments.
89 The shell places these arguments in the variable
91 and then begins to read commands from the script.
92 These parameters are then available through the same mechanisms
93 which are used to reference any other shell variables.
101 and place a shell comment at the beginning of the shell script
102 (i.e. begin the file with a `#' character)
103 then a `/bin/csh' will automatically be invoked to execute `script' when
108 If the file does not begin with a `#' then the standard shell
109 `/bin/sh' will be used to execute it.
110 This allows you to convert your older shell scripts to use
114 Variable substitution
116 After each input line is broken into words and history substitutions
117 are done on it, the input line is parsed into distinct commands.
118 Before each command is executed a mechanism know as
119 .I "variable substitution"
120 is done on these words.
121 Keyed by the character `$' this substitution replaces the names
122 of variables by their values.
127 when placed in a command script would cause the current value of the
130 to be echoed to the output of the shell script.
133 to be unset at this point.
135 A number of notations are provided for accessing components and attributes
141 expands to `1' if name is
146 It is the fundamental mechanism used for checking whether particular
147 variables have been assigned values.
148 All other forms of reference to undefined variables cause errors.
154 expands to the number of elements in the variable
167 Undefined variable: argv.
171 It is also possible to access the components of a variable
172 which has several values.
177 gives the first component of
179 or in the example above `a'.
189 would give `a b'. Other notations useful in shell scripts are
195 is an integer as a shorthand for
205 which is a shorthand for
213 expands to the process number of the current shell.
214 Since this process number is unique in the system it can
215 be used in generation of unique temporary file names.
220 is quite special and is replaced by the next line of input read from
221 the shell's standard input (not the script it is reading). This is
222 useful for writing shell scripts that are interactive, reading
223 commands from the terminal, or even writing a shell script that
224 acts as a filter, reading lines from its input file.
230 would write out the prompt `yes or no?' without a newline and then
231 read the answer into the variable `a'. In this case `$#a' would be
232 `0' if either a blank line or end-of-file (^D) was typed.
234 One minor difference between `$\fIn\fR\|' and `$argv[\fIn\fR\|]'
235 should be noted here.
238 will yield an error if
243 will never yield an out of range subscript error.
244 This is for compatibility with the way older shells handled parameters.
246 Another important point is that it is never an error to give a subrange
247 of the form `n\-'; if there are less than
249 components of the given variable then no words are substituted.
250 A range of the form `m\-n' likewise returns an empty vector without giving
251 an error when \fIm\fR exceeds the number of elements of the given variable,
252 provided the subscript \fIn\fR is in range.
256 In order for interesting shell scripts to be constructed it
257 must be possible to evaluate expressions in the shell based on the
259 In fact, all the arithmetic operations of the language C are available
261 with the same precedence that they have in C.
262 In particular, the operations `==' and `!=' compare strings
263 and the operators `&&' and `|\|\||' implement the boolean and/or operations.
264 The special operators `=~' and `!~' are similar to `==' and `!=' except
265 that the string on the right side can have pattern matching characters
266 (like *, ? or []) and the test is whether the string on the left matches
267 the pattern on the right.
269 The shell also allows file enquiries of the form
273 where `?' is replace by a number of single characters.
274 For instance the expression primitive
278 tell whether the file
281 Other primitives test for read, write and execute access to the file,
282 whether it is a directory, or has non-zero length.
284 It is possible to test whether a command terminates normally,
285 by a primitive of the
286 form `{ command }' which returns true, i.e. `1' if the command
287 succeeds exiting normally with exit status 0, or `0' if the command
288 terminates abnormally or with exit status non-zero.
289 If more detailed information about the execution status of a command
290 is required, it can be executed and the variable `$status' examined
292 Since `$status' is set by every command, it is very transient.
293 It can be saved if it is inconvenient to use it only in the single
294 immediately following command.
296 For a full list of expression components available see the manual
297 section for the shell.
301 A sample shell script which makes use of the expression mechanism
302 of the shell and some of its control structure follows:
306 # Copyc copies those C programs in the specified list
307 # to the directory ~/backup if they differ from the files
308 # already in ~/backup
313 if ($i !~ *.c) continue # not a .c file so do nothing
315 if (! \-r ~/backup/$i:t) then
316 echo $i:t not in backup... not cp\e\'ed
320 cmp \-s $i ~/backup/$i:t # to set $status
322 if ($status != 0) then
323 echo new backup of $i
329 This script makes use of the
331 command, which causes the shell to execute the commands between the
335 for each of the values given between `(' and `)' with the named
336 variable, in this case `i' set to successive values in the list.
337 Within this loop we may use the command
339 to stop executing the loop
342 to prematurely terminate one iteration
346 loop the iteration variable
347 (\fIi\fR in this case)
348 has the value at the last iteration.
352 here to prevent filename expansion of the members of
354 This is a good idea, in general, if the arguments to a shell script
355 are filenames which have already been expanded or if the arguments
356 may contain filename expansion metacharacters.
357 It is also possible to quote each use of a `$' variable expansion,
358 but this is harder and less reliable.
360 The other control construct used here is a statement of the form
362 \fBif\fR ( expression ) \fBthen\fR
367 The placement of the keywords here is
369 flexible due to the current implementation of the shell.\(dg
371 \(dgThe following two formats are not currently acceptable to the shell:
375 \fBif\fR ( expression ) # \fBWon't work!\fR
387 \fBif\fR ( expression ) \fBthen\fR command \fBendif\fR # \fBWon't work\fR
392 The shell does have another form of the if statement of the form
394 \fBif\fR ( expression ) \fBcommand\fR
398 \fBif\fR ( expression ) \e
401 Here we have escaped the newline for the sake of appearance.
402 The command must not involve `\||\|', `&' or `;'
403 and must not be another control command.
404 The second form requires the final `\e' to
406 precede the end-of-line.
410 statements above also admit a sequence of
412 pairs followed by a single
418 \fBif\fR ( expression ) \fBthen\fR
420 \fBelse\fR \fBif\fR (expression ) \fBthen\fR
429 Another important mechanism used in shell scripts is the `:' modifier.
430 We can use the modifier `:r' here to extract a root of a filename or
442 /mnt/foo.bar /mnt/foo bar
447 shows how the `:r' modifier strips off the trailing `.bar' and the
448 the `:e' modifier leaves only the `bar'.
449 Other modifiers will take off the last component of a pathname leaving
450 the head `:h' or all but the last component of a pathname leaving the
452 These modifiers are fully described in the
454 manual pages in the User's Reference Manual.
455 It is also possible to use the
456 .I "command substitution"
457 mechanism described in the next major section to perform modifications
458 on strings to then reenter the shell's environment.
459 Since each usage of this mechanism involves the creation of a new process,
460 it is much more expensive to use than the `:' modification mechanism.\(dd
462 \(dd It is also important to note that
463 the current implementation of the shell limits the number of `:' modifiers
464 on a `$' substitution to 1.
475 does not do what one would expect.
477 Finally, we note that the character `#' lexically introduces a shell
478 comment in shell scripts (but not from the terminal).
479 All subsequent characters on the input line after a `#' are discarded
481 This character can be quoted using `\'' or `\e' to place it in
484 Other control structures
486 The shell also has control structures
490 similar to those of C.
493 \fBwhile\fR ( expression )
499 \fBswitch\fR ( word )
517 For details see the manual section for
519 C programmers should note that we use
530 A common mistake to make in
542 statement, with labels looking like they do in C, i.e.:
549 Supplying input to commands
551 Commands run from shell scripts receive by default the standard
552 input of the shell which is running the script.
553 This is different from previous shells running
554 under \s-2UNIX\s0. It allows shell scripts to fully participate
555 in pipelines, but mandates extra notation for commands which are to take
558 Thus we need a metanotation for supplying inline data to commands in
560 As an example, consider this script which runs the editor to
561 delete leading blanks from the lines in each argument file:
564 # deblank \-\- remove leading blanks
574 The notation `<< \'EOF\''
575 means that the standard input for the
577 command is to come from the text in the shell script file
578 up to the next line consisting of exactly `\'EOF\''.
579 The fact that the `EOF' is enclosed in `\'' characters, i.e. quoted,
580 causes the shell to not perform variable substitution on the
582 In general, if any part of the word following the `<<' which the
583 shell uses to terminate the text to be given to the command is quoted
584 then these substitutions will not be performed.
585 In this case since we used the form `1,$' in our editor script
586 we needed to insure that this `$' was not variable substituted.
587 We could also have insured this by preceding the `$' here with a `\e',
592 but quoting the `EOF' terminator is a more reliable way of achieving the
597 If our shell script creates temporary files, we may wish to catch
598 interruptions of the shell script so that we can clean up
606 is a label in our program.
607 If an interrupt is received the shell will do a
609 and we can remove the temporary files and then do an
611 command (which is built in to the shell)
612 to exit from the shell script.
613 If we wish to exit with a non-zero status we can do
617 e.g. to exit with status `1'.
621 There are other features of the shell useful to writers of shell
627 options and the related
631 command line options can be used to help trace the actions of the shell.
634 option causes the shell only to read commands and not to execute
635 them and may sometimes be of use.
637 One other thing to note is that
639 will not execute shell scripts which do not begin with the
640 character `#', that is shell scripts that do not begin with a comment.
641 Similarly, the `/bin/sh' on your system may well defer to `csh'
642 to interpret shell scripts which begin with `#'.
643 This allows shell scripts for both shells to live in harmony.
645 There is also another quotation mechanism using `"' which allows
646 only some of the expansion mechanisms we have so far discussed to occur
647 on the quoted string and serves to make this string into a single word