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 $
37 Shell control structures and command scripts
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,
45 We here detail those features of the shell useful to the writers of such
50 It is important to first note what shell scripts are
53 There is a program called
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
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
66 This format is superior and preferable to maintaining a group of shell
67 procedures to maintain these files.
69 Similarly when working on a document a
71 may be created which defines how different versions of the document
72 are to be created and which options of
78 Invocation and the argv variable
82 command script may be interpreted by saying
88 is the name of the file containing a group of
91 `\&...' is replaced by a sequence of arguments.
92 The shell places these arguments in the variable
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.
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
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
117 Variable substitution
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.
130 when placed in a command script would cause the current value of the
133 to be echoed to the output of the shell script.
136 to be unset at this point.
138 A number of notations are provided for accessing components and attributes
144 expands to `1' if name is
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.
157 expands to the number of elements in the variable
170 Undefined variable: argv.
174 It is also possible to access the components of a variable
175 which has several values.
180 gives the first component of
182 or in the example above `a'.
192 would give `a b'. Other notations useful in shell scripts are
198 is an integer as a shorthand for
208 which is a shorthand for
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.
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.
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.
237 One minor difference between `$\fIn\fR\|' and `$argv[\fIn\fR\|]'
238 should be noted here.
241 will yield an error if
246 will never yield an out of range subscript error.
247 This is for compatibility with the way older shells handled parameters.
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
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.
259 In order for interesting shell scripts to be constructed it
260 must be possible to evaluate expressions in the shell based on the
262 In fact, all the arithmetic operations of the language C are available
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.
272 The shell also allows file enquiries of the form
276 where `?' is replace by a number of single characters.
277 For instance the expression primitive
281 tell whether the file
284 Other primitives test for read, write and execute access to the file,
285 whether it is a directory, or has non-zero length.
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
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.
299 For a full list of expression components available see the manual
300 section for the shell.
304 A sample shell script which makes use of the expression mechanism
305 of the shell and some of its control structure follows:
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
316 if ($i !~ *.c) continue # not a .c file so do nothing
318 if (! \-r ~/backup/$i:t) then
319 echo $i:t not in backup... not cp\e\'ed
323 cmp \-s $i ~/backup/$i:t # to set $status
325 if ($status != 0) then
326 echo new backup of $i
332 This script makes use of the
334 command, which causes the shell to execute the commands between the
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
342 to stop executing the loop
345 to prematurely terminate one iteration
349 loop the iteration variable
350 (\fIi\fR in this case)
351 has the value at the last iteration.
355 here to prevent filename expansion of the members of
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.
363 The other control construct used here is a statement of the form
365 \fBif\fR ( expression ) \fBthen\fR
370 The placement of the keywords here is
372 flexible due to the current implementation of the shell.\(dg
374 \(dgThe following two formats are not currently acceptable to the shell:
378 \fBif\fR ( expression ) # \fBWon't work!\fR
390 \fBif\fR ( expression ) \fBthen\fR command \fBendif\fR # \fBWon't work\fR
395 The shell does have another form of the if statement of the form
397 \fBif\fR ( expression ) \fBcommand\fR
401 \fBif\fR ( expression ) \e
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
409 precede the end-of-line.
413 statements above also admit a sequence of
415 pairs followed by a single
421 \fBif\fR ( expression ) \fBthen\fR
423 \fBelse\fR \fBif\fR (expression ) \fBthen\fR
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
445 /mnt/foo.bar /mnt/foo bar
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
455 These modifiers are fully described in the
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
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.
478 does not do what one would expect.
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
484 This character can be quoted using `\'' or `\e' to place it in
487 Other control structures
489 The shell also has control structures
493 similar to those of C.
496 \fBwhile\fR ( expression )
502 \fBswitch\fR ( word )
520 For details see the manual section for
522 C programmers should note that we use
533 A common mistake to make in
545 statement, with labels looking like they do in C, i.e.:
552 Supplying input to commands
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
561 Thus we need a metanotation for supplying inline data to commands in
563 As an example, consider this script which runs the editor to
564 delete leading blanks from the lines in each argument file:
567 # deblank \-\- remove leading blanks
577 The notation `<< \'EOF\''
578 means that the standard input for the
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
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',
595 but quoting the `EOF' terminator is a more reliable way of achieving the
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
609 is a label in our program.
610 If an interrupt is received the shell will do a
612 and we can remove the temporary files and then do an
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
620 e.g. to exit with status `1'.
624 There are other features of the shell useful to writers of shell
630 options and the related
634 command line options can be used to help trace the actions of the shell.
637 option causes the shell only to read commands and not to execute
638 them and may sometimes be of use.
640 One other thing to note is that
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.
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