home *** CD-ROM | disk | FTP | other *** search
/ InfoMagic Source Code 1993 July / THE_SOURCE_CODE_CD_ROM.iso / bsd_srcs / share / doc / usd / 04.csh / csh.3 < prev    next >
Encoding:
Text File  |  1991-04-17  |  16.7 KB  |  651 lines

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