Debian Codegraph @

HTML/assortedtips.html

raw symbols SCIP
1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
2 <HTML
3 ><HEAD
4 ><TITLE
5 >Assorted Tips</TITLE
6 ><META
7 NAME="GENERATOR"
8 CONTENT="Modular DocBook HTML Stylesheet Version 1.76b+
9 "><LINK
10 REL="HOME"
11 TITLE="Advanced Bash-Scripting Guide"
12 HREF="index.html"><LINK
13 REL="UP"
14 TITLE="Miscellany"
15 HREF="miscellany.html"><LINK
16 REL="PREVIOUS"
17 TITLE="Optimizations"
18 HREF="optimizations.html"><LINK
19 REL="NEXT"
20 TITLE="Security Issues"
21 HREF="securityissues.html"><META
22 HTTP-EQUIV="Content-Style-Type"
23 CONTENT="text/css"><LINK
24 REL="stylesheet"
25 HREF="common/kde-common.css"
26 TYPE="text/css"><META
27 HTTP-EQUIV="Content-Type"
28 CONTENT="text/html; charset=iso-8859-1"><META
29 HTTP-EQUIV="Content-Language"
30 CONTENT="en"><LINK
31 REL="stylesheet"
32 HREF="common/kde-localised.css"
33 TYPE="text/css"
34 TITLE="KDE-English"><LINK
35 REL="stylesheet"
36 HREF="common/kde-default.css"
37 TYPE="text/css"
38 TITLE="KDE-Default"></HEAD
39 ><BODY
40 CLASS="SECT1"
41 BGCOLOR="#FFFFFF"
42 TEXT="#000000"
43 LINK="#AA0000"
44 VLINK="#AA0055"
45 ALINK="#AA0000"
46 STYLE="font-family: sans-serif;"
47 ><DIV
48 CLASS="NAVHEADER"
49 ><TABLE
50 SUMMARY="Header navigation table"
51 WIDTH="100%"
52 BORDER="0"
53 CELLPADDING="0"
54 CELLSPACING="0"
55 ><TR
56 ><TH
57 COLSPAN="3"
58 ALIGN="center"
59 >Advanced Bash-Scripting Guide: An in-depth exploration of the art of shell scripting</TH
60 ></TR
61 ><TR
62 ><TD
63 WIDTH="10%"
64 ALIGN="left"
65 VALIGN="bottom"
66 ><A
67 HREF="optimizations.html"
68 ACCESSKEY="P"
69 >Prev</A
70 ></TD
71 ><TD
72 WIDTH="80%"
73 ALIGN="center"
74 VALIGN="bottom"
75 >Chapter 36. Miscellany</TD
76 ><TD
77 WIDTH="10%"
78 ALIGN="right"
79 VALIGN="bottom"
80 ><A
81 HREF="securityissues.html"
82 ACCESSKEY="N"
83 >Next</A
84 ></TD
85 ></TR
86 ></TABLE
87 ><HR
88 ALIGN="LEFT"
89 WIDTH="100%"></DIV
90 ><DIV
91 CLASS="SECT1"
92 ><H1
93 CLASS="SECT1"
94 ><A
95 NAME="ASSORTEDTIPS"
96 ></A
97 >36.7. Assorted Tips</H1
98 ><DIV
99 CLASS="SECT2"
100 ><H2
101 CLASS="SECT2"
102 ><A
103 NAME="AEN20460"
104 ></A
105 >36.7.1. Ideas for more powerful scripts</H2
106 ><UL
107 ><LI
108 ><P
109 ><A
110 NAME="PSEUDOCODEREF"
111 ></A
112 ></P
113 ><P
114 >You have a problem that you want to solve by writing a Bash
115 script. Unfortunately, you don't know quite where to start.
116 One method is to plunge right in and code those parts
117 of the script that come easily, and write the hard parts as
118 <I
119 CLASS="FIRSTTERM"
120 >pseudo-code</I
121 >.</P
122 ><P
123 ><TABLE
124 BORDER="0"
125 BGCOLOR="#E0E0E0"
126 WIDTH="90%"
127 ><TR
128 ><TD
129 ><PRE
130 CLASS="PROGRAMLISTING"
131 > 1&nbsp;#!/bin/bash
132 2&nbsp;
133 3&nbsp;ARGCOUNT=1 # Need name as argument.
134 4&nbsp;E_WRONGARGS=65
135 5&nbsp;
136 6&nbsp;if [ number-of-arguments is-not-equal-to "$ARGCOUNT" ]
137 7&nbsp;# ^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^
138 8&nbsp;# Can't figure out how to code this . . .
139 9&nbsp;#+ . . . so write it in pseudo-code.
140 10&nbsp;
141 11&nbsp;then
142 12&nbsp; echo "Usage: name-of-script name"
143 13&nbsp; # ^^^^^^^^^^^^^^ More pseudo-code.
144 14&nbsp; exit $E_WRONGARGS
145 15&nbsp;fi
146 16&nbsp;
147 17&nbsp;. . .
148 18&nbsp;
149 19&nbsp;exit 0
150 20&nbsp;
151 21&nbsp;
152 22&nbsp;# Later on, substitute working code for the pseudo-code.
153 23&nbsp;
154 24&nbsp;# Line 6 becomes:
155 25&nbsp;if [ $# -ne "$ARGCOUNT" ]
156 26&nbsp;
157 27&nbsp;# Line 12 becomes:
158 28&nbsp; echo "Usage: `basename $0` name"</PRE
159 ></TD
160 ></TR
161 ></TABLE
162 ></P
163 ><P
164 >For an example of using pseudo-code, see the <A
165 HREF="writingscripts.html#NEWTONSQRT"
166 >Square Root</A
167 > exercise.</P
168 ></LI
169 ><LI
170 ><P
171 ><A
172 NAME="TRACKINGSCR"
173 ></A
174 ></P
175 ><P
176 >To keep a record of which user scripts have run
177 during a particular session or over a number of sessions,
178 add the following lines to each script you want to keep track
179 of. This will keep a continuing file record of the script
180 names and invocation times. </P
181 ><P
182 > <TABLE
183 BORDER="0"
184 BGCOLOR="#E0E0E0"
185 WIDTH="90%"
186 ><TR
187 ><TD
188 ><PRE
189 CLASS="PROGRAMLISTING"
190 > 1&nbsp;# Append (&#62;&#62;) following to end of each script tracked.
191 2&nbsp;
192 3&nbsp;whoami&#62;&#62; $SAVE_FILE # User invoking the script.
193 4&nbsp;echo $0&#62;&#62; $SAVE_FILE # Script name.
194 5&nbsp;date&#62;&#62; $SAVE_FILE # Date and time.
195 6&nbsp;echo&#62;&#62; $SAVE_FILE # Blank line as separator.
196 7&nbsp;
197 8&nbsp;# Of course, SAVE_FILE defined and exported as environmental variable in ~/.bashrc
198 9&nbsp;#+ (something like ~/.scripts-run)</PRE
199 ></TD
200 ></TR
201 ></TABLE
202 >
203 </P
204 ></LI
205 ><LI
206 ><P
207 ><A
208 NAME="PREPENDREF"
209 ></A
210 ></P
211 ><P
212 >The <SPAN
213 CLASS="TOKEN"
214 >&#62;&#62;</SPAN
215 > operator
216 <I
217 CLASS="FIRSTTERM"
218 >appends</I
219 > lines to a file.
220 What if you wish to <I
221 CLASS="FIRSTTERM"
222 >prepend</I
223 > a
224 line to an existing file, that is, to paste it in at the
225 beginning?</P
226 ><P
227 > <TABLE
228 BORDER="0"
229 BGCOLOR="#E0E0E0"
230 WIDTH="90%"
231 ><TR
232 ><TD
233 ><PRE
234 CLASS="PROGRAMLISTING"
235 > 1&nbsp;file=data.txt
236 2&nbsp;title="***This is the title line of data text file***"
237 3&nbsp;
238 4&nbsp;echo $title | cat - $file &#62;$file.new
239 5&nbsp;# "cat -" concatenates stdout to $file.
240 6&nbsp;# End result is
241 7&nbsp;#+ to write a new file with $title appended at *beginning*.</PRE
242 ></TD
243 ></TR
244 ></TABLE
245 >
246 </P
247 ><P
248 >This is a simplified variant of the <A
249 HREF="here-docs.html#PREPENDEX"
250 >Example 19-13</A
251 > script given earlier. And, of course,
252 <A
253 HREF="sedawk.html#SEDREF"
254 >sed</A
255 > can also do this.</P
256 ></LI
257 ><LI
258 ><P
259 ><A
260 NAME="SCRIPTASEMB"
261 ></A
262 ></P
263 ><P
264 >A shell script may act as an embedded command inside
265 another shell script, a <I
266 CLASS="FIRSTTERM"
267 >Tcl</I
268 > or
269 <I
270 CLASS="FIRSTTERM"
271 >wish</I
272 > script, or even a <A
273 HREF="filearchiv.html#MAKEFILEREF"
274 >Makefile</A
275 >. It can be invoked
276 as an external shell command in a C program using the
277 <TT
278 CLASS="REPLACEABLE"
279 ><I
280 >system()</I
281 ></TT
282 > call, i.e.,
283 <TT
284 CLASS="REPLACEABLE"
285 ><I
286 >system("script_name");</I
287 ></TT
288 >.</P
289 ></LI
290 ><LI
291 ><P
292 ><A
293 NAME="SETVAREMB"
294 ></A
295 ></P
296 ><P
297 >Setting a variable to the contents of an embedded
298 <I
299 CLASS="FIRSTTERM"
300 >sed</I
301 > or <I
302 CLASS="FIRSTTERM"
303 >awk</I
304 >
305 script increases the readability of the surrounding <A
306 HREF="wrapper.html#SHWRAPPER"
307 >shell wrapper</A
308 >. See <A
309 HREF="contributed-scripts.html#MAILFORMAT"
310 >Example A-1</A
311 > and <A
312 HREF="internal.html#COLTOTALER3"
313 >Example 15-20</A
314 >.</P
315 ></LI
316 ><LI
317 ><P
318 ><A
319 NAME="LIBROUTINES"
320 ></A
321 ></P
322 ><P
323 >Put together files containing your favorite and most useful
324 definitions and functions. As necessary,
325 <SPAN
326 CLASS="QUOTE"
327 >"include"</SPAN
328 > one or more of these
329 <SPAN
330 CLASS="QUOTE"
331 >"library files"</SPAN
332 > in scripts with either the
333 <A
334 HREF="special-chars.html#DOTREF"
335 >dot</A
336 > (<B
337 CLASS="COMMAND"
338 >.</B
339 >)
340 or <A
341 HREF="internal.html#SOURCEREF"
342 >source</A
343 > command.</P
344 ><P
345 >
346 <TABLE
347 BORDER="0"
348 BGCOLOR="#E0E0E0"
349 WIDTH="90%"
350 ><TR
351 ><TD
352 ><PRE
353 CLASS="PROGRAMLISTING"
354 > 1&nbsp;# SCRIPT LIBRARY
355 2&nbsp;# ------ -------
356 3&nbsp;
357 4&nbsp;# Note:
358 5&nbsp;# No "#!" here.
359 6&nbsp;# No "live code" either.
360 7&nbsp;
361 8&nbsp;
362 9&nbsp;# Useful variable definitions
363 10&nbsp;
364 11&nbsp;ROOT_UID=0 # Root has $UID 0.
365 12&nbsp;E_NOTROOT=101 # Not root user error.
366 13&nbsp;MAXRETVAL=255 # Maximum (positive) return value of a function.
367 14&nbsp;SUCCESS=0
368 15&nbsp;FAILURE=-1
369 16&nbsp;
370 17&nbsp;
371 18&nbsp;
372 19&nbsp;# Functions
373 20&nbsp;
374 21&nbsp;Usage () # "Usage:" message.
375 22&nbsp;{
376 23&nbsp; if [ -z "$1" ] # No arg passed.
377 24&nbsp; then
378 25&nbsp; msg=filename
379 26&nbsp; else
380 27&nbsp; msg=$@
381 28&nbsp; fi
382 29&nbsp;
383 30&nbsp; echo "Usage: `basename $0` "$msg""
384 31&nbsp;}
385 32&nbsp;
386 33&nbsp;
387 34&nbsp;Check_if_root () # Check if root running script.
388 35&nbsp;{ # From "ex39.sh" example.
389 36&nbsp; if [ "$UID" -ne "$ROOT_UID" ]
390 37&nbsp; then
391 38&nbsp; echo "Must be root to run this script."
392 39&nbsp; exit $E_NOTROOT
393 40&nbsp; fi
394 41&nbsp;}
395 42&nbsp;
396 43&nbsp;
397 44&nbsp;CreateTempfileName () # Creates a "unique" temp filename.
398 45&nbsp;{ # From "ex51.sh" example.
399 46&nbsp; prefix=temp
400 47&nbsp; suffix=`eval date +%s`
401 48&nbsp; Tempfilename=$prefix.$suffix
402 49&nbsp;}
403 50&nbsp;
404 51&nbsp;
405 52&nbsp;isalpha2 () # Tests whether *entire string* is alphabetic.
406 53&nbsp;{ # From "isalpha.sh" example.
407 54&nbsp; [ $# -eq 1 ] || return $FAILURE
408 55&nbsp;
409 56&nbsp; case $1 in
410 57&nbsp; *[!a-zA-Z]*|"") return $FAILURE;;
411 58&nbsp; *) return $SUCCESS;;
412 59&nbsp; esac # Thanks, S.C.
413 60&nbsp;}
414 61&nbsp;
415 62&nbsp;
416 63&nbsp;abs () # Absolute value.
417 64&nbsp;{ # Caution: Max return value = 255.
418 65&nbsp; E_ARGERR=-999999
419 66&nbsp;
420 67&nbsp; if [ -z "$1" ] # Need arg passed.
421 68&nbsp; then
422 69&nbsp; return $E_ARGERR # Obvious error value returned.
423 70&nbsp; fi
424 71&nbsp;
425 72&nbsp; if [ "$1" -ge 0 ] # If non-negative,
426 73&nbsp; then #
427 74&nbsp; absval=$1 # stays as-is.
428 75&nbsp; else # Otherwise,
429 76&nbsp; let "absval = (( 0 - $1 ))" # change sign.
430 77&nbsp; fi
431 78&nbsp;
432 79&nbsp; return $absval
433 80&nbsp;}
434 81&nbsp;
435 82&nbsp;
436 83&nbsp;tolower () # Converts string(s) passed as argument(s)
437 84&nbsp;{ #+ to lowercase.
438 85&nbsp;
439 86&nbsp; if [ -z "$1" ] # If no argument(s) passed,
440 87&nbsp; then #+ send error message
441 88&nbsp; echo "(null)" #+ (C-style void-pointer error message)
442 89&nbsp; return #+ and return from function.
443 90&nbsp; fi
444 91&nbsp;
445 92&nbsp; echo "$@" | tr A-Z a-z
446 93&nbsp; # Translate all passed arguments ($@).
447 94&nbsp;
448 95&nbsp; return
449 96&nbsp;
450 97&nbsp;# Use command substitution to set a variable to function output.
451 98&nbsp;# For example:
452 99&nbsp;# oldvar="A seT of miXed-caSe LEtTerS"
453 100&nbsp;# newvar=`tolower "$oldvar"`
454 101&nbsp;# echo "$newvar" # a set of mixed-case letters
455 102&nbsp;#
456 103&nbsp;# Exercise: Rewrite this function to change lowercase passed argument(s)
457 104&nbsp;# to uppercase ... toupper() [easy].
458 105&nbsp;}</PRE
459 ></TD
460 ></TR
461 ></TABLE
462 >
463 </P
464 ></LI
465 ><LI
466 ><P
467 ><A
468 NAME="COMMENTH"
469 ></A
470 ></P
471 ><P
472 >Use special-purpose comment headers to increase clarity
473 and legibility in scripts.</P
474 ><P
475 ><TABLE
476 BORDER="0"
477 BGCOLOR="#E0E0E0"
478 WIDTH="90%"
479 ><TR
480 ><TD
481 ><PRE
482 CLASS="PROGRAMLISTING"
483 > 1&nbsp;## Caution.
484 2&nbsp;rm -rf *.zzy ## The "-rf" options to "rm" are very dangerous,
485 3&nbsp; ##+ especially with wild cards.
486 4&nbsp;
487 5&nbsp;#+ Line continuation.
488 6&nbsp;# This is line 1
489 7&nbsp;#+ of a multi-line comment,
490 8&nbsp;#+ and this is the final line.
491 9&nbsp;
492 10&nbsp;#* Note.
493 11&nbsp;
494 12&nbsp;#o List item.
495 13&nbsp;
496 14&nbsp;#&#62; Another point of view.
497 15&nbsp;while [ "$var1" != "end" ] #&#62; while test "$var1" != "end"</PRE
498 ></TD
499 ></TR
500 ></TABLE
501 ></P
502 ></LI
503 ><LI
504 ><P
505 ><A
506 NAME="PROGBAR"
507 ></A
508 ></P
509 ><P
510 >Dotan Barak contributes template code for a
511 <I
512 CLASS="FIRSTTERM"
513 >progress bar</I
514 > in a script.</P
515 ><DIV
516 CLASS="EXAMPLE"
517 ><HR><A
518 NAME="PROGRESSBAR"
519 ></A
520 ><P
521 ><B
522 >Example 36-17. A Progress Bar</B
523 ></P
524 ><TABLE
525 BORDER="0"
526 BGCOLOR="#E0E0E0"
527 WIDTH="90%"
528 ><TR
529 ><TD
530 ><PRE
531 CLASS="PROGRAMLISTING"
532 > 1&nbsp;#!/bin/bash
533 2&nbsp;# progress-bar.sh
534 3&nbsp;
535 4&nbsp;# Author: Dotan Barak (very minor revisions by ABS Guide author).
536 5&nbsp;# Used in ABS Guide with permission (thanks!).
537 6&nbsp;
538 7&nbsp;
539 8&nbsp;BAR_WIDTH=50
540 9&nbsp;BAR_CHAR_START="["
541 10&nbsp;BAR_CHAR_END="]"
542 11&nbsp;BAR_CHAR_EMPTY="."
543 12&nbsp;BAR_CHAR_FULL="="
544 13&nbsp;BRACKET_CHARS=2
545 14&nbsp;LIMIT=100
546 15&nbsp;
547 16&nbsp;print_progress_bar()
548 17&nbsp;{
549 18&nbsp; # Calculate how many characters will be full.
550 19&nbsp; let "full_limit = ((($1 - $BRACKET_CHARS) * $2) / $LIMIT)"
551 20&nbsp;
552 21&nbsp; # Calculate how many characters will be empty.
553 22&nbsp; let "empty_limit = ($1 - $BRACKET_CHARS) - ${full_limit}"
554 23&nbsp;
555 24&nbsp; # Prepare the bar.
556 25&nbsp; bar_line="${BAR_CHAR_START}"
557 26&nbsp; for ((j=0; j&#60;full_limit; j++)); do
558 27&nbsp; bar_line="${bar_line}${BAR_CHAR_FULL}"
559 28&nbsp; done
560 29&nbsp;
561 30&nbsp; for ((j=0; j&#60;empty_limit; j++)); do
562 31&nbsp; bar_line="${bar_line}${BAR_CHAR_EMPTY}"
563 32&nbsp; done
564 33&nbsp;
565 34&nbsp; bar_line="${bar_line}${BAR_CHAR_END}"
566 35&nbsp;
567 36&nbsp; printf "%3d%% %s" $2 ${bar_line}
568 37&nbsp;}
569 38&nbsp;
570 39&nbsp;# Here is a sample of code that uses it.
571 40&nbsp;MAX_PERCENT=100
572 41&nbsp;for ((i=0; i&#60;=MAX_PERCENT; i++)); do
573 42&nbsp; #
574 43&nbsp; usleep 10000
575 44&nbsp; # ... Or run some other commands ...
576 45&nbsp; #
577 46&nbsp; print_progress_bar ${BAR_WIDTH} ${i}
578 47&nbsp; echo -en "\r"
579 48&nbsp;done
580 49&nbsp;
581 50&nbsp;echo ""
582 51&nbsp;
583 52&nbsp;exit</PRE
584 ></TD
585 ></TR
586 ></TABLE
587 ><HR></DIV
588 ></LI
589 ><LI
590 ><P
591 ><A
592 NAME="COMOUTBL"
593 ></A
594 ></P
595 ><P
596 >A particularly clever use of <A
597 HREF="tests.html#TESTCONSTRUCTS1"
598 >if-test</A
599 > constructs
600 is for comment blocks.</P
601 ><P
602 >
603 <TABLE
604 BORDER="0"
605 BGCOLOR="#E0E0E0"
606 WIDTH="90%"
607 ><TR
608 ><TD
609 ><PRE
610 CLASS="PROGRAMLISTING"
611 > 1&nbsp;#!/bin/bash
612 2&nbsp;
613 3&nbsp;COMMENT_BLOCK=
614 4&nbsp;# Try setting the above variable to some value
615 5&nbsp;#+ for an unpleasant surprise.
616 6&nbsp;
617 7&nbsp;if [ $COMMENT_BLOCK ]; then
618 8&nbsp;
619 9&nbsp;Comment block --
620 10&nbsp;=================================
621 11&nbsp;This is a comment line.
622 12&nbsp;This is another comment line.
623 13&nbsp;This is yet another comment line.
624 14&nbsp;=================================
625 15&nbsp;
626 16&nbsp;echo "This will not echo."
627 17&nbsp;
628 18&nbsp;Comment blocks are error-free! Whee!
629 19&nbsp;
630 20&nbsp;fi
631 21&nbsp;
632 22&nbsp;echo "No more comments, please."
633 23&nbsp;
634 24&nbsp;exit 0</PRE
635 ></TD
636 ></TR
637 ></TABLE
638 >
639 </P
640 ><P
641 >Compare this with <A
642 HREF="here-docs.html#CBLOCK1"
643 >using
644 here documents to comment out code blocks</A
645 >.</P
646 ></LI
647 ><LI
648 ><P
649 ><A
650 NAME="INTPARAM"
651 ></A
652 ></P
653 ><P
654 >Using the <A
655 HREF="variables2.html#XSTATVARREF"
656 >$? exit status
657 variable</A
658 >, a script may test if a parameter contains
659 only digits, so it can be treated as an integer.</P
660 ><P
661 >
662 <TABLE
663 BORDER="0"
664 BGCOLOR="#E0E0E0"
665 WIDTH="90%"
666 ><TR
667 ><TD
668 ><PRE
669 CLASS="PROGRAMLISTING"
670 > 1&nbsp;#!/bin/bash
671 2&nbsp;
672 3&nbsp;SUCCESS=0
673 4&nbsp;E_BADINPUT=85
674 5&nbsp;
675 6&nbsp;test "$1" -ne 0 -o "$1" -eq 0 2&#62;/dev/null
676 7&nbsp;# An integer is either equal to 0 or not equal to 0.
677 8&nbsp;# 2&#62;/dev/null suppresses error message.
678 9&nbsp;
679 10&nbsp;if [ $? -ne "$SUCCESS" ]
680 11&nbsp;then
681 12&nbsp; echo "Usage: `basename $0` integer-input"
682 13&nbsp; exit $E_BADINPUT
683 14&nbsp;fi
684 15&nbsp;
685 16&nbsp;let "sum = $1 + 25" # Would give error if $1 not integer.
686 17&nbsp;echo "Sum = $sum"
687 18&nbsp;
688 19&nbsp;# Any variable, not just a command-line parameter, can be tested this way.
689 20&nbsp;
690 21&nbsp;exit 0</PRE
691 ></TD
692 ></TR
693 ></TABLE
694 >
695 </P
696 ></LI
697 ><LI
698 ><P
699 ><A
700 NAME="RVT"
701 ></A
702 >The 0 - 255 range for function return
703 values is a severe limitation. Global variables and
704 other workarounds are often problematic. An alternative
705 method for a function to communicate a value back to
706 the main body of the script is to have the function
707 write to <TT
708 CLASS="FILENAME"
709 >stdout</TT
710 > (usually with
711 <A
712 HREF="internal.html#ECHOREF"
713 >echo</A
714 >) the <SPAN
715 CLASS="QUOTE"
716 >"return
717 value,"</SPAN
718 > and assign this to a variable. This is
719 actually a variant of <A
720 HREF="commandsub.html#COMMANDSUBREF"
721 >command
722 substitution.</A
723 ></P
724 ><DIV
725 CLASS="EXAMPLE"
726 ><HR><A
727 NAME="MULTIPLICATION"
728 ></A
729 ><P
730 ><B
731 >Example 36-18. Return value trickery</B
732 ></P
733 ><TABLE
734 BORDER="0"
735 BGCOLOR="#E0E0E0"
736 WIDTH="90%"
737 ><TR
738 ><TD
739 ><PRE
740 CLASS="PROGRAMLISTING"
741 > 1&nbsp;#!/bin/bash
742 2&nbsp;# multiplication.sh
743 3&nbsp;
744 4&nbsp;multiply () # Multiplies params passed.
745 5&nbsp;{ # Will accept a variable number of args.
746 6&nbsp;
747 7&nbsp; local product=1
748 8&nbsp;
749 9&nbsp; until [ -z "$1" ] # Until uses up arguments passed...
750 10&nbsp; do
751 11&nbsp; let "product *= $1"
752 12&nbsp; shift
753 13&nbsp; done
754 14&nbsp;
755 15&nbsp; echo $product # Will not echo to stdout,
756 16&nbsp;} #+ since this will be assigned to a variable.
757 17&nbsp;
758 18&nbsp;mult1=15383; mult2=25211
759 19&nbsp;val1=`multiply $mult1 $mult2`
760 20&nbsp;# Assigns stdout (echo) of function to the variable val1.
761 21&nbsp;echo "$mult1 X $mult2 = $val1" # 387820813
762 22&nbsp;
763 23&nbsp;mult1=25; mult2=5; mult3=20
764 24&nbsp;val2=`multiply $mult1 $mult2 $mult3`
765 25&nbsp;echo "$mult1 X $mult2 X $mult3 = $val2" # 2500
766 26&nbsp;
767 27&nbsp;mult1=188; mult2=37; mult3=25; mult4=47
768 28&nbsp;val3=`multiply $mult1 $mult2 $mult3 $mult4`
769 29&nbsp;echo "$mult1 X $mult2 X $mult3 X $mult4 = $val3" # 8173300
770 30&nbsp;
771 31&nbsp;exit 0</PRE
772 ></TD
773 ></TR
774 ></TABLE
775 ><HR></DIV
776 ><P
777 >The same technique also works for alphanumeric
778 strings. This means that a function can <SPAN
779 CLASS="QUOTE"
780 >"return"</SPAN
781 >
782 a non-numeric value.</P
783 ><P
784 > <TABLE
785 BORDER="0"
786 BGCOLOR="#E0E0E0"
787 WIDTH="90%"
788 ><TR
789 ><TD
790 ><PRE
791 CLASS="PROGRAMLISTING"
792 > 1&nbsp;capitalize_ichar () # Capitalizes initial character
793 2&nbsp;{ #+ of argument string(s) passed.
794 3&nbsp;
795 4&nbsp; string0="$@" # Accepts multiple arguments.
796 5&nbsp;
797 6&nbsp; firstchar=${string0:0:1} # First character.
798 7&nbsp; string1=${string0:1} # Rest of string(s).
799 8&nbsp;
800 9&nbsp; FirstChar=`echo "$firstchar" | tr a-z A-Z`
801 10&nbsp; # Capitalize first character.
802 11&nbsp;
803 12&nbsp; echo "$FirstChar$string1" # Output to stdout.
804 13&nbsp;
805 14&nbsp;}
806 15&nbsp;
807 16&nbsp;newstring=`capitalize_ichar "every sentence should start with a capital letter."`
808 17&nbsp;echo "$newstring" # Every sentence should start with a capital letter.</PRE
809 ></TD
810 ></TR
811 ></TABLE
812 >
813 </P
814 ><P
815 >It is even possible for a function to <SPAN
816 CLASS="QUOTE"
817 >"return"</SPAN
818 >
819 multiple values with this method.</P
820 ><DIV
821 CLASS="EXAMPLE"
822 ><HR><A
823 NAME="SUMPRODUCT"
824 ></A
825 ><P
826 ><B
827 >Example 36-19. Even more return value trickery</B
828 ></P
829 ><TABLE
830 BORDER="0"
831 BGCOLOR="#E0E0E0"
832 WIDTH="90%"
833 ><TR
834 ><TD
835 ><PRE
836 CLASS="PROGRAMLISTING"
837 > 1&nbsp;#!/bin/bash
838 2&nbsp;# sum-product.sh
839 3&nbsp;# A function may "return" more than one value.
840 4&nbsp;
841 5&nbsp;sum_and_product () # Calculates both sum and product of passed args.
842 6&nbsp;{
843 7&nbsp; echo $(( $1 + $2 )) $(( $1 * $2 ))
844 8&nbsp;# Echoes to stdout each calculated value, separated by space.
845 9&nbsp;}
846 10&nbsp;
847 11&nbsp;echo
848 12&nbsp;echo "Enter first number "
849 13&nbsp;read first
850 14&nbsp;
851 15&nbsp;echo
852 16&nbsp;echo "Enter second number "
853 17&nbsp;read second
854 18&nbsp;echo
855 19&nbsp;
856 20&nbsp;retval=`sum_and_product $first $second` # Assigns output of function.
857 21&nbsp;sum=`echo "$retval" | awk '{print $1}'` # Assigns first field.
858 22&nbsp;product=`echo "$retval" | awk '{print $2}'` # Assigns second field.
859 23&nbsp;
860 24&nbsp;echo "$first + $second = $sum"
861 25&nbsp;echo "$first * $second = $product"
862 26&nbsp;echo
863 27&nbsp;
864 28&nbsp;exit 0</PRE
865 ></TD
866 ></TR
867 ></TABLE
868 ><HR></DIV
869 ><DIV
870 CLASS="CAUTION"
871 ><TABLE
872 CLASS="CAUTION"
873 WIDTH="90%"
874 BORDER="0"
875 ><TR
876 ><TD
877 WIDTH="25"
878 ALIGN="CENTER"
879 VALIGN="TOP"
880 ><IMG
881 SRC="common/caution.png"
882 HSPACE="5"
883 ALT="Caution"></TD
884 ><TD
885 ALIGN="LEFT"
886 VALIGN="TOP"
887 ><P
888 ><A
889 NAME="RVTCAUTION"
890 ></A
891 >There can be only
892 <B
893 CLASS="COMMAND"
894 >one</B
895 > <I
896 CLASS="FIRSTTERM"
897 >echo</I
898 > statement
899 in the function for this to work. If you alter the previous
900 example:</P
901 ><P
902 ><TABLE
903 BORDER="0"
904 BGCOLOR="#E0E0E0"
905 WIDTH="90%"
906 ><TR
907 ><TD
908 ><PRE
909 CLASS="PROGRAMLISTING"
910 > 1&nbsp;sum_and_product ()
911 2&nbsp;{
912 3&nbsp; echo "This is the sum_and_product function." # This messes things up!
913 4&nbsp; echo $(( $1 + $2 )) $(( $1 * $2 ))
914 5&nbsp;}
915 6&nbsp;...
916 7&nbsp;retval=`sum_and_product $first $second` # Assigns output of function.
917 8&nbsp;# Now, this will not work correctly.</PRE
918 ></TD
919 ></TR
920 ></TABLE
921 ></P
922 ></TD
923 ></TR
924 ></TABLE
925 ></DIV
926 ></LI
927 ><LI
928 ><P
929 ><A
930 NAME="PASSARRAY"
931 ></A
932 ></P
933 ><P
934 >Next in our bag of tricks are techniques for passing
935 an <A
936 HREF="arrays.html#ARRAYREF"
937 >array</A
938 > to a
939 <A
940 HREF="functions.html#FUNCTIONREF"
941 >function</A
942 >, then
943 <SPAN
944 CLASS="QUOTE"
945 >"returning"</SPAN
946 > an array back to the main body of
947 the script.</P
948 ><P
949 >Passing an array involves loading the space-separated
950 elements of the array into a variable with <A
951 HREF="commandsub.html#COMMANDSUBREF"
952 >command substitution</A
953 >. <A
954 NAME="RETARRAY"
955 ></A
956 >Getting an array back as the <SPAN
957 CLASS="QUOTE"
958 >"return
959 value"</SPAN
960 > from a function uses the previously mentioned
961 strategem of <A
962 HREF="internal.html#ECHOREF"
963 >echoing</A
964 > the
965 array in the function, then invoking command substitution
966 and the <B
967 CLASS="COMMAND"
968 >( ... )</B
969 > operator to assign it to
970 an array.</P
971 ><DIV
972 CLASS="EXAMPLE"
973 ><HR><A
974 NAME="ARRFUNC"
975 ></A
976 ><P
977 ><B
978 >Example 36-20. Passing and returning arrays</B
979 ></P
980 ><TABLE
981 BORDER="0"
982 BGCOLOR="#E0E0E0"
983 WIDTH="90%"
984 ><TR
985 ><TD
986 ><PRE
987 CLASS="PROGRAMLISTING"
988 > 1&nbsp;#!/bin/bash
989 2&nbsp;# array-function.sh: Passing an array to a function and ...
990 3&nbsp;# "returning" an array from a function
991 4&nbsp;
992 5&nbsp;
993 6&nbsp;Pass_Array ()
994 7&nbsp;{
995 8&nbsp; local passed_array # Local variable!
996 9&nbsp; passed_array=( `echo "$1"` )
997 10&nbsp; echo "${passed_array[@]}"
998 11&nbsp; # List all the elements of the new array
999 12&nbsp; #+ declared and set within the function.
1000 13&nbsp;}
1001 14&nbsp;
1002 15&nbsp;
1003 16&nbsp;original_array=( element1 element2 element3 element4 element5 )
1004 17&nbsp;
1005 18&nbsp;echo
1006 19&nbsp;echo "original_array = ${original_array[@]}"
1007 20&nbsp;# List all elements of original array.
1008 21&nbsp;
1009 22&nbsp;
1010 23&nbsp;# This is the trick that permits passing an array to a function.
1011 24&nbsp;# **********************************
1012 25&nbsp;argument=`echo ${original_array[@]}`
1013 26&nbsp;# **********************************
1014 27&nbsp;# Pack a variable
1015 28&nbsp;#+ with all the space-separated elements of the original array.
1016 29&nbsp;#
1017 30&nbsp;# Attempting to just pass the array itself will not work.
1018 31&nbsp;
1019 32&nbsp;
1020 33&nbsp;# This is the trick that allows grabbing an array as a "return value".
1021 34&nbsp;# *****************************************
1022 35&nbsp;returned_array=( `Pass_Array "$argument"` )
1023 36&nbsp;# *****************************************
1024 37&nbsp;# Assign 'echoed' output of function to array variable.
1025 38&nbsp;
1026 39&nbsp;echo "returned_array = ${returned_array[@]}"
1027 40&nbsp;
1028 41&nbsp;echo "============================================================="
1029 42&nbsp;
1030 43&nbsp;# Now, try it again,
1031 44&nbsp;#+ attempting to access (list) the array from outside the function.
1032 45&nbsp;Pass_Array "$argument"
1033 46&nbsp;
1034 47&nbsp;# The function itself lists the array, but ...
1035 48&nbsp;#+ accessing the array from outside the function is forbidden.
1036 49&nbsp;echo "Passed array (within function) = ${passed_array[@]}"
1037 50&nbsp;# NULL VALUE since the array is a variable local to the function.
1038 51&nbsp;
1039 52&nbsp;echo
1040 53&nbsp;
1041 54&nbsp;############################################
1042 55&nbsp;
1043 56&nbsp;# And here is an even more explicit example:
1044 57&nbsp;
1045 58&nbsp;ret_array ()
1046 59&nbsp;{
1047 60&nbsp; for element in {11..20}
1048 61&nbsp; do
1049 62&nbsp; echo "$element " # Echo individual elements
1050 63&nbsp; done #+ of what will be assembled into an array.
1051 64&nbsp;}
1052 65&nbsp;
1053 66&nbsp;arr=( $(ret_array) ) # Assemble into array.
1054 67&nbsp;
1055 68&nbsp;echo "Capturing array \"arr\" from function ret_array () ..."
1056 69&nbsp;echo "Third element of array \"arr\" is ${arr[2]}." # 13 (zero-indexed)
1057 70&nbsp;echo -n "Entire array is: "
1058 71&nbsp;echo ${arr[@]} # 11 12 13 14 15 16 17 18 19 20
1059 72&nbsp;
1060 73&nbsp;echo
1061 74&nbsp;
1062 75&nbsp;exit 0
1063 76&nbsp;
1064 77&nbsp;# Nathan Coulter points out that passing arrays with elements containing
1065 78&nbsp;#+ whitespace breaks this example.</PRE
1066 ></TD
1067 ></TR
1068 ></TABLE
1069 ><HR></DIV
1070 ><P
1071 >For a more elaborate example of passing arrays to
1072 functions, see <A
1073 HREF="contributed-scripts.html#LIFESLOW"
1074 >Example A-10</A
1075 >.</P
1076 ></LI
1077 ><LI
1078 ><P
1079 ><A
1080 NAME="CSTYLE"
1081 ></A
1082 ></P
1083 ><P
1084 >Using the <A
1085 HREF="dblparens.html"
1086 >double-parentheses
1087 construct</A
1088 >, it is possible to use C-style syntax
1089 for setting and incrementing/decrementing variables
1090 and in <A
1091 HREF="loops.html#FORLOOPREF1"
1092 >for</A
1093 > and <A
1094 HREF="loops.html#WHILELOOPREF"
1095 >while</A
1096 > loops. See <A
1097 HREF="loops.html#FORLOOPC"
1098 >Example 11-13</A
1099 > and <A
1100 HREF="loops.html#WHLOOPC"
1101 >Example 11-18</A
1102 >.</P
1103 ></LI
1104 ><LI
1105 ><P
1106 ><A
1107 NAME="SETPUM"
1108 ></A
1109 ></P
1110 ><P
1111 >Setting the <A
1112 HREF="variables2.html#PATHREF"
1113 >path</A
1114 > and <A
1115 HREF="system.html#UMASKREF"
1116 >umask</A
1117 > at the beginning of a script makes
1118 it more <A
1119 HREF="portabilityissues.html"
1120 >portable</A
1121 >
1122 -- more likely to run on a <SPAN
1123 CLASS="QUOTE"
1124 >"foreign"</SPAN
1125 > machine
1126 whose user may have bollixed up the <TT
1127 CLASS="VARNAME"
1128 >$PATH</TT
1129 >
1130 and <B
1131 CLASS="COMMAND"
1132 >umask</B
1133 >.
1134 <TABLE
1135 BORDER="0"
1136 BGCOLOR="#E0E0E0"
1137 WIDTH="90%"
1138 ><TR
1139 ><TD
1140 ><PRE
1141 CLASS="PROGRAMLISTING"
1142 > 1&nbsp;#!/bin/bash
1143 2&nbsp;PATH=/bin:/usr/bin:/usr/local/bin ; export PATH
1144 3&nbsp;umask 022 # Files that the script creates will have 755 permission.
1145 4&nbsp;
1146 5&nbsp;# Thanks to Ian D. Allen, for this tip.</PRE
1147 ></TD
1148 ></TR
1149 ></TABLE
1150 ></P
1151 ></LI
1152 ><LI
1153 ><P
1154 ><A
1155 NAME="FILTEROUTP"
1156 ></A
1157 ></P
1158 ><P
1159 >A useful scripting technique is to
1160 <SPAN
1161 CLASS="emphasis"
1162 ><I
1163 CLASS="EMPHASIS"
1164 >repeatedly</I
1165 ></SPAN
1166 > feed the output of a filter
1167 (by piping) back to the <SPAN
1168 CLASS="emphasis"
1169 ><I
1170 CLASS="EMPHASIS"
1171 >same filter</I
1172 ></SPAN
1173 >, but
1174 with a different set of arguments and/or options. Especially
1175 suitable for this are <A
1176 HREF="textproc.html#TRREF"
1177 >tr</A
1178 > and
1179 <A
1180 HREF="textproc.html#GREPREF"
1181 >grep</A
1182 >.</P
1183 ><P
1184 > <TABLE
1185 BORDER="0"
1186 BGCOLOR="#E0E0E0"
1187 WIDTH="90%"
1188 ><TR
1189 ><TD
1190 ><PRE
1191 CLASS="PROGRAMLISTING"
1192 > 1&nbsp;# From "wstrings.sh" example.
1193 2&nbsp;
1194 3&nbsp;wlist=`strings "$1" | tr A-Z a-z | tr '[:space:]' Z | \
1195 4&nbsp;tr -cs '[:alpha:]' Z | tr -s '\173-\377' Z | tr Z ' '`</PRE
1196 ></TD
1197 ></TR
1198 ></TABLE
1199 >
1200 </P
1201 ><DIV
1202 CLASS="EXAMPLE"
1203 ><HR><A
1204 NAME="AGRAM"
1205 ></A
1206 ><P
1207 ><B
1208 >Example 36-21. Fun with anagrams</B
1209 ></P
1210 ><TABLE
1211 BORDER="0"
1212 BGCOLOR="#E0E0E0"
1213 WIDTH="90%"
1214 ><TR
1215 ><TD
1216 ><PRE
1217 CLASS="PROGRAMLISTING"
1218 > 1&nbsp;#!/bin/bash
1219 2&nbsp;# agram.sh: Playing games with anagrams.
1220 3&nbsp;
1221 4&nbsp;# Find anagrams of...
1222 5&nbsp;LETTERSET=etaoinshrdlu
1223 6&nbsp;FILTER='.......' # How many letters minimum?
1224 7&nbsp;# 1234567
1225 8&nbsp;
1226 9&nbsp;anagram "$LETTERSET" | # Find all anagrams of the letterset...
1227 10&nbsp;grep "$FILTER" | # With at least 7 letters,
1228 11&nbsp;grep '^is' | # starting with 'is'
1229 12&nbsp;grep -v 's$' | # no plurals
1230 13&nbsp;grep -v 'ed$' # no past tense verbs
1231 14&nbsp;# Possible to add many combinations of conditions and filters.
1232 15&nbsp;
1233 16&nbsp;# Uses "anagram" utility
1234 17&nbsp;#+ that is part of the author's "yawl" word list package.
1235 18&nbsp;# http://ibiblio.org/pub/Linux/libs/yawl-0.3.2.tar.gz
1236 19&nbsp;# http://bash.deta.in/yawl-0.3.2.tar.gz
1237 20&nbsp;
1238 21&nbsp;exit 0 # End of code.
1239 22&nbsp;
1240 23&nbsp;
1241 24&nbsp;bash$ sh agram.sh
1242 25&nbsp;islander
1243 26&nbsp;isolate
1244 27&nbsp;isolead
1245 28&nbsp;isotheral
1246 29&nbsp;
1247 30&nbsp;
1248 31&nbsp;
1249 32&nbsp;# Exercises:
1250 33&nbsp;# ---------
1251 34&nbsp;# Modify this script to take the LETTERSET as a command-line parameter.
1252 35&nbsp;# Parameterize the filters in lines 11 - 13 (as with $FILTER),
1253 36&nbsp;#+ so that they can be specified by passing arguments to a function.
1254 37&nbsp;
1255 38&nbsp;# For a slightly different approach to anagramming,
1256 39&nbsp;#+ see the agram2.sh script.</PRE
1257 ></TD
1258 ></TR
1259 ></TABLE
1260 ><HR></DIV
1261 ><P
1262 >See also <A
1263 HREF="procref1.html#CONSTAT"
1264 >Example 29-4</A
1265 >, <A
1266 HREF="textproc.html#CRYPTOQUOTE"
1267 >Example 16-25</A
1268 >, and <A
1269 HREF="contributed-scripts.html#SOUNDEX"
1270 >Example A-9</A
1271 >.</P
1272 ></LI
1273 ><LI
1274 ><P
1275 ><A
1276 NAME="COMMBLAHD"
1277 ></A
1278 ></P
1279 ><P
1280 >Use <SPAN
1281 CLASS="QUOTE"
1282 >"<A
1283 HREF="here-docs.html#ANONHEREDOC0"
1284 >anonymous here
1285 documents</A
1286 >"</SPAN
1287 > to comment out blocks of code,
1288 to save having to individually comment out each line with
1289 a <SPAN
1290 CLASS="TOKEN"
1291 >#</SPAN
1292 >. See <A
1293 HREF="here-docs.html#COMMENTBLOCK"
1294 >Example 19-11</A
1295 >.</P
1296 ></LI
1297 ><LI
1298 ><P
1299 ><A
1300 NAME="WHATISREF3"
1301 ></A
1302 ></P
1303 ><P
1304 >Running a script on a machine that relies on a command
1305 that might not be installed is dangerous. Use <A
1306 HREF="filearchiv.html#WHATISREF"
1307 >whatis</A
1308 > to avoid potential problems
1309 with this.</P
1310 ><P
1311 > <TABLE
1312 BORDER="0"
1313 BGCOLOR="#E0E0E0"
1314 WIDTH="90%"
1315 ><TR
1316 ><TD
1317 ><PRE
1318 CLASS="PROGRAMLISTING"
1319 > 1&nbsp;CMD=command1 # First choice.
1320 2&nbsp;PlanB=command2 # Fallback option.
1321 3&nbsp;
1322 4&nbsp;command_test=$(whatis "$CMD" | grep 'nothing appropriate')
1323 5&nbsp;# If 'command1' not found on system , 'whatis' will return
1324 6&nbsp;#+ "command1: nothing appropriate."
1325 7&nbsp;#
1326 8&nbsp;# A safer alternative is:
1327 9&nbsp;# command_test=$(whereis "$CMD" | grep \/)
1328 10&nbsp;# But then the sense of the following test would have to be reversed,
1329 11&nbsp;#+ since the $command_test variable holds content only if
1330 12&nbsp;#+ the $CMD exists on the system.
1331 13&nbsp;# (Thanks, bojster.)
1332 14&nbsp;
1333 15&nbsp;
1334 16&nbsp;if [[ -z "$command_test" ]] # Check whether command present.
1335 17&nbsp;then
1336 18&nbsp; $CMD option1 option2 # Run command1 with options.
1337 19&nbsp;else # Otherwise,
1338 20&nbsp; $PlanB #+ run command2.
1339 21&nbsp;fi</PRE
1340 ></TD
1341 ></TR
1342 ></TABLE
1343 >
1344 </P
1345 ></LI
1346 ><LI
1347 ><P
1348 ><A
1349 NAME="IFGREPFIX"
1350 ></A
1351 ></P
1352 ><P
1353 >An <A
1354 HREF="tests.html#IFGREPREF"
1355 >if-grep test</A
1356 > may not
1357 return expected results in an error case, when text is output to
1358 <TT
1359 CLASS="FILENAME"
1360 >stderr</TT
1361 >, rather that
1362 <TT
1363 CLASS="FILENAME"
1364 >stdout</TT
1365 >.
1366 <TABLE
1367 BORDER="0"
1368 BGCOLOR="#E0E0E0"
1369 WIDTH="90%"
1370 ><TR
1371 ><TD
1372 ><PRE
1373 CLASS="PROGRAMLISTING"
1374 > 1&nbsp;if ls -l nonexistent_filename | grep -q 'No such file or directory'
1375 2&nbsp; then echo "File \"nonexistent_filename\" does not exist."
1376 3&nbsp;fi</PRE
1377 ></TD
1378 ></TR
1379 ></TABLE
1380 ></P
1381 ><P
1382 ><A
1383 HREF="io-redirection.html#IOREDIRREF"
1384 >Redirecting</A
1385 >
1386 <TT
1387 CLASS="FILENAME"
1388 >stderr</TT
1389 > to <TT
1390 CLASS="FILENAME"
1391 >stdout</TT
1392 > fixes
1393 this.
1394 <TABLE
1395 BORDER="0"
1396 BGCOLOR="#E0E0E0"
1397 WIDTH="90%"
1398 ><TR
1399 ><TD
1400 ><PRE
1401 CLASS="PROGRAMLISTING"
1402 > 1&nbsp;if ls -l nonexistent_filename 2&#62;&#38;1 | grep -q 'No such file or directory'
1403 2&nbsp;# ^^^^
1404 3&nbsp; then echo "File \"nonexistent_filename\" does not exist."
1405 4&nbsp;fi
1406 5&nbsp;
1407 6&nbsp;# Thanks, Chris Martin, for pointing this out.</PRE
1408 ></TD
1409 ></TR
1410 ></TABLE
1411 ></P
1412 ></LI
1413 ><LI
1414 ><P
1415 ><A
1416 NAME="SUBSHTMP"
1417 ></A
1418 >
1419 If you absolutely must access a subshell variable outside the
1420 subshell, here's a way to do it.
1421 <TABLE
1422 BORDER="0"
1423 BGCOLOR="#E0E0E0"
1424 WIDTH="90%"
1425 ><TR
1426 ><TD
1427 ><PRE
1428 CLASS="PROGRAMLISTING"
1429 > 1&nbsp;TMPFILE=tmpfile # Create a temp file to store the variable.
1430 2&nbsp;
1431 3&nbsp;( # Inside the subshell ...
1432 4&nbsp;inner_variable=Inner
1433 5&nbsp;echo $inner_variable
1434 6&nbsp;echo $inner_variable &#62;&#62;$TMPFILE # Append to temp file.
1435 7&nbsp;)
1436 8&nbsp;
1437 9&nbsp; # Outside the subshell ...
1438 10&nbsp;
1439 11&nbsp;echo; echo "-----"; echo
1440 12&nbsp;echo $inner_variable # Null, as expected.
1441 13&nbsp;echo "-----"; echo
1442 14&nbsp;
1443 15&nbsp;# Now ...
1444 16&nbsp;read inner_variable &#60;$TMPFILE # Read back shell variable.
1445 17&nbsp;rm -f "$TMPFILE" # Get rid of temp file.
1446 18&nbsp;echo "$inner_variable" # It's an ugly kludge, but it works.</PRE
1447 ></TD
1448 ></TR
1449 ></TABLE
1450 >
1451 </P
1452 ></LI
1453 ><LI
1454 ><P
1455 ><A
1456 NAME="RUNPARTSREF2"
1457 ></A
1458 ></P
1459 ><P
1460 >The <A
1461 HREF="extmisc.html#RUNPARTSREF"
1462 >run-parts</A
1463 >
1464 command is handy for running a set of command
1465 scripts in a particular sequence, especially in
1466 combination with <A
1467 HREF="system.html#CRONREF"
1468 >cron</A
1469 > or
1470 <A
1471 HREF="timedate.html#ATREF"
1472 >at</A
1473 >.</P
1474 ></LI
1475 ><LI
1476 ><P
1477 ><A
1478 NAME="RCSREF"
1479 ></A
1480 ></P
1481 ><P
1482 >For doing multiple revisions on a complex script, use the
1483 <I
1484 CLASS="FIRSTTERM"
1485 >rcs</I
1486 > Revision Control System package.</P
1487 ><P
1488 > Among other benefits of this is automatically updated ID
1489 header tags. The <B
1490 CLASS="COMMAND"
1491 >co</B
1492 > command in
1493 <I
1494 CLASS="FIRSTTERM"
1495 >rcs</I
1496 > does a parameter replacement of
1497 certain reserved key words, for example, replacing
1498 <TT
1499 CLASS="PARAMETER"
1500 ><I
1501 ># $Id$</I
1502 ></TT
1503 > in a script with something like:
1504 <TABLE
1505 BORDER="0"
1506 BGCOLOR="#E0E0E0"
1507 WIDTH="90%"
1508 ><TR
1509 ><TD
1510 ><PRE
1511 CLASS="PROGRAMLISTING"
1512 > 1&nbsp;# $Id: hello-world.sh,v 1.1 2004/10/16 02:43:05 bozo Exp $</PRE
1513 ></TD
1514 ></TR
1515 ></TABLE
1516 ></P
1517 ></LI
1518 ></UL
1519 ></DIV
1520 ><DIV
1521 CLASS="SECT2"
1522 ><H2
1523 CLASS="SECT2"
1524 ><A
1525 NAME="AEN20679"
1526 ></A
1527 >36.7.2. Widgets</H2
1528 ><P
1529 ><A
1530 NAME="WIDGETREF"
1531 ></A
1532 ></P
1533 ><P
1534 >It would be nice to be able to invoke X-Windows widgets
1535 from a shell script. There happen to exist several packages
1536 that purport to do so, namely <I
1537 CLASS="FIRSTTERM"
1538 >Xscript</I
1539 >,
1540 <I
1541 CLASS="FIRSTTERM"
1542 >Xmenu</I
1543 >, and <I
1544 CLASS="FIRSTTERM"
1545 >widtools</I
1546 >.
1547 The first two of these no longer seem
1548 to be maintained. Fortunately, it is still
1549 possible to obtain <I
1550 CLASS="FIRSTTERM"
1551 >widtools</I
1552 > <A
1553 HREF="http://www.batse.msfc.nasa.gov/~mallozzi/home/software/xforms/src/widtools-2.0.tgz"
1554 TARGET="_top"
1555 >here</A
1556 >.
1557 </P
1558 ><DIV
1559 CLASS="CAUTION"
1560 ><TABLE
1561 CLASS="CAUTION"
1562 WIDTH="100%"
1563 BORDER="0"
1564 ><TR
1565 ><TD
1566 WIDTH="25"
1567 ALIGN="CENTER"
1568 VALIGN="TOP"
1569 ><IMG
1570 SRC="common/caution.png"
1571 HSPACE="5"
1572 ALT="Caution"></TD
1573 ><TD
1574 ALIGN="LEFT"
1575 VALIGN="TOP"
1576 ><P
1577 >The <I
1578 CLASS="FIRSTTERM"
1579 >widtools</I
1580 > (widget tools)
1581 package requires the <I
1582 CLASS="FIRSTTERM"
1583 >XForms</I
1584 > library to
1585 be installed. Additionally, the <A
1586 HREF="filearchiv.html#MAKEFILEREF"
1587 >Makefile</A
1588 > needs some judicious
1589 editing before the package will build on a typical Linux
1590 system. Finally, three of the six widgets offered do not work
1591 (and, in fact, segfault).</P
1592 ></TD
1593 ></TR
1594 ></TABLE
1595 ></DIV
1596 ><P
1597 ><A
1598 NAME="DIALOGREF"
1599 ></A
1600 ></P
1601 ><P
1602 >The <I
1603 CLASS="FIRSTTERM"
1604 >dialog</I
1605 > family of tools offers a method
1606 of calling <SPAN
1607 CLASS="QUOTE"
1608 >"dialog"</SPAN
1609 > widgets from a shell script. The
1610 original <I
1611 CLASS="FIRSTTERM"
1612 >dialog</I
1613 > utility works in a text
1614 console, but its successors, <I
1615 CLASS="FIRSTTERM"
1616 >gdialog</I
1617 >,
1618 <I
1619 CLASS="FIRSTTERM"
1620 >Xdialog</I
1621 >, and <I
1622 CLASS="FIRSTTERM"
1623 >kdialog</I
1624 >
1625 use X-Windows-based widget sets.</P
1626 ><DIV
1627 CLASS="EXAMPLE"
1628 ><HR><A
1629 NAME="DIALOG"
1630 ></A
1631 ><P
1632 ><B
1633 >Example 36-22. Widgets invoked from a shell script</B
1634 ></P
1635 ><TABLE
1636 BORDER="0"
1637 BGCOLOR="#E0E0E0"
1638 WIDTH="100%"
1639 ><TR
1640 ><TD
1641 ><PRE
1642 CLASS="PROGRAMLISTING"
1643 > 1&nbsp;#!/bin/bash
1644 2&nbsp;# dialog.sh: Using 'gdialog' widgets.
1645 3&nbsp;
1646 4&nbsp;# Must have 'gdialog' installed on your system to run this script.
1647 5&nbsp;# Or, you can replace all instance of 'gdialog' below with 'kdialog' ...
1648 6&nbsp;# Version 1.1 (corrected 04/05/05)
1649 7&nbsp;
1650 8&nbsp;# This script was inspired by the following article.
1651 9&nbsp;# "Scripting for X Productivity," by Marco Fioretti,
1652 10&nbsp;# LINUX JOURNAL, Issue 113, September 2003, pp. 86-9.
1653 11&nbsp;# Thank you, all you good people at LJ.
1654 12&nbsp;
1655 13&nbsp;
1656 14&nbsp;# Input error in dialog box.
1657 15&nbsp;E_INPUT=85
1658 16&nbsp;# Dimensions of display, input widgets.
1659 17&nbsp;HEIGHT=50
1660 18&nbsp;WIDTH=60
1661 19&nbsp;
1662 20&nbsp;# Output file name (constructed out of script name).
1663 21&nbsp;OUTFILE=$0.output
1664 22&nbsp;
1665 23&nbsp;# Display this script in a text widget.
1666 24&nbsp;gdialog --title "Displaying: $0" --textbox $0 $HEIGHT $WIDTH
1667 25&nbsp;
1668 26&nbsp;
1669 27&nbsp;
1670 28&nbsp;# Now, we'll try saving input in a file.
1671 29&nbsp;echo -n "VARIABLE=" &#62; $OUTFILE
1672 30&nbsp;gdialog --title "User Input" --inputbox "Enter variable, please:" \
1673 31&nbsp;$HEIGHT $WIDTH 2&#62;&#62; $OUTFILE
1674 32&nbsp;
1675 33&nbsp;
1676 34&nbsp;if [ "$?" -eq 0 ]
1677 35&nbsp;# It's good practice to check exit status.
1678 36&nbsp;then
1679 37&nbsp; echo "Executed \"dialog box\" without errors."
1680 38&nbsp;else
1681 39&nbsp; echo "Error(s) in \"dialog box\" execution."
1682 40&nbsp; # Or, clicked on "Cancel", instead of "OK" button.
1683 41&nbsp; rm $OUTFILE
1684 42&nbsp; exit $E_INPUT
1685 43&nbsp;fi
1686 44&nbsp;
1687 45&nbsp;
1688 46&nbsp;
1689 47&nbsp;# Now, we'll retrieve and display the saved variable.
1690 48&nbsp;. $OUTFILE # 'Source' the saved file.
1691 49&nbsp;echo "The variable input in the \"input box\" was: "$VARIABLE""
1692 50&nbsp;
1693 51&nbsp;
1694 52&nbsp;rm $OUTFILE # Clean up by removing the temp file.
1695 53&nbsp; # Some applications may need to retain this file.
1696 54&nbsp;
1697 55&nbsp;exit $?
1698 56&nbsp;
1699 57&nbsp;# Exercise: Rewrite this script using the 'zenity' widget set.</PRE
1700 ></TD
1701 ></TR
1702 ></TABLE
1703 ><HR></DIV
1704 ><P
1705 ><A
1706 NAME="XMESSAGEREF2"
1707 ></A
1708 >
1709 The <A
1710 HREF="extmisc.html#XMESSAGEREF"
1711 >xmessage</A
1712 > command is
1713 a simple method of popping up a message/query window. For
1714 example:
1715 <TABLE
1716 BORDER="0"
1717 BGCOLOR="#E0E0E0"
1718 WIDTH="100%"
1719 ><TR
1720 ><TD
1721 ><PRE
1722 CLASS="PROGRAMLISTING"
1723 > 1&nbsp;xmessage Fatal error in script! -button exit</PRE
1724 ></TD
1725 ></TR
1726 ></TABLE
1727 >
1728 </P
1729 ><P
1730 ><A
1731 NAME="ZENITYREF2"
1732 ></A
1733 >
1734 The latest entry in the widget sweepstakes is
1735 <A
1736 HREF="extmisc.html#ZENITYREF"
1737 >zenity</A
1738 >.
1739 This utility pops up
1740 <I
1741 CLASS="FIRSTTERM"
1742 >GTK+</I
1743 > dialog widgets-and-windows,
1744 and it works very nicely within a script.
1745 <TABLE
1746 BORDER="0"
1747 BGCOLOR="#E0E0E0"
1748 WIDTH="100%"
1749 ><TR
1750 ><TD
1751 ><PRE
1752 CLASS="PROGRAMLISTING"
1753 > 1&nbsp;get_info ()
1754 2&nbsp;{
1755 3&nbsp; zenity --entry # Pops up query window . . .
1756 4&nbsp; #+ and prints user entry to stdout.
1757 5&nbsp;
1758 6&nbsp; # Also try the --calendar and --scale options.
1759 7&nbsp;}
1760 8&nbsp;
1761 9&nbsp;answer=$( get_info ) # Capture stdout in $answer variable.
1762 10&nbsp;
1763 11&nbsp;echo "User entered: "$answer""</PRE
1764 ></TD
1765 ></TR
1766 ></TABLE
1767 >
1768 </P
1769 ><P
1770 >For other methods of scripting with widgets, try
1771 <I
1772 CLASS="FIRSTTERM"
1773 >Tk</I
1774 > or <I
1775 CLASS="FIRSTTERM"
1776 >wish</I
1777 >
1778 (<I
1779 CLASS="FIRSTTERM"
1780 >Tcl</I
1781 > derivatives),
1782 <I
1783 CLASS="FIRSTTERM"
1784 >PerlTk</I
1785 > (<I
1786 CLASS="FIRSTTERM"
1787 >Perl</I
1788 >
1789 with <I
1790 CLASS="FIRSTTERM"
1791 >Tk</I
1792 > extensions),
1793 <I
1794 CLASS="FIRSTTERM"
1795 >tksh</I
1796 > (<I
1797 CLASS="FIRSTTERM"
1798 >ksh</I
1799 >
1800 with <I
1801 CLASS="FIRSTTERM"
1802 >Tk</I
1803 > extensions),
1804 <I
1805 CLASS="FIRSTTERM"
1806 >XForms4Perl</I
1807 >
1808 (<I
1809 CLASS="FIRSTTERM"
1810 >Perl</I
1811 > with
1812 <I
1813 CLASS="FIRSTTERM"
1814 >XForms</I
1815 > extensions),
1816 <I
1817 CLASS="FIRSTTERM"
1818 >Gtk-Perl</I
1819 > (<I
1820 CLASS="FIRSTTERM"
1821 >Perl</I
1822 >
1823 with <I
1824 CLASS="FIRSTTERM"
1825 >Gtk</I
1826 > extensions), or
1827 <I
1828 CLASS="FIRSTTERM"
1829 >PyQt</I
1830 > (<I
1831 CLASS="FIRSTTERM"
1832 >Python</I
1833 >
1834 with <I
1835 CLASS="FIRSTTERM"
1836 >Qt</I
1837 > extensions).</P
1838 ></DIV
1839 ></DIV
1840 ><DIV
1841 CLASS="NAVFOOTER"
1842 ><HR
1843 ALIGN="LEFT"
1844 WIDTH="100%"><TABLE
1845 SUMMARY="Footer navigation table"
1846 WIDTH="100%"
1847 BORDER="0"
1848 CELLPADDING="0"
1849 CELLSPACING="0"
1850 ><TR
1851 ><TD
1852 WIDTH="33%"
1853 ALIGN="left"
1854 VALIGN="top"
1855 ><A
1856 HREF="optimizations.html"
1857 ACCESSKEY="P"
1858 >Prev</A
1859 ></TD
1860 ><TD
1861 WIDTH="34%"
1862 ALIGN="center"
1863 VALIGN="top"
1864 ><A
1865 HREF="index.html"
1866 ACCESSKEY="H"
1867 >Home</A
1868 ></TD
1869 ><TD
1870 WIDTH="33%"
1871 ALIGN="right"
1872 VALIGN="top"
1873 ><A
1874 HREF="securityissues.html"
1875 ACCESSKEY="N"
1876 >Next</A
1877 ></TD
1878 ></TR
1879 ><TR
1880 ><TD
1881 WIDTH="33%"
1882 ALIGN="left"
1883 VALIGN="top"
1884 >Optimizations</TD
1885 ><TD
1886 WIDTH="34%"
1887 ALIGN="center"
1888 VALIGN="top"
1889 ><A
1890 HREF="miscellany.html"
1891 ACCESSKEY="U"
1892 >Up</A
1893 ></TD
1894 ><TD
1895 WIDTH="33%"
1896 ALIGN="right"
1897 VALIGN="top"
1898 >Security Issues</TD
1899 ></TR
1900 ></TABLE
1901 ></DIV
1902 ></BODY
1903 ></HTML
1904 >