Debian Codegraph @

HTML/functions.html

raw symbols SCIP
1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
2 <HTML
3 ><HEAD
4 ><TITLE
5 >Functions</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="Advanced Topics"
15 HREF="part5.html"><LINK
16 REL="PREVIOUS"
17 TITLE="Process Substitution"
18 HREF="process-sub.html"><LINK
19 REL="NEXT"
20 TITLE="Local Variables"
21 HREF="localvar.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="CHAPTER"
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="process-sub.html"
68 ACCESSKEY="P"
69 >Prev</A
70 ></TD
71 ><TD
72 WIDTH="80%"
73 ALIGN="center"
74 VALIGN="bottom"
75 ></TD
76 ><TD
77 WIDTH="10%"
78 ALIGN="right"
79 VALIGN="bottom"
80 ><A
81 HREF="localvar.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="CHAPTER"
92 ><H1
93 ><A
94 NAME="FUNCTIONS"
95 ></A
96 >Chapter 24. Functions</H1
97 ><P
98 ><A
99 NAME="FUNCTIONREF"
100 ></A
101 ></P
102 ><P
103 >Like <SPAN
104 CLASS="QUOTE"
105 >"real"</SPAN
106 > programming languages,
107 Bash has functions, though in a somewhat limited implementation.
108 A function is a subroutine, a <A
109 HREF="special-chars.html#CODEBLOCKREF"
110 >code
111 block</A
112 > that implements a set of operations, a <SPAN
113 CLASS="QUOTE"
114 >"black
115 box"</SPAN
116 > that performs a specified task. Wherever there is
117 repetitive code, when a task repeats with only slight variations in
118 procedure, then consider using a function.</P
119 ><P
120 ><P
121 ><B
122 CLASS="COMMAND"
123 >function</B
124 > <TT
125 CLASS="REPLACEABLE"
126 ><I
127 >function_name</I
128 ></TT
129 > { <BR> <TT
130 CLASS="REPLACEABLE"
131 ><I
132 >command</I
133 ></TT
134 >... <BR> } <BR></P
135 >
136 or
137 <P
138 > <TT
139 CLASS="REPLACEABLE"
140 ><I
141 >function_name</I
142 ></TT
143 > () { <BR> <TT
144 CLASS="REPLACEABLE"
145 ><I
146 >command</I
147 ></TT
148 >... <BR> } <BR></P
149 >
150 </P
151 ><P
152 >This second form will cheer the hearts of C programmers
153 (and is more <A
154 HREF="portabilityissues.html"
155 >portable</A
156 >).</P
157 ><P
158 >As in C, the function's opening bracket may optionally appear
159 on the second line.</P
160 ><P
161 ><P
162 > <TT
163 CLASS="REPLACEABLE"
164 ><I
165 >function_name</I
166 ></TT
167 > () <BR> { <BR> <TT
168 CLASS="REPLACEABLE"
169 ><I
170 >command</I
171 ></TT
172 >... <BR> } <BR></P
173 >
174 </P
175 ><DIV
176 CLASS="NOTE"
177 ><TABLE
178 CLASS="NOTE"
179 WIDTH="100%"
180 BORDER="0"
181 ><TR
182 ><TD
183 WIDTH="25"
184 ALIGN="CENTER"
185 VALIGN="TOP"
186 ><IMG
187 SRC="common/note.png"
188 HSPACE="5"
189 ALT="Note"></TD
190 ><TD
191 ALIGN="LEFT"
192 VALIGN="TOP"
193 ><P
194 >A function may be <SPAN
195 CLASS="QUOTE"
196 >"compacted"</SPAN
197 > into a single
198 line.</P
199 ><P
200 ><TABLE
201 BORDER="0"
202 BGCOLOR="#E0E0E0"
203 WIDTH="100%"
204 ><TR
205 ><TD
206 ><PRE
207 CLASS="PROGRAMLISTING"
208 > 1&nbsp;fun () { echo "This is a function"; echo; }
209 2&nbsp;# ^ ^</PRE
210 ></TD
211 ></TR
212 ></TABLE
213 ></P
214 ><P
215 >In this case, however, a <I
216 CLASS="FIRSTTERM"
217 >semicolon</I
218 >
219 must follow the final command in the function.</P
220 ><P
221 ><TABLE
222 BORDER="0"
223 BGCOLOR="#E0E0E0"
224 WIDTH="100%"
225 ><TR
226 ><TD
227 ><PRE
228 CLASS="PROGRAMLISTING"
229 > 1&nbsp;fun () { echo "This is a function"; echo } # Error!
230 2&nbsp;# ^
231 3&nbsp;
232 4&nbsp;fun2 () { echo "Even a single-command function? Yes!"; }
233 5&nbsp;# ^</PRE
234 ></TD
235 ></TR
236 ></TABLE
237 ></P
238 ></TD
239 ></TR
240 ></TABLE
241 ></DIV
242 ><P
243 >Functions are called, <I
244 CLASS="FIRSTTERM"
245 >triggered</I
246 >, simply by
247 invoking their names. <SPAN
248 CLASS="emphasis"
249 ><I
250 CLASS="EMPHASIS"
251 >A function call is equivalent to
252 a command.</I
253 ></SPAN
254 ></P
255 ><DIV
256 CLASS="EXAMPLE"
257 ><HR><A
258 NAME="EX59"
259 ></A
260 ><P
261 ><B
262 >Example 24-1. Simple functions</B
263 ></P
264 ><TABLE
265 BORDER="0"
266 BGCOLOR="#E0E0E0"
267 WIDTH="100%"
268 ><TR
269 ><TD
270 ><PRE
271 CLASS="PROGRAMLISTING"
272 > 1&nbsp;#!/bin/bash
273 2&nbsp;# ex59.sh: Exercising functions (simple).
274 3&nbsp;
275 4&nbsp;JUST_A_SECOND=1
276 5&nbsp;
277 6&nbsp;funky ()
278 7&nbsp;{ # This is about as simple as functions get.
279 8&nbsp; echo "This is a funky function."
280 9&nbsp; echo "Now exiting funky function."
281 10&nbsp;} # Function declaration must precede call.
282 11&nbsp;
283 12&nbsp;
284 13&nbsp;fun ()
285 14&nbsp;{ # A somewhat more complex function.
286 15&nbsp; i=0
287 16&nbsp; REPEATS=30
288 17&nbsp;
289 18&nbsp; echo
290 19&nbsp; echo "And now the fun really begins."
291 20&nbsp; echo
292 21&nbsp;
293 22&nbsp; sleep $JUST_A_SECOND # Hey, wait a second!
294 23&nbsp; while [ $i -lt $REPEATS ]
295 24&nbsp; do
296 25&nbsp; echo "----------FUNCTIONS----------&#62;"
297 26&nbsp; echo "&#60;------------ARE-------------"
298 27&nbsp; echo "&#60;------------FUN------------&#62;"
299 28&nbsp; echo
300 29&nbsp; let "i+=1"
301 30&nbsp; done
302 31&nbsp;}
303 32&nbsp;
304 33&nbsp; # Now, call the functions.
305 34&nbsp;
306 35&nbsp;funky
307 36&nbsp;fun
308 37&nbsp;
309 38&nbsp;exit $?</PRE
310 ></TD
311 ></TR
312 ></TABLE
313 ><HR></DIV
314 ><P
315 ><A
316 NAME="FUNCTDEFMUST"
317 ></A
318 ></P
319 ><P
320 >The function definition must precede the first call to
321 it. There is no method of <SPAN
322 CLASS="QUOTE"
323 >"declaring"</SPAN
324 > the function,
325 as, for example, in C.
326 <TABLE
327 BORDER="0"
328 BGCOLOR="#E0E0E0"
329 WIDTH="100%"
330 ><TR
331 ><TD
332 ><PRE
333 CLASS="PROGRAMLISTING"
334 > 1&nbsp;f1
335 2&nbsp;# Will give an error message, since function "f1" not yet defined.
336 3&nbsp;
337 4&nbsp;declare -f f1 # This doesn't help either.
338 5&nbsp;f1 # Still an error message.
339 6&nbsp;
340 7&nbsp;# However...
341 8&nbsp;
342 9&nbsp;
343 10&nbsp;f1 ()
344 11&nbsp;{
345 12&nbsp; echo "Calling function \"f2\" from within function \"f1\"."
346 13&nbsp; f2
347 14&nbsp;}
348 15&nbsp;
349 16&nbsp;f2 ()
350 17&nbsp;{
351 18&nbsp; echo "Function \"f2\"."
352 19&nbsp;}
353 20&nbsp;
354 21&nbsp;f1 # Function "f2" is not actually called until this point,
355 22&nbsp; #+ although it is referenced before its definition.
356 23&nbsp; # This is permissible.
357 24&nbsp;
358 25&nbsp; # Thanks, S.C.</PRE
359 ></TD
360 ></TR
361 ></TABLE
362 >
363 </P
364 ><DIV
365 CLASS="NOTE"
366 ><TABLE
367 CLASS="NOTE"
368 WIDTH="100%"
369 BORDER="0"
370 ><TR
371 ><TD
372 WIDTH="25"
373 ALIGN="CENTER"
374 VALIGN="TOP"
375 ><IMG
376 SRC="common/note.png"
377 HSPACE="5"
378 ALT="Note"></TD
379 ><TD
380 ALIGN="LEFT"
381 VALIGN="TOP"
382 ><P
383 ><A
384 NAME="EMPTYFUNC"
385 ></A
386 >Functions may not be empty!
387 <TABLE
388 BORDER="0"
389 BGCOLOR="#E0E0E0"
390 WIDTH="100%"
391 ><TR
392 ><TD
393 ><PRE
394 CLASS="PROGRAMLISTING"
395 > 1&nbsp;#!/bin/bash
396 2&nbsp;# empty-function.sh
397 3&nbsp;
398 4&nbsp;empty ()
399 5&nbsp;{
400 6&nbsp;}
401 7&nbsp;
402 8&nbsp;exit 0 # Will not exit here!
403 9&nbsp;
404 10&nbsp;# $ sh empty-function.sh
405 11&nbsp;# empty-function.sh: line 6: syntax error near unexpected token `}'
406 12&nbsp;# empty-function.sh: line 6: `}'
407 13&nbsp;
408 14&nbsp;# $ echo $?
409 15&nbsp;# 2
410 16&nbsp;
411 17&nbsp;
412 18&nbsp;# Note that a function containing only comments is empty.
413 19&nbsp;
414 20&nbsp;func ()
415 21&nbsp;{
416 22&nbsp; # Comment 1.
417 23&nbsp; # Comment 2.
418 24&nbsp; # This is still an empty function.
419 25&nbsp; # Thank you, Mark Bova, for pointing this out.
420 26&nbsp;}
421 27&nbsp;# Results in same error message as above.
422 28&nbsp;
423 29&nbsp;
424 30&nbsp;# However ...
425 31&nbsp;
426 32&nbsp;not_quite_empty ()
427 33&nbsp;{
428 34&nbsp; illegal_command
429 35&nbsp;} # A script containing this function will *not* bomb
430 36&nbsp; #+ as long as the function is not called.
431 37&nbsp;
432 38&nbsp;not_empty ()
433 39&nbsp;{
434 40&nbsp; :
435 41&nbsp;} # Contains a : (null command), and this is okay.
436 42&nbsp;
437 43&nbsp;
438 44&nbsp;# Thank you, Dominick Geyer and Thiemo Kellner.</PRE
439 ></TD
440 ></TR
441 ></TABLE
442 ></P
443 ></TD
444 ></TR
445 ></TABLE
446 ></DIV
447 ><P
448 >It is even possible to nest a function within another function,
449 although this is not very useful.
450 <TABLE
451 BORDER="0"
452 BGCOLOR="#E0E0E0"
453 WIDTH="100%"
454 ><TR
455 ><TD
456 ><PRE
457 CLASS="PROGRAMLISTING"
458 > 1&nbsp;f1 ()
459 2&nbsp;{
460 3&nbsp;
461 4&nbsp; f2 () # nested
462 5&nbsp; {
463 6&nbsp; echo "Function \"f2\", inside \"f1\"."
464 7&nbsp; }
465 8&nbsp;
466 9&nbsp;}
467 10&nbsp;
468 11&nbsp;f2 # Gives an error message.
469 12&nbsp; # Even a preceding "declare -f f2" wouldn't help.
470 13&nbsp;
471 14&nbsp;echo
472 15&nbsp;
473 16&nbsp;f1 # Does nothing, since calling "f1" does not automatically call "f2".
474 17&nbsp;f2 # Now, it's all right to call "f2",
475 18&nbsp; #+ since its definition has been made visible by calling "f1".
476 19&nbsp;
477 20&nbsp; # Thanks, S.C.</PRE
478 ></TD
479 ></TR
480 ></TABLE
481 >
482 </P
483 ><P
484 >Function declarations can appear in unlikely places, even where a
485 command would otherwise go.
486 <TABLE
487 BORDER="0"
488 BGCOLOR="#E0E0E0"
489 WIDTH="100%"
490 ><TR
491 ><TD
492 ><PRE
493 CLASS="PROGRAMLISTING"
494 > 1&nbsp;ls -l | foo() { echo "foo"; } # Permissible, but useless.
495 2&nbsp;
496 3&nbsp;
497 4&nbsp;
498 5&nbsp;if [ "$USER" = bozo ]
499 6&nbsp;then
500 7&nbsp; bozo_greet () # Function definition embedded in an if/then construct.
501 8&nbsp; {
502 9&nbsp; echo "Hello, Bozo."
503 10&nbsp; }
504 11&nbsp;fi
505 12&nbsp;
506 13&nbsp;bozo_greet # Works only for Bozo, and other users get an error.
507 14&nbsp;
508 15&nbsp;
509 16&nbsp;
510 17&nbsp;# Something like this might be useful in some contexts.
511 18&nbsp;NO_EXIT=1 # Will enable function definition below.
512 19&nbsp;
513 20&nbsp;[[ $NO_EXIT -eq 1 ]] &#38;&#38; exit() { true; } # Function definition in an "and-list".
514 21&nbsp;# If $NO_EXIT is 1, declares "exit ()".
515 22&nbsp;# This disables the "exit" builtin by aliasing it to "true".
516 23&nbsp;
517 24&nbsp;exit # Invokes "exit ()" function, not "exit" builtin.
518 25&nbsp;
519 26&nbsp;
520 27&nbsp;
521 28&nbsp;# Or, similarly:
522 29&nbsp;filename=file1
523 30&nbsp;
524 31&nbsp;[ -f "$filename" ] &#38;&#38;
525 32&nbsp;foo () { rm -f "$filename"; echo "File "$filename" deleted."; } ||
526 33&nbsp;foo () { echo "File "$filename" not found."; touch bar; }
527 34&nbsp;
528 35&nbsp;foo
529 36&nbsp;
530 37&nbsp;# Thanks, S.C. and Christopher Head</PRE
531 ></TD
532 ></TR
533 ></TABLE
534 >
535 </P
536 ><P
537 ><A
538 NAME="FSTRANGEREF"
539 ></A
540 >Function names can take strange
541 forms.
542 <TABLE
543 BORDER="0"
544 BGCOLOR="#E0E0E0"
545 WIDTH="100%"
546 ><TR
547 ><TD
548 ><PRE
549 CLASS="PROGRAMLISTING"
550 > 1&nbsp; _(){ for i in {1..10}; do echo -n "$FUNCNAME"; done; echo; }
551 2&nbsp;# ^^^ No space between function name and parentheses.
552 3&nbsp;# This doesn't always work. Why not?
553 4&nbsp;
554 5&nbsp;# Now, let's invoke the function.
555 6&nbsp; _ # __________
556 7&nbsp;# ^^^^^^^^^^ 10 underscores (10 x function name)!
557 8&nbsp;# A "naked" underscore is an acceptable function name.
558 9&nbsp;
559 10&nbsp;
560 11&nbsp;# In fact, a colon is likewise an acceptable function name.
561 12&nbsp;
562 13&nbsp;:(){ echo ":"; }; :
563 14&nbsp;
564 15&nbsp;# Of what use is this?
565 16&nbsp;# It's a devious way to obfuscate the code in a script.</PRE
566 ></TD
567 ></TR
568 ></TABLE
569 >
570 See also <A
571 HREF="contributed-scripts.html#GRONSFELD"
572 >Example A-56</A
573 ></P
574 ><DIV
575 CLASS="NOTE"
576 ><TABLE
577 CLASS="NOTE"
578 WIDTH="100%"
579 BORDER="0"
580 ><TR
581 ><TD
582 WIDTH="25"
583 ALIGN="CENTER"
584 VALIGN="TOP"
585 ><IMG
586 SRC="common/note.png"
587 HSPACE="5"
588 ALT="Note"></TD
589 ><TD
590 ALIGN="LEFT"
591 VALIGN="TOP"
592 ><P
593 >What happens when different versions of the same function
594 appear in a script?
595 <TABLE
596 BORDER="0"
597 BGCOLOR="#E0E0E0"
598 WIDTH="100%"
599 ><TR
600 ><TD
601 ><PRE
602 CLASS="PROGRAMLISTING"
603 > 1&nbsp;# As Yan Chen points out,
604 2&nbsp;# when a function is defined multiple times,
605 3&nbsp;# the final version is what is invoked.
606 4&nbsp;# This is not, however, particularly useful.
607 5&nbsp;
608 6&nbsp;func ()
609 7&nbsp;{
610 8&nbsp; echo "First version of func ()."
611 9&nbsp;}
612 10&nbsp;
613 11&nbsp;func ()
614 12&nbsp;{
615 13&nbsp; echo "Second version of func ()."
616 14&nbsp;}
617 15&nbsp;
618 16&nbsp;func # Second version of func ().
619 17&nbsp;
620 18&nbsp;exit $?
621 19&nbsp;
622 20&nbsp;# It is even possible to use functions to override
623 21&nbsp;#+ or preempt system commands.
624 22&nbsp;# Of course, this is *not* advisable.</PRE
625 ></TD
626 ></TR
627 ></TABLE
628 ></P
629 ></TD
630 ></TR
631 ></TABLE
632 ></DIV
633 ><DIV
634 CLASS="SECT1"
635 ><H1
636 CLASS="SECT1"
637 ><A
638 NAME="COMPLEXFUNCT"
639 ></A
640 >24.1. Complex Functions and Function Complexities</H1
641 ><P
642 >Functions may process arguments passed to them and return
643 an <A
644 HREF="exit-status.html#EXITSTATUSREF"
645 >exit status</A
646 > to the script
647 for further processing.</P
648 ><TABLE
649 BORDER="0"
650 BGCOLOR="#E0E0E0"
651 WIDTH="100%"
652 ><TR
653 ><TD
654 ><PRE
655 CLASS="PROGRAMLISTING"
656 > 1&nbsp;function_name $arg1 $arg2</PRE
657 ></TD
658 ></TR
659 ></TABLE
660 ><P
661 ><A
662 NAME="PASSEDARGS"
663 ></A
664 ></P
665 ><P
666 >The function refers to the passed arguments by position (as if they were
667 <A
668 HREF="variables2.html#POSPARAMREF"
669 >positional parameters</A
670 >),
671 that is, <TT
672 CLASS="VARNAME"
673 >$1</TT
674 >, <TT
675 CLASS="VARNAME"
676 >$2</TT
677 >, and
678 so forth.</P
679 ><DIV
680 CLASS="EXAMPLE"
681 ><HR><A
682 NAME="EX60"
683 ></A
684 ><P
685 ><B
686 >Example 24-2. Function Taking Parameters</B
687 ></P
688 ><TABLE
689 BORDER="0"
690 BGCOLOR="#E0E0E0"
691 WIDTH="100%"
692 ><TR
693 ><TD
694 ><PRE
695 CLASS="PROGRAMLISTING"
696 > 1&nbsp;#!/bin/bash
697 2&nbsp;# Functions and parameters
698 3&nbsp;
699 4&nbsp;DEFAULT=default # Default param value.
700 5&nbsp;
701 6&nbsp;func2 () {
702 7&nbsp; if [ -z "$1" ] # Is parameter #1 zero length?
703 8&nbsp; then
704 9&nbsp; echo "-Parameter #1 is zero length.-" # Or no parameter passed.
705 10&nbsp; else
706 11&nbsp; echo "-Parameter #1 is \"$1\".-"
707 12&nbsp; fi
708 13&nbsp;
709 14&nbsp; variable=${1-$DEFAULT} # What does
710 15&nbsp; echo "variable = $variable" #+ parameter substitution show?
711 16&nbsp; # ---------------------------
712 17&nbsp; # It distinguishes between
713 18&nbsp; #+ no param and a null param.
714 19&nbsp;
715 20&nbsp; if [ "$2" ]
716 21&nbsp; then
717 22&nbsp; echo "-Parameter #2 is \"$2\".-"
718 23&nbsp; fi
719 24&nbsp;
720 25&nbsp; return 0
721 26&nbsp;}
722 27&nbsp;
723 28&nbsp;echo
724 29&nbsp;
725 30&nbsp;echo "Nothing passed."
726 31&nbsp;func2 # Called with no params
727 32&nbsp;echo
728 33&nbsp;
729 34&nbsp;
730 35&nbsp;echo "Zero-length parameter passed."
731 36&nbsp;func2 "" # Called with zero-length param
732 37&nbsp;echo
733 38&nbsp;
734 39&nbsp;echo "Null parameter passed."
735 40&nbsp;func2 "$uninitialized_param" # Called with uninitialized param
736 41&nbsp;echo
737 42&nbsp;
738 43&nbsp;echo "One parameter passed."
739 44&nbsp;func2 first # Called with one param
740 45&nbsp;echo
741 46&nbsp;
742 47&nbsp;echo "Two parameters passed."
743 48&nbsp;func2 first second # Called with two params
744 49&nbsp;echo
745 50&nbsp;
746 51&nbsp;echo "\"\" \"second\" passed."
747 52&nbsp;func2 "" second # Called with zero-length first parameter
748 53&nbsp;echo # and ASCII string as a second one.
749 54&nbsp;
750 55&nbsp;exit 0</PRE
751 ></TD
752 ></TR
753 ></TABLE
754 ><HR></DIV
755 ><P
756 ><A
757 NAME="FSHIFTREF"
758 ></A
759 ></P
760 ><DIV
761 CLASS="IMPORTANT"
762 ><TABLE
763 CLASS="IMPORTANT"
764 WIDTH="100%"
765 BORDER="0"
766 ><TR
767 ><TD
768 WIDTH="25"
769 ALIGN="CENTER"
770 VALIGN="TOP"
771 ><IMG
772 SRC="common/important.png"
773 HSPACE="5"
774 ALT="Important"></TD
775 ><TD
776 ALIGN="LEFT"
777 VALIGN="TOP"
778 ><P
779 >The <A
780 HREF="othertypesv.html#SHIFTREF"
781 >shift</A
782 >
783 command works on arguments passed to functions (see <A
784 HREF="assortedtips.html#MULTIPLICATION"
785 >Example 36-18</A
786 >).</P
787 ></TD
788 ></TR
789 ></TABLE
790 ></DIV
791 ><P
792 >But, what about command-line arguments passed to the script?
793 Does a function see them? Well, let's clear up the confusion.</P
794 ><DIV
795 CLASS="EXAMPLE"
796 ><HR><A
797 NAME="FUNCCMDLINEARG"
798 ></A
799 ><P
800 ><B
801 >Example 24-3. Functions and command-line args passed to the script</B
802 ></P
803 ><TABLE
804 BORDER="0"
805 BGCOLOR="#E0E0E0"
806 WIDTH="100%"
807 ><TR
808 ><TD
809 ><PRE
810 CLASS="PROGRAMLISTING"
811 > 1&nbsp;#!/bin/bash
812 2&nbsp;# func-cmdlinearg.sh
813 3&nbsp;# Call this script with a command-line argument,
814 4&nbsp;#+ something like $0 arg1.
815 5&nbsp;
816 6&nbsp;
817 7&nbsp;func ()
818 8&nbsp;
819 9&nbsp;{
820 10&nbsp;echo "$1" # Echoes first arg passed to the function.
821 11&nbsp;} # Does a command-line arg qualify?
822 12&nbsp;
823 13&nbsp;echo "First call to function: no arg passed."
824 14&nbsp;echo "See if command-line arg is seen."
825 15&nbsp;func
826 16&nbsp;# No! Command-line arg not seen.
827 17&nbsp;
828 18&nbsp;echo "============================================================"
829 19&nbsp;echo
830 20&nbsp;echo "Second call to function: command-line arg passed explicitly."
831 21&nbsp;func $1
832 22&nbsp;# Now it's seen!
833 23&nbsp;
834 24&nbsp;exit 0</PRE
835 ></TD
836 ></TR
837 ></TABLE
838 ><HR></DIV
839 ><P
840 >In contrast to certain other programming languages,
841 shell scripts normally pass only value parameters to
842 functions. Variable names (which are actually
843 <I
844 CLASS="FIRSTTERM"
845 >pointers</I
846 >), if
847 passed as parameters to functions, will be treated as string
848 literals. <SPAN
849 CLASS="emphasis"
850 ><I
851 CLASS="EMPHASIS"
852 >Functions interpret their arguments
853 literally.</I
854 ></SPAN
855 ></P
856 ><P
857 ><A
858 NAME="FUNCPOINTERS"
859 ></A
860 ></P
861 ><P
862 ><A
863 HREF="ivr.html#IVRREF"
864 >Indirect variable
865 references</A
866 > (see <A
867 HREF="bash2.html#EX78"
868 >Example 37-2</A
869 >) provide a clumsy
870 sort of mechanism for passing variable pointers to
871 functions.</P
872 ><DIV
873 CLASS="EXAMPLE"
874 ><HR><A
875 NAME="INDFUNC"
876 ></A
877 ><P
878 ><B
879 >Example 24-4. Passing an indirect reference to a function</B
880 ></P
881 ><TABLE
882 BORDER="0"
883 BGCOLOR="#E0E0E0"
884 WIDTH="100%"
885 ><TR
886 ><TD
887 ><PRE
888 CLASS="PROGRAMLISTING"
889 > 1&nbsp;#!/bin/bash
890 2&nbsp;# ind-func.sh: Passing an indirect reference to a function.
891 3&nbsp;
892 4&nbsp;echo_var ()
893 5&nbsp;{
894 6&nbsp;echo "$1"
895 7&nbsp;}
896 8&nbsp;
897 9&nbsp;message=Hello
898 10&nbsp;Hello=Goodbye
899 11&nbsp;
900 12&nbsp;echo_var "$message" # Hello
901 13&nbsp;# Now, let's pass an indirect reference to the function.
902 14&nbsp;echo_var "${!message}" # Goodbye
903 15&nbsp;
904 16&nbsp;echo "-------------"
905 17&nbsp;
906 18&nbsp;# What happens if we change the contents of "hello" variable?
907 19&nbsp;Hello="Hello, again!"
908 20&nbsp;echo_var "$message" # Hello
909 21&nbsp;echo_var "${!message}" # Hello, again!
910 22&nbsp;
911 23&nbsp;exit 0</PRE
912 ></TD
913 ></TR
914 ></TABLE
915 ><HR></DIV
916 ><P
917 >The next logical question is whether parameters can be
918 dereferenced <SPAN
919 CLASS="emphasis"
920 ><I
921 CLASS="EMPHASIS"
922 >after</I
923 ></SPAN
924 > being passed to a
925 function.</P
926 ><DIV
927 CLASS="EXAMPLE"
928 ><HR><A
929 NAME="DEREFERENCECL"
930 ></A
931 ><P
932 ><B
933 >Example 24-5. Dereferencing a parameter passed to a function</B
934 ></P
935 ><TABLE
936 BORDER="0"
937 BGCOLOR="#E0E0E0"
938 WIDTH="100%"
939 ><TR
940 ><TD
941 ><PRE
942 CLASS="PROGRAMLISTING"
943 > 1&nbsp;#!/bin/bash
944 2&nbsp;# dereference.sh
945 3&nbsp;# Dereferencing parameter passed to a function.
946 4&nbsp;# Script by Bruce W. Clare.
947 5&nbsp;
948 6&nbsp;dereference ()
949 7&nbsp;{
950 8&nbsp; y=\$"$1" # Name of variable (not value!).
951 9&nbsp; echo $y # $Junk
952 10&nbsp;
953 11&nbsp; x=`eval "expr \"$y\" "`
954 12&nbsp; echo $1=$x
955 13&nbsp; eval "$1=\"Some Different Text \"" # Assign new value.
956 14&nbsp;}
957 15&nbsp;
958 16&nbsp;Junk="Some Text"
959 17&nbsp;echo $Junk "before" # Some Text before
960 18&nbsp;
961 19&nbsp;dereference Junk
962 20&nbsp;echo $Junk "after" # Some Different Text after
963 21&nbsp;
964 22&nbsp;exit 0</PRE
965 ></TD
966 ></TR
967 ></TABLE
968 ><HR></DIV
969 ><DIV
970 CLASS="EXAMPLE"
971 ><HR><A
972 NAME="REFPARAMS"
973 ></A
974 ><P
975 ><B
976 >Example 24-6. Again, dereferencing a parameter passed to a function</B
977 ></P
978 ><TABLE
979 BORDER="0"
980 BGCOLOR="#E0E0E0"
981 WIDTH="100%"
982 ><TR
983 ><TD
984 ><PRE
985 CLASS="PROGRAMLISTING"
986 > 1&nbsp;#!/bin/bash
987 2&nbsp;# ref-params.sh: Dereferencing a parameter passed to a function.
988 3&nbsp;# (Complex Example)
989 4&nbsp;
990 5&nbsp;ITERATIONS=3 # How many times to get input.
991 6&nbsp;icount=1
992 7&nbsp;
993 8&nbsp;my_read () {
994 9&nbsp; # Called with my_read varname,
995 10&nbsp; #+ outputs the previous value between brackets as the default value,
996 11&nbsp; #+ then asks for a new value.
997 12&nbsp;
998 13&nbsp; local local_var
999 14&nbsp;
1000 15&nbsp; echo -n "Enter a value "
1001 16&nbsp; eval 'echo -n "[$'$1'] "' # Previous value.
1002 17&nbsp;# eval echo -n "[\$$1] " # Easier to understand,
1003 18&nbsp; #+ but loses trailing space in user prompt.
1004 19&nbsp; read local_var
1005 20&nbsp; [ -n "$local_var" ] &#38;&#38; eval $1=\$local_var
1006 21&nbsp;
1007 22&nbsp; # "And-list": if "local_var" then set "$1" to its value.
1008 23&nbsp;}
1009 24&nbsp;
1010 25&nbsp;echo
1011 26&nbsp;
1012 27&nbsp;while [ "$icount" -le "$ITERATIONS" ]
1013 28&nbsp;do
1014 29&nbsp; my_read var
1015 30&nbsp; echo "Entry #$icount = $var"
1016 31&nbsp; let "icount += 1"
1017 32&nbsp; echo
1018 33&nbsp;done
1019 34&nbsp;
1020 35&nbsp;
1021 36&nbsp;# Thanks to Stephane Chazelas for providing this instructive example.
1022 37&nbsp;
1023 38&nbsp;exit 0</PRE
1024 ></TD
1025 ></TR
1026 ></TABLE
1027 ><HR></DIV
1028 ><DIV
1029 CLASS="VARIABLELIST"
1030 ><P
1031 ><B
1032 ><A
1033 NAME="EXITRETURN1"
1034 ></A
1035 >Exit and Return</B
1036 ></P
1037 ><DL
1038 ><DT
1039 ><B
1040 CLASS="COMMAND"
1041 >exit status</B
1042 ></DT
1043 ><DD
1044 ><P
1045 >Functions return a value, called an <I
1046 CLASS="FIRSTTERM"
1047 >exit
1048 status</I
1049 >. This is analogous to the <A
1050 HREF="exit-status.html#EXITSTATUSREF"
1051 >exit status</A
1052 > returned by a
1053 command. The exit status may be explicitly specified
1054 by a <B
1055 CLASS="COMMAND"
1056 >return</B
1057 > statement, otherwise it
1058 is the exit status of the last command in the function
1059 (<SPAN
1060 CLASS="RETURNVALUE"
1061 >0</SPAN
1062 > if successful, and a non-zero
1063 error code if not). This <A
1064 HREF="exit-status.html#EXITSTATUSREF"
1065 >exit
1066 status</A
1067 > may be used in the script by referencing it
1068 as <A
1069 HREF="variables2.html#XSTATVARREF"
1070 >$?</A
1071 >. This mechanism
1072 effectively permits script functions to have a <SPAN
1073 CLASS="QUOTE"
1074 >"return
1075 value"</SPAN
1076 > similar to C functions.</P
1077 ></DD
1078 ><DT
1079 ><B
1080 CLASS="COMMAND"
1081 >return</B
1082 ></DT
1083 ><DD
1084 ><P
1085 ><A
1086 NAME="RETURNREF"
1087 ></A
1088 ></P
1089 ><P
1090 >Terminates a function. A <B
1091 CLASS="COMMAND"
1092 >return</B
1093 > command
1094 <A
1095 NAME="AEN18474"
1096 HREF="#FTN.AEN18474"
1097 >[1]</A
1098 >
1099 optionally takes an <I
1100 CLASS="FIRSTTERM"
1101 >integer</I
1102 >
1103 argument, which is returned to the calling script as
1104 the <SPAN
1105 CLASS="QUOTE"
1106 >"exit status"</SPAN
1107 > of the function, and
1108 this exit status is assigned to the variable <A
1109 HREF="variables2.html#XSTATVARREF"
1110 >$?</A
1111 >.</P
1112 ><DIV
1113 CLASS="EXAMPLE"
1114 ><HR><A
1115 NAME="MAX"
1116 ></A
1117 ><P
1118 ><B
1119 >Example 24-7. Maximum of two numbers</B
1120 ></P
1121 ><TABLE
1122 BORDER="0"
1123 BGCOLOR="#E0E0E0"
1124 WIDTH="90%"
1125 ><TR
1126 ><TD
1127 ><PRE
1128 CLASS="PROGRAMLISTING"
1129 > 1&nbsp;#!/bin/bash
1130 2&nbsp;# max.sh: Maximum of two integers.
1131 3&nbsp;
1132 4&nbsp;E_PARAM_ERR=250 # If less than 2 params passed to function.
1133 5&nbsp;EQUAL=251 # Return value if both params equal.
1134 6&nbsp;# Error values out of range of any
1135 7&nbsp;#+ params that might be fed to the function.
1136 8&nbsp;
1137 9&nbsp;max2 () # Returns larger of two numbers.
1138 10&nbsp;{ # Note: numbers compared must be less than 250.
1139 11&nbsp;if [ -z "$2" ]
1140 12&nbsp;then
1141 13&nbsp; return $E_PARAM_ERR
1142 14&nbsp;fi
1143 15&nbsp;
1144 16&nbsp;if [ "$1" -eq "$2" ]
1145 17&nbsp;then
1146 18&nbsp; return $EQUAL
1147 19&nbsp;else
1148 20&nbsp; if [ "$1" -gt "$2" ]
1149 21&nbsp; then
1150 22&nbsp; return $1
1151 23&nbsp; else
1152 24&nbsp; return $2
1153 25&nbsp; fi
1154 26&nbsp;fi
1155 27&nbsp;}
1156 28&nbsp;
1157 29&nbsp;max2 33 34
1158 30&nbsp;return_val=$?
1159 31&nbsp;
1160 32&nbsp;if [ "$return_val" -eq $E_PARAM_ERR ]
1161 33&nbsp;then
1162 34&nbsp; echo "Need to pass two parameters to the function."
1163 35&nbsp;elif [ "$return_val" -eq $EQUAL ]
1164 36&nbsp; then
1165 37&nbsp; echo "The two numbers are equal."
1166 38&nbsp;else
1167 39&nbsp; echo "The larger of the two numbers is $return_val."
1168 40&nbsp;fi
1169 41&nbsp;
1170 42&nbsp;
1171 43&nbsp;exit 0
1172 44&nbsp;
1173 45&nbsp;# Exercise (easy):
1174 46&nbsp;# ---------------
1175 47&nbsp;# Convert this to an interactive script,
1176 48&nbsp;#+ that is, have the script ask for input (two numbers).</PRE
1177 ></TD
1178 ></TR
1179 ></TABLE
1180 ><HR></DIV
1181 ><DIV
1182 CLASS="TIP"
1183 ><TABLE
1184 CLASS="TIP"
1185 WIDTH="90%"
1186 BORDER="0"
1187 ><TR
1188 ><TD
1189 WIDTH="25"
1190 ALIGN="CENTER"
1191 VALIGN="TOP"
1192 ><IMG
1193 SRC="common/tip.png"
1194 HSPACE="5"
1195 ALT="Tip"></TD
1196 ><TD
1197 ALIGN="LEFT"
1198 VALIGN="TOP"
1199 ><P
1200 >For a function to return a string or array, use a
1201 dedicated variable.
1202 <TABLE
1203 BORDER="0"
1204 BGCOLOR="#E0E0E0"
1205 WIDTH="90%"
1206 ><TR
1207 ><TD
1208 ><PRE
1209 CLASS="PROGRAMLISTING"
1210 > 1&nbsp;count_lines_in_etc_passwd()
1211 2&nbsp;{
1212 3&nbsp; [[ -r /etc/passwd ]] &#38;&#38; REPLY=$(echo $(wc -l &#60; /etc/passwd))
1213 4&nbsp; # If /etc/passwd is readable, set REPLY to line count.
1214 5&nbsp; # Returns both a parameter value and status information.
1215 6&nbsp; # The 'echo' seems unnecessary, but . . .
1216 7&nbsp; #+ it removes excess whitespace from the output.
1217 8&nbsp;}
1218 9&nbsp;
1219 10&nbsp;if count_lines_in_etc_passwd
1220 11&nbsp;then
1221 12&nbsp; echo "There are $REPLY lines in /etc/passwd."
1222 13&nbsp;else
1223 14&nbsp; echo "Cannot count lines in /etc/passwd."
1224 15&nbsp;fi
1225 16&nbsp;
1226 17&nbsp;# Thanks, S.C.</PRE
1227 ></TD
1228 ></TR
1229 ></TABLE
1230 >
1231 </P
1232 ></TD
1233 ></TR
1234 ></TABLE
1235 ></DIV
1236 ><DIV
1237 CLASS="EXAMPLE"
1238 ><HR><A
1239 NAME="EX61"
1240 ></A
1241 ><P
1242 ><B
1243 >Example 24-8. Converting numbers to Roman numerals</B
1244 ></P
1245 ><TABLE
1246 BORDER="0"
1247 BGCOLOR="#E0E0E0"
1248 WIDTH="90%"
1249 ><TR
1250 ><TD
1251 ><PRE
1252 CLASS="PROGRAMLISTING"
1253 > 1&nbsp;#!/bin/bash
1254 2&nbsp;
1255 3&nbsp;# Arabic number to Roman numeral conversion
1256 4&nbsp;# Range: 0 - 200
1257 5&nbsp;# It's crude, but it works.
1258 6&nbsp;
1259 7&nbsp;# Extending the range and otherwise improving the script is left as an exercise.
1260 8&nbsp;
1261 9&nbsp;# Usage: roman number-to-convert
1262 10&nbsp;
1263 11&nbsp;LIMIT=200
1264 12&nbsp;E_ARG_ERR=65
1265 13&nbsp;E_OUT_OF_RANGE=66
1266 14&nbsp;
1267 15&nbsp;if [ -z "$1" ]
1268 16&nbsp;then
1269 17&nbsp; echo "Usage: `basename $0` number-to-convert"
1270 18&nbsp; exit $E_ARG_ERR
1271 19&nbsp;fi
1272 20&nbsp;
1273 21&nbsp;num=$1
1274 22&nbsp;if [ "$num" -gt $LIMIT ]
1275 23&nbsp;then
1276 24&nbsp; echo "Out of range!"
1277 25&nbsp; exit $E_OUT_OF_RANGE
1278 26&nbsp;fi
1279 27&nbsp;
1280 28&nbsp;to_roman () # Must declare function before first call to it.
1281 29&nbsp;{
1282 30&nbsp;number=$1
1283 31&nbsp;factor=$2
1284 32&nbsp;rchar=$3
1285 33&nbsp;let "remainder = number - factor"
1286 34&nbsp;while [ "$remainder" -ge 0 ]
1287 35&nbsp;do
1288 36&nbsp; echo -n $rchar
1289 37&nbsp; let "number -= factor"
1290 38&nbsp; let "remainder = number - factor"
1291 39&nbsp;done
1292 40&nbsp;
1293 41&nbsp;return $number
1294 42&nbsp; # Exercises:
1295 43&nbsp; # ---------
1296 44&nbsp; # 1) Explain how this function works.
1297 45&nbsp; # Hint: division by successive subtraction.
1298 46&nbsp; # 2) Extend to range of the function.
1299 47&nbsp; # Hint: use "echo" and command-substitution capture.
1300 48&nbsp;}
1301 49&nbsp;
1302 50&nbsp;
1303 51&nbsp;to_roman $num 100 C
1304 52&nbsp;num=$?
1305 53&nbsp;to_roman $num 90 LXXXX
1306 54&nbsp;num=$?
1307 55&nbsp;to_roman $num 50 L
1308 56&nbsp;num=$?
1309 57&nbsp;to_roman $num 40 XL
1310 58&nbsp;num=$?
1311 59&nbsp;to_roman $num 10 X
1312 60&nbsp;num=$?
1313 61&nbsp;to_roman $num 9 IX
1314 62&nbsp;num=$?
1315 63&nbsp;to_roman $num 5 V
1316 64&nbsp;num=$?
1317 65&nbsp;to_roman $num 4 IV
1318 66&nbsp;num=$?
1319 67&nbsp;to_roman $num 1 I
1320 68&nbsp;# Successive calls to conversion function!
1321 69&nbsp;# Is this really necessary??? Can it be simplified?
1322 70&nbsp;
1323 71&nbsp;echo
1324 72&nbsp;
1325 73&nbsp;exit</PRE
1326 ></TD
1327 ></TR
1328 ></TABLE
1329 ><HR></DIV
1330 ><P
1331 >See also <A
1332 HREF="testbranch.html#ISALPHA"
1333 >Example 11-29</A
1334 >.</P
1335 ><DIV
1336 CLASS="IMPORTANT"
1337 ><TABLE
1338 CLASS="IMPORTANT"
1339 WIDTH="90%"
1340 BORDER="0"
1341 ><TR
1342 ><TD
1343 WIDTH="25"
1344 ALIGN="CENTER"
1345 VALIGN="TOP"
1346 ><IMG
1347 SRC="common/important.png"
1348 HSPACE="5"
1349 ALT="Important"></TD
1350 ><TD
1351 ALIGN="LEFT"
1352 VALIGN="TOP"
1353 ><P
1354 >The largest positive integer a function can return is
1355 255. The <B
1356 CLASS="COMMAND"
1357 >return</B
1358 > command is closely tied
1359 to the concept of <A
1360 HREF="exit-status.html#EXITSTATUSREF"
1361 >exit
1362 status</A
1363 >, which accounts for this particular
1364 limitation. Fortunately, there are various <A
1365 HREF="assortedtips.html#RVT"
1366 >workarounds</A
1367 > for those situations
1368 requiring a large integer return value from a
1369 function.</P
1370 ><DIV
1371 CLASS="EXAMPLE"
1372 ><HR><A
1373 NAME="RETURNTEST"
1374 ></A
1375 ><P
1376 ><B
1377 >Example 24-9. Testing large return values in a function</B
1378 ></P
1379 ><TABLE
1380 BORDER="0"
1381 BGCOLOR="#E0E0E0"
1382 WIDTH="90%"
1383 ><TR
1384 ><TD
1385 ><PRE
1386 CLASS="PROGRAMLISTING"
1387 > 1&nbsp;#!/bin/bash
1388 2&nbsp;# return-test.sh
1389 3&nbsp;
1390 4&nbsp;# The largest positive value a function can return is 255.
1391 5&nbsp;
1392 6&nbsp;return_test () # Returns whatever passed to it.
1393 7&nbsp;{
1394 8&nbsp; return $1
1395 9&nbsp;}
1396 10&nbsp;
1397 11&nbsp;return_test 27 # o.k.
1398 12&nbsp;echo $? # Returns 27.
1399 13&nbsp;
1400 14&nbsp;return_test 255 # Still o.k.
1401 15&nbsp;echo $? # Returns 255.
1402 16&nbsp;
1403 17&nbsp;return_test 257 # Error!
1404 18&nbsp;echo $? # Returns 1 (return code for miscellaneous error).
1405 19&nbsp;
1406 20&nbsp;# =========================================================
1407 21&nbsp;return_test -151896 # Do large negative numbers work?
1408 22&nbsp;echo $? # Will this return -151896?
1409 23&nbsp; # No! It returns 168.
1410 24&nbsp;# Version of Bash before 2.05b permitted
1411 25&nbsp;#+ large negative integer return values.
1412 26&nbsp;# It happened to be a useful feature.
1413 27&nbsp;# Newer versions of Bash unfortunately plug this loophole.
1414 28&nbsp;# This may break older scripts.
1415 29&nbsp;# Caution!
1416 30&nbsp;# =========================================================
1417 31&nbsp;
1418 32&nbsp;exit 0</PRE
1419 ></TD
1420 ></TR
1421 ></TABLE
1422 ><HR></DIV
1423 ><P
1424 >A workaround for obtaining large integer <SPAN
1425 CLASS="QUOTE"
1426 >"return
1427 values"</SPAN
1428 > is to simply assign the <SPAN
1429 CLASS="QUOTE"
1430 >"return
1431 value"</SPAN
1432 > to a global variable.
1433
1434 <TABLE
1435 BORDER="0"
1436 BGCOLOR="#E0E0E0"
1437 WIDTH="90%"
1438 ><TR
1439 ><TD
1440 ><PRE
1441 CLASS="PROGRAMLISTING"
1442 > 1&nbsp;Return_Val= # Global variable to hold oversize return value of function.
1443 2&nbsp;
1444 3&nbsp;alt_return_test ()
1445 4&nbsp;{
1446 5&nbsp; fvar=$1
1447 6&nbsp; Return_Val=$fvar
1448 7&nbsp; return # Returns 0 (success).
1449 8&nbsp;}
1450 9&nbsp;
1451 10&nbsp;alt_return_test 1
1452 11&nbsp;echo $? # 0
1453 12&nbsp;echo "return value = $Return_Val" # 1
1454 13&nbsp;
1455 14&nbsp;alt_return_test 256
1456 15&nbsp;echo "return value = $Return_Val" # 256
1457 16&nbsp;
1458 17&nbsp;alt_return_test 257
1459 18&nbsp;echo "return value = $Return_Val" # 257
1460 19&nbsp;
1461 20&nbsp;alt_return_test 25701
1462 21&nbsp;echo "return value = $Return_Val" #25701</PRE
1463 ></TD
1464 ></TR
1465 ></TABLE
1466 >
1467 </P
1468 ><P
1469 ><A
1470 NAME="CAPTURERETVAL"
1471 ></A
1472 ></P
1473 ><P
1474 >A more elegant method is to have the function
1475 <B
1476 CLASS="COMMAND"
1477 >echo</B
1478 > its <SPAN
1479 CLASS="QUOTE"
1480 >"return
1481 value to <TT
1482 CLASS="FILENAME"
1483 >stdout</TT
1484 >,"</SPAN
1485 > and
1486 then capture it by <A
1487 HREF="commandsub.html#COMMANDSUBREF"
1488 >command
1489 substitution</A
1490 >. See the <A
1491 HREF="assortedtips.html#RVT"
1492 >discussion
1493 of this</A
1494 > in <A
1495 HREF="assortedtips.html"
1496 >Section 36.7</A
1497 >.</P
1498 ><DIV
1499 CLASS="EXAMPLE"
1500 ><HR><A
1501 NAME="MAX2"
1502 ></A
1503 ><P
1504 ><B
1505 >Example 24-10. Comparing two large integers</B
1506 ></P
1507 ><TABLE
1508 BORDER="0"
1509 BGCOLOR="#E0E0E0"
1510 WIDTH="90%"
1511 ><TR
1512 ><TD
1513 ><PRE
1514 CLASS="PROGRAMLISTING"
1515 > 1&nbsp;#!/bin/bash
1516 2&nbsp;# max2.sh: Maximum of two LARGE integers.
1517 3&nbsp;
1518 4&nbsp;# This is the previous "max.sh" example,
1519 5&nbsp;#+ modified to permit comparing large integers.
1520 6&nbsp;
1521 7&nbsp;EQUAL=0 # Return value if both params equal.
1522 8&nbsp;E_PARAM_ERR=-99999 # Not enough params passed to function.
1523 9&nbsp;# ^^^^^^ Out of range of any params that might be passed.
1524 10&nbsp;
1525 11&nbsp;max2 () # "Returns" larger of two numbers.
1526 12&nbsp;{
1527 13&nbsp;if [ -z "$2" ]
1528 14&nbsp;then
1529 15&nbsp; echo $E_PARAM_ERR
1530 16&nbsp; return
1531 17&nbsp;fi
1532 18&nbsp;
1533 19&nbsp;if [ "$1" -eq "$2" ]
1534 20&nbsp;then
1535 21&nbsp; echo $EQUAL
1536 22&nbsp; return
1537 23&nbsp;else
1538 24&nbsp; if [ "$1" -gt "$2" ]
1539 25&nbsp; then
1540 26&nbsp; retval=$1
1541 27&nbsp; else
1542 28&nbsp; retval=$2
1543 29&nbsp; fi
1544 30&nbsp;fi
1545 31&nbsp;
1546 32&nbsp;echo $retval # Echoes (to stdout), rather than returning value.
1547 33&nbsp; # Why?
1548 34&nbsp;}
1549 35&nbsp;
1550 36&nbsp;
1551 37&nbsp;return_val=$(max2 33001 33997)
1552 38&nbsp;# ^^^^ Function name
1553 39&nbsp;# ^^^^^ ^^^^^ Params passed
1554 40&nbsp;# This is actually a form of command substitution:
1555 41&nbsp;#+ treating a function as if it were a command,
1556 42&nbsp;#+ and assigning the stdout of the function to the variable "return_val."
1557 43&nbsp;
1558 44&nbsp;
1559 45&nbsp;# ========================= OUTPUT ========================
1560 46&nbsp;if [ "$return_val" -eq "$E_PARAM_ERR" ]
1561 47&nbsp; then
1562 48&nbsp; echo "Error in parameters passed to comparison function!"
1563 49&nbsp;elif [ "$return_val" -eq "$EQUAL" ]
1564 50&nbsp; then
1565 51&nbsp; echo "The two numbers are equal."
1566 52&nbsp;else
1567 53&nbsp; echo "The larger of the two numbers is $return_val."
1568 54&nbsp;fi
1569 55&nbsp;# =========================================================
1570 56&nbsp;
1571 57&nbsp;exit 0
1572 58&nbsp;
1573 59&nbsp;# Exercises:
1574 60&nbsp;# ---------
1575 61&nbsp;# 1) Find a more elegant way of testing
1576 62&nbsp;#+ the parameters passed to the function.
1577 63&nbsp;# 2) Simplify the if/then structure at "OUTPUT."
1578 64&nbsp;# 3) Rewrite the script to take input from command-line parameters.</PRE
1579 ></TD
1580 ></TR
1581 ></TABLE
1582 ><HR></DIV
1583 ><P
1584 >Here is another example of capturing a function
1585 <SPAN
1586 CLASS="QUOTE"
1587 >"return value."</SPAN
1588 > Understanding it requires some
1589 knowledge of <A
1590 HREF="awk.html#AWKREF"
1591 >awk</A
1592 >.
1593
1594 <TABLE
1595 BORDER="0"
1596 BGCOLOR="#E0E0E0"
1597 WIDTH="90%"
1598 ><TR
1599 ><TD
1600 ><PRE
1601 CLASS="PROGRAMLISTING"
1602 > 1&nbsp;month_length () # Takes month number as an argument.
1603 2&nbsp;{ # Returns number of days in month.
1604 3&nbsp;monthD="31 28 31 30 31 30 31 31 30 31 30 31" # Declare as local?
1605 4&nbsp;echo "$monthD" | awk '{ print $'"${1}"' }' # Tricky.
1606 5&nbsp;# ^^^^^^^^^
1607 6&nbsp;# Parameter passed to function ($1 -- month number), then to awk.
1608 7&nbsp;# Awk sees this as "print $1 . . . print $12" (depending on month number)
1609 8&nbsp;# Template for passing a parameter to embedded awk script:
1610 9&nbsp;# $'"${script_parameter}"'
1611 10&nbsp;
1612 11&nbsp;# Here's a slightly simpler awk construct:
1613 12&nbsp;# echo $monthD | awk -v month=$1 '{print $(month)}'
1614 13&nbsp;# Uses the -v awk option, which assigns a variable value
1615 14&nbsp;#+ prior to execution of the awk program block.
1616 15&nbsp;# Thank you, Rich.
1617 16&nbsp;
1618 17&nbsp;# Needs error checking for correct parameter range (1-12)
1619 18&nbsp;#+ and for February in leap year.
1620 19&nbsp;}
1621 20&nbsp;
1622 21&nbsp;# ----------------------------------------------
1623 22&nbsp;# Usage example:
1624 23&nbsp;month=4 # April, for example (4th month).
1625 24&nbsp;days_in=$(month_length $month)
1626 25&nbsp;echo $days_in # 30
1627 26&nbsp;# ----------------------------------------------</PRE
1628 ></TD
1629 ></TR
1630 ></TABLE
1631 ></P
1632 ><P
1633 >See also <A
1634 HREF="contributed-scripts.html#DAYSBETWEEN"
1635 >Example A-7</A
1636 >
1637 and <A
1638 HREF="contributed-scripts.html#STDDEV"
1639 >Example A-37</A
1640 >.</P
1641 ><P
1642 ><TT
1643 CLASS="USERINPUT"
1644 ><B
1645 >Exercise:</B
1646 ></TT
1647 > Using what we have
1648 just learned, extend the previous <A
1649 HREF="functions.html#EX61"
1650 >Roman numerals example</A
1651 > to accept
1652 arbitrarily large input.</P
1653 ></TD
1654 ></TR
1655 ></TABLE
1656 ></DIV
1657 ></DD
1658 ></DL
1659 ></DIV
1660 ><DIV
1661 CLASS="VARIABLELIST"
1662 ><P
1663 ><B
1664 ><A
1665 NAME="REDSTDINFUNC1"
1666 ></A
1667 >Redirection</B
1668 ></P
1669 ><DL
1670 ><DT
1671 ><TT
1672 CLASS="REPLACEABLE"
1673 ><I
1674 >Redirecting the stdin
1675 of a function</I
1676 ></TT
1677 ></DT
1678 ><DD
1679 ><P
1680 >A function is essentially a <A
1681 HREF="special-chars.html#CODEBLOCKREF"
1682 >code block</A
1683 >, which means its
1684 <TT
1685 CLASS="FILENAME"
1686 >stdin</TT
1687 > can be redirected (as in <A
1688 HREF="special-chars.html#EX8"
1689 >Example 3-1</A
1690 >).</P
1691 ><DIV
1692 CLASS="EXAMPLE"
1693 ><HR><A
1694 NAME="REALNAME"
1695 ></A
1696 ><P
1697 ><B
1698 >Example 24-11. Real name from username</B
1699 ></P
1700 ><TABLE
1701 BORDER="0"
1702 BGCOLOR="#E0E0E0"
1703 WIDTH="90%"
1704 ><TR
1705 ><TD
1706 ><PRE
1707 CLASS="PROGRAMLISTING"
1708 > 1&nbsp;#!/bin/bash
1709 2&nbsp;# realname.sh
1710 3&nbsp;#
1711 4&nbsp;# From username, gets "real name" from /etc/passwd.
1712 5&nbsp;
1713 6&nbsp;
1714 7&nbsp;ARGCOUNT=1 # Expect one arg.
1715 8&nbsp;E_WRONGARGS=85
1716 9&nbsp;
1717 10&nbsp;file=/etc/passwd
1718 11&nbsp;pattern=$1
1719 12&nbsp;
1720 13&nbsp;if [ $# -ne "$ARGCOUNT" ]
1721 14&nbsp;then
1722 15&nbsp; echo "Usage: `basename $0` USERNAME"
1723 16&nbsp; exit $E_WRONGARGS
1724 17&nbsp;fi
1725 18&nbsp;
1726 19&nbsp;file_excerpt () # Scan file for pattern,
1727 20&nbsp;{ #+ then print relevant portion of line.
1728 21&nbsp; while read line # "while" does not necessarily need [ condition ]
1729 22&nbsp; do
1730 23&nbsp; echo "$line" | grep $1 | awk -F":" '{ print $5 }'
1731 24&nbsp; # Have awk use ":" delimiter.
1732 25&nbsp; done
1733 26&nbsp;} &#60;$file # Redirect into function's stdin.
1734 27&nbsp;
1735 28&nbsp;file_excerpt $pattern
1736 29&nbsp;
1737 30&nbsp;# Yes, this entire script could be reduced to
1738 31&nbsp;# grep PATTERN /etc/passwd | awk -F":" '{ print $5 }'
1739 32&nbsp;# or
1740 33&nbsp;# awk -F: '/PATTERN/ {print $5}'
1741 34&nbsp;# or
1742 35&nbsp;# awk -F: '($1 == "username") { print $5 }' # real name from username
1743 36&nbsp;# However, it might not be as instructive.
1744 37&nbsp;
1745 38&nbsp;exit 0</PRE
1746 ></TD
1747 ></TR
1748 ></TABLE
1749 ><HR></DIV
1750 ><P
1751 >There is an alternate, and perhaps less confusing
1752 method of redirecting a function's
1753 <TT
1754 CLASS="FILENAME"
1755 >stdin</TT
1756 >. This involves redirecting the
1757 <TT
1758 CLASS="FILENAME"
1759 >stdin</TT
1760 > to an embedded bracketed code
1761 block within the function.
1762
1763 <TABLE
1764 BORDER="0"
1765 BGCOLOR="#E0E0E0"
1766 WIDTH="90%"
1767 ><TR
1768 ><TD
1769 ><PRE
1770 CLASS="PROGRAMLISTING"
1771 > 1&nbsp;# Instead of:
1772 2&nbsp;Function ()
1773 3&nbsp;{
1774 4&nbsp; ...
1775 5&nbsp; } &#60; file
1776 6&nbsp;
1777 7&nbsp;# Try this:
1778 8&nbsp;Function ()
1779 9&nbsp;{
1780 10&nbsp; {
1781 11&nbsp; ...
1782 12&nbsp; } &#60; file
1783 13&nbsp;}
1784 14&nbsp;
1785 15&nbsp;# Similarly,
1786 16&nbsp;
1787 17&nbsp;Function () # This works.
1788 18&nbsp;{
1789 19&nbsp; {
1790 20&nbsp; echo $*
1791 21&nbsp; } | tr a b
1792 22&nbsp;}
1793 23&nbsp;
1794 24&nbsp;Function () # This doesn't work.
1795 25&nbsp;{
1796 26&nbsp; echo $*
1797 27&nbsp;} | tr a b # A nested code block is mandatory here.
1798 28&nbsp;
1799 29&nbsp;
1800 30&nbsp;# Thanks, S.C.</PRE
1801 ></TD
1802 ></TR
1803 ></TABLE
1804 >
1805 </P
1806 ><DIV
1807 CLASS="NOTE"
1808 ><TABLE
1809 CLASS="NOTE"
1810 WIDTH="90%"
1811 BORDER="0"
1812 ><TR
1813 ><TD
1814 WIDTH="25"
1815 ALIGN="CENTER"
1816 VALIGN="TOP"
1817 ><IMG
1818 SRC="common/note.png"
1819 HSPACE="5"
1820 ALT="Note"></TD
1821 ><TD
1822 ALIGN="LEFT"
1823 VALIGN="TOP"
1824 ><P
1825 >Emmanuel Rouat's <A
1826 HREF="sample-bashrc.html"
1827 >sample <TT
1828 CLASS="FILENAME"
1829 >bashrc</TT
1830 >
1831 file</A
1832 > contains some instructive examples of
1833 functions.</P
1834 ></TD
1835 ></TR
1836 ></TABLE
1837 ></DIV
1838 ></DD
1839 ></DL
1840 ></DIV
1841 ></DIV
1842 ></DIV
1843 ><H3
1844 CLASS="FOOTNOTES"
1845 >Notes</H3
1846 ><TABLE
1847 BORDER="0"
1848 CLASS="FOOTNOTES"
1849 WIDTH="100%"
1850 ><TR
1851 ><TD
1852 ALIGN="LEFT"
1853 VALIGN="TOP"
1854 WIDTH="5%"
1855 ><A
1856 NAME="FTN.AEN18474"
1857 HREF="functions.html#AEN18474"
1858 >[1]</A
1859 ></TD
1860 ><TD
1861 ALIGN="LEFT"
1862 VALIGN="TOP"
1863 WIDTH="95%"
1864 ><P
1865 >The <B
1866 CLASS="COMMAND"
1867 >return</B
1868 > command is a
1869 Bash <A
1870 HREF="internal.html#BUILTINREF"
1871 >builtin</A
1872 >.</P
1873 ></TD
1874 ></TR
1875 ></TABLE
1876 ><DIV
1877 CLASS="NAVFOOTER"
1878 ><HR
1879 ALIGN="LEFT"
1880 WIDTH="100%"><TABLE
1881 SUMMARY="Footer navigation table"
1882 WIDTH="100%"
1883 BORDER="0"
1884 CELLPADDING="0"
1885 CELLSPACING="0"
1886 ><TR
1887 ><TD
1888 WIDTH="33%"
1889 ALIGN="left"
1890 VALIGN="top"
1891 ><A
1892 HREF="process-sub.html"
1893 ACCESSKEY="P"
1894 >Prev</A
1895 ></TD
1896 ><TD
1897 WIDTH="34%"
1898 ALIGN="center"
1899 VALIGN="top"
1900 ><A
1901 HREF="index.html"
1902 ACCESSKEY="H"
1903 >Home</A
1904 ></TD
1905 ><TD
1906 WIDTH="33%"
1907 ALIGN="right"
1908 VALIGN="top"
1909 ><A
1910 HREF="localvar.html"
1911 ACCESSKEY="N"
1912 >Next</A
1913 ></TD
1914 ></TR
1915 ><TR
1916 ><TD
1917 WIDTH="33%"
1918 ALIGN="left"
1919 VALIGN="top"
1920 >Process Substitution</TD
1921 ><TD
1922 WIDTH="34%"
1923 ALIGN="center"
1924 VALIGN="top"
1925 ><A
1926 HREF="part5.html"
1927 ACCESSKEY="U"
1928 >Up</A
1929 ></TD
1930 ><TD
1931 WIDTH="33%"
1932 ALIGN="right"
1933 VALIGN="top"
1934 >Local Variables</TD
1935 ></TR
1936 ></TABLE
1937 ></DIV
1938 ></BODY
1939 ></HTML
1940 >