Debian Codegraph @

HTML/arrays.html

raw symbols SCIP
1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
2 <HTML
3 ><HEAD
4 ><TITLE
5 >Arrays</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="List Constructs"
18 HREF="list-cons.html"><LINK
19 REL="NEXT"
20 TITLE="Indirect References"
21 HREF="ivr.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="list-cons.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="ivr.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="ARRAYS"
95 ></A
96 >Chapter 27. Arrays</H1
97 ><P
98 ><A
99 NAME="ARRAYREF"
100 ></A
101 ></P
102 ><P
103 >Newer versions of Bash support one-dimensional arrays.
104 <A
105 NAME="BRACKARRAY"
106 ></A
107 >
108 Array elements may be initialized with the
109 <TT
110 CLASS="USERINPUT"
111 ><B
112 >variable[xx]</B
113 ></TT
114 > notation. Alternatively,
115 a script may introduce the entire array by an explicit
116 <TT
117 CLASS="USERINPUT"
118 ><B
119 >declare -a variable</B
120 ></TT
121 > statement. To
122 dereference (retrieve the contents of) an array element, use
123 <I
124 CLASS="FIRSTTERM"
125 >curly bracket</I
126 > notation, that is,
127 <TT
128 CLASS="USERINPUT"
129 ><B
130 >${element[xx]}</B
131 ></TT
132 >.</P
133 ><P
134 ><A
135 NAME="ARRAYNOTATION"
136 ></A
137 ></P
138 ><DIV
139 CLASS="EXAMPLE"
140 ><HR><A
141 NAME="EX66"
142 ></A
143 ><P
144 ><B
145 >Example 27-1. Simple array usage</B
146 ></P
147 ><TABLE
148 BORDER="0"
149 BGCOLOR="#E0E0E0"
150 WIDTH="100%"
151 ><TR
152 ><TD
153 ><PRE
154 CLASS="PROGRAMLISTING"
155 > 1&nbsp;#!/bin/bash
156 2&nbsp;
157 3&nbsp;
158 4&nbsp;area[11]=23
159 5&nbsp;area[13]=37
160 6&nbsp;area[51]=UFOs
161 7&nbsp;
162 8&nbsp;# Array members need not be consecutive or contiguous.
163 9&nbsp;
164 10&nbsp;# Some members of the array can be left uninitialized.
165 11&nbsp;# Gaps in the array are okay.
166 12&nbsp;# In fact, arrays with sparse data ("sparse arrays")
167 13&nbsp;#+ are useful in spreadsheet-processing software.
168 14&nbsp;
169 15&nbsp;
170 16&nbsp;echo -n "area[11] = "
171 17&nbsp;echo ${area[11]} # {curly brackets} needed.
172 18&nbsp;
173 19&nbsp;echo -n "area[13] = "
174 20&nbsp;echo ${area[13]}
175 21&nbsp;
176 22&nbsp;echo "Contents of area[51] are ${area[51]}."
177 23&nbsp;
178 24&nbsp;# Contents of uninitialized array variable print blank (null variable).
179 25&nbsp;echo -n "area[43] = "
180 26&nbsp;echo ${area[43]}
181 27&nbsp;echo "(area[43] unassigned)"
182 28&nbsp;
183 29&nbsp;echo
184 30&nbsp;
185 31&nbsp;# Sum of two array variables assigned to third
186 32&nbsp;area[5]=`expr ${area[11]} + ${area[13]}`
187 33&nbsp;echo "area[5] = area[11] + area[13]"
188 34&nbsp;echo -n "area[5] = "
189 35&nbsp;echo ${area[5]}
190 36&nbsp;
191 37&nbsp;area[6]=`expr ${area[11]} + ${area[51]}`
192 38&nbsp;echo "area[6] = area[11] + area[51]"
193 39&nbsp;echo -n "area[6] = "
194 40&nbsp;echo ${area[6]}
195 41&nbsp;# This fails because adding an integer to a string is not permitted.
196 42&nbsp;
197 43&nbsp;echo; echo; echo
198 44&nbsp;
199 45&nbsp;# -----------------------------------------------------------------
200 46&nbsp;# Another array, "area2".
201 47&nbsp;# Another way of assigning array variables...
202 48&nbsp;# array_name=( XXX YYY ZZZ ... )
203 49&nbsp;
204 50&nbsp;area2=( zero one two three four )
205 51&nbsp;
206 52&nbsp;echo -n "area2[0] = "
207 53&nbsp;echo ${area2[0]}
208 54&nbsp;# Aha, zero-based indexing (first element of array is [0], not [1]).
209 55&nbsp;
210 56&nbsp;echo -n "area2[1] = "
211 57&nbsp;echo ${area2[1]} # [1] is second element of array.
212 58&nbsp;# -----------------------------------------------------------------
213 59&nbsp;
214 60&nbsp;echo; echo; echo
215 61&nbsp;
216 62&nbsp;# -----------------------------------------------
217 63&nbsp;# Yet another array, "area3".
218 64&nbsp;# Yet another way of assigning array variables...
219 65&nbsp;# array_name=([xx]=XXX [yy]=YYY ...)
220 66&nbsp;
221 67&nbsp;area3=([17]=seventeen [24]=twenty-four)
222 68&nbsp;
223 69&nbsp;echo -n "area3[17] = "
224 70&nbsp;echo ${area3[17]}
225 71&nbsp;
226 72&nbsp;echo -n "area3[24] = "
227 73&nbsp;echo ${area3[24]}
228 74&nbsp;# -----------------------------------------------
229 75&nbsp;
230 76&nbsp;exit 0</PRE
231 ></TD
232 ></TR
233 ></TABLE
234 ><HR></DIV
235 ><P
236 ><A
237 NAME="ARRAYINIT0"
238 ></A
239 ></P
240 ><P
241 >As we have seen, a convenient way of initializing an entire array
242 is the <TT
243 CLASS="VARNAME"
244 >array=( element1 element2 ... elementN )</TT
245 >
246 notation.</P
247 ><P
248 ><TABLE
249 BORDER="0"
250 BGCOLOR="#E0E0E0"
251 WIDTH="100%"
252 ><TR
253 ><TD
254 ><PRE
255 CLASS="PROGRAMLISTING"
256 > 1&nbsp;base64_charset=( {A..Z} {a..z} {0..9} + / = )
257 2&nbsp; # Using extended brace expansion
258 3&nbsp; #+ to initialize the elements of the array.
259 4&nbsp; # Excerpted from vladz's "base64.sh" script
260 5&nbsp; #+ in the "Contributed Scripts" appendix.</PRE
261 ></TD
262 ></TR
263 ></TABLE
264 ></P
265 ><P
266 ><A
267 NAME="ARRAYOPSVARS"
268 ></A
269 ></P
270 ><TABLE
271 CLASS="SIDEBAR"
272 BORDER="1"
273 CELLPADDING="5"
274 ><TR
275 ><TD
276 ><DIV
277 CLASS="SIDEBAR"
278 ><A
279 NAME="AEN18812"
280 ></A
281 ><P
282 >Bash permits array operations on variables, even if
283 the variables are not explicitly declared as arrays.</P
284 ><P
285 ><TABLE
286 BORDER="0"
287 BGCOLOR="#E0E0E0"
288 WIDTH="100%"
289 ><TR
290 ><TD
291 ><PRE
292 CLASS="PROGRAMLISTING"
293 > 1&nbsp;string=abcABC123ABCabc
294 2&nbsp;echo ${string[@]} # abcABC123ABCabc
295 3&nbsp;echo ${string[*]} # abcABC123ABCabc
296 4&nbsp;echo ${string[0]} # abcABC123ABCabc
297 5&nbsp;echo ${string[1]} # No output!
298 6&nbsp; # Why?
299 7&nbsp;echo ${#string[@]} # 1
300 8&nbsp; # One element in the array.
301 9&nbsp; # The string itself.
302 10&nbsp;
303 11&nbsp;# Thank you, Michael Zick, for pointing this out.</PRE
304 ></TD
305 ></TR
306 ></TABLE
307 >
308 Once again this demonstrates that <A
309 HREF="untyped.html#BVUNTYPED"
310 >Bash
311 variables are untyped</A
312 >.
313 </P
314 ></DIV
315 ></TD
316 ></TR
317 ></TABLE
318 ><DIV
319 CLASS="EXAMPLE"
320 ><HR><A
321 NAME="POEM"
322 ></A
323 ><P
324 ><B
325 >Example 27-2. Formatting a poem</B
326 ></P
327 ><TABLE
328 BORDER="0"
329 BGCOLOR="#E0E0E0"
330 WIDTH="100%"
331 ><TR
332 ><TD
333 ><PRE
334 CLASS="PROGRAMLISTING"
335 > 1&nbsp;#!/bin/bash
336 2&nbsp;# poem.sh: Pretty-prints one of the ABS Guide author's favorite poems.
337 3&nbsp;
338 4&nbsp;# Lines of the poem (single stanza).
339 5&nbsp;Line[1]="I do not know which to prefer,"
340 6&nbsp;Line[2]="The beauty of inflections"
341 7&nbsp;Line[3]="Or the beauty of innuendoes,"
342 8&nbsp;Line[4]="The blackbird whistling"
343 9&nbsp;Line[5]="Or just after."
344 10&nbsp;# Note that quoting permits embedding whitespace.
345 11&nbsp;
346 12&nbsp;# Attribution.
347 13&nbsp;Attrib[1]=" Wallace Stevens"
348 14&nbsp;Attrib[2]="\"Thirteen Ways of Looking at a Blackbird\""
349 15&nbsp;# This poem is in the Public Domain (copyright expired).
350 16&nbsp;
351 17&nbsp;echo
352 18&nbsp;
353 19&nbsp;tput bold # Bold print.
354 20&nbsp;
355 21&nbsp;for index in 1 2 3 4 5 # Five lines.
356 22&nbsp;do
357 23&nbsp; printf " %s\n" "${Line[index]}"
358 24&nbsp;done
359 25&nbsp;
360 26&nbsp;for index in 1 2 # Two attribution lines.
361 27&nbsp;do
362 28&nbsp; printf " %s\n" "${Attrib[index]}"
363 29&nbsp;done
364 30&nbsp;
365 31&nbsp;tput sgr0 # Reset terminal.
366 32&nbsp; # See 'tput' docs.
367 33&nbsp;
368 34&nbsp;echo
369 35&nbsp;
370 36&nbsp;exit 0
371 37&nbsp;
372 38&nbsp;# Exercise:
373 39&nbsp;# --------
374 40&nbsp;# Modify this script to pretty-print a poem from a text data file.</PRE
375 ></TD
376 ></TR
377 ></TABLE
378 ><HR></DIV
379 ><P
380 ><A
381 NAME="ARRAYSYNTAX"
382 ></A
383 ></P
384 ><P
385 >Array variables have a syntax all their own, and even
386 standard Bash commands and operators have special options adapted
387 for array use.</P
388 ><DIV
389 CLASS="EXAMPLE"
390 ><HR><A
391 NAME="ARRAYOPS"
392 ></A
393 ><P
394 ><B
395 >Example 27-3. Various array operations</B
396 ></P
397 ><TABLE
398 BORDER="0"
399 BGCOLOR="#E0E0E0"
400 WIDTH="100%"
401 ><TR
402 ><TD
403 ><PRE
404 CLASS="PROGRAMLISTING"
405 > 1&nbsp;#!/bin/bash
406 2&nbsp;# array-ops.sh: More fun with arrays.
407 3&nbsp;
408 4&nbsp;
409 5&nbsp;array=( zero one two three four five )
410 6&nbsp;# Element 0 1 2 3 4 5
411 7&nbsp;
412 8&nbsp;echo ${array[0]} # zero
413 9&nbsp;echo ${array:0} # zero
414 10&nbsp; # Parameter expansion of first element,
415 11&nbsp; #+ starting at position # 0 (1st character).
416 12&nbsp;echo ${array:1} # ero
417 13&nbsp; # Parameter expansion of first element,
418 14&nbsp; #+ starting at position # 1 (2nd character).
419 15&nbsp;
420 16&nbsp;echo "--------------"
421 17&nbsp;
422 18&nbsp;echo ${#array[0]} # 4
423 19&nbsp; # Length of first element of array.
424 20&nbsp;echo ${#array} # 4
425 21&nbsp; # Length of first element of array.
426 22&nbsp; # (Alternate notation)
427 23&nbsp;
428 24&nbsp;echo ${#array[1]} # 3
429 25&nbsp; # Length of second element of array.
430 26&nbsp; # Arrays in Bash have zero-based indexing.
431 27&nbsp;
432 28&nbsp;echo ${#array[*]} # 6
433 29&nbsp; # Number of elements in array.
434 30&nbsp;echo ${#array[@]} # 6
435 31&nbsp; # Number of elements in array.
436 32&nbsp;
437 33&nbsp;echo "--------------"
438 34&nbsp;
439 35&nbsp;array2=( [0]="first element" [1]="second element" [3]="fourth element" )
440 36&nbsp;# ^ ^ ^ ^ ^ ^ ^ ^ ^
441 37&nbsp;# Quoting permits embedding whitespace within individual array elements.
442 38&nbsp;
443 39&nbsp;echo ${array2[0]} # first element
444 40&nbsp;echo ${array2[1]} # second element
445 41&nbsp;echo ${array2[2]} #
446 42&nbsp; # Skipped in initialization, and therefore null.
447 43&nbsp;echo ${array2[3]} # fourth element
448 44&nbsp;echo ${#array2[0]} # 13 (length of first element)
449 45&nbsp;echo ${#array2[*]} # 3 (number of elements in array)
450 46&nbsp;
451 47&nbsp;exit</PRE
452 ></TD
453 ></TR
454 ></TABLE
455 ><HR></DIV
456 ><P
457 ><A
458 NAME="ARRAYSTRINGOPS"
459 ></A
460 ></P
461 ><P
462 >Many of the standard <A
463 HREF="manipulatingvars.html#STRINGMANIP"
464 >string
465 operations</A
466 > work on arrays.</P
467 ><DIV
468 CLASS="EXAMPLE"
469 ><HR><A
470 NAME="ARRAYSTROPS"
471 ></A
472 ><P
473 ><B
474 >Example 27-4. String operations on arrays</B
475 ></P
476 ><TABLE
477 BORDER="0"
478 BGCOLOR="#E0E0E0"
479 WIDTH="100%"
480 ><TR
481 ><TD
482 ><PRE
483 CLASS="PROGRAMLISTING"
484 > 1&nbsp;#!/bin/bash
485 2&nbsp;# array-strops.sh: String operations on arrays.
486 3&nbsp;
487 4&nbsp;# Script by Michael Zick.
488 5&nbsp;# Used in ABS Guide with permission.
489 6&nbsp;# Fixups: 05 May 08, 04 Aug 08.
490 7&nbsp;
491 8&nbsp;# In general, any string operation using the ${name ... } notation
492 9&nbsp;#+ can be applied to all string elements in an array,
493 10&nbsp;#+ with the ${name[@] ... } or ${name[*] ...} notation.
494 11&nbsp;
495 12&nbsp;
496 13&nbsp;arrayZ=( one two three four five five )
497 14&nbsp;
498 15&nbsp;echo
499 16&nbsp;
500 17&nbsp;# Trailing Substring Extraction
501 18&nbsp;echo ${arrayZ[@]:0} # one two three four five five
502 19&nbsp;# ^ All elements.
503 20&nbsp;
504 21&nbsp;echo ${arrayZ[@]:1} # two three four five five
505 22&nbsp;# ^ All elements following element[0].
506 23&nbsp;
507 24&nbsp;echo ${arrayZ[@]:1:2} # two three
508 25&nbsp;# ^ Only the two elements after element[0].
509 26&nbsp;
510 27&nbsp;echo "---------"
511 28&nbsp;
512 29&nbsp;
513 30&nbsp;# Substring Removal
514 31&nbsp;
515 32&nbsp;# Removes shortest match from front of string(s).
516 33&nbsp;
517 34&nbsp;echo ${arrayZ[@]#f*r} # one two three five five
518 35&nbsp;# ^ # Applied to all elements of the array.
519 36&nbsp; # Matches "four" and removes it.
520 37&nbsp;
521 38&nbsp;# Longest match from front of string(s)
522 39&nbsp;echo ${arrayZ[@]##t*e} # one two four five five
523 40&nbsp;# ^^ # Applied to all elements of the array.
524 41&nbsp; # Matches "three" and removes it.
525 42&nbsp;
526 43&nbsp;# Shortest match from back of string(s)
527 44&nbsp;echo ${arrayZ[@]%h*e} # one two t four five five
528 45&nbsp;# ^ # Applied to all elements of the array.
529 46&nbsp; # Matches "hree" and removes it.
530 47&nbsp;
531 48&nbsp;# Longest match from back of string(s)
532 49&nbsp;echo ${arrayZ[@]%%t*e} # one two four five five
533 50&nbsp;# ^^ # Applied to all elements of the array.
534 51&nbsp; # Matches "three" and removes it.
535 52&nbsp;
536 53&nbsp;echo "----------------------"
537 54&nbsp;
538 55&nbsp;
539 56&nbsp;# Substring Replacement
540 57&nbsp;
541 58&nbsp;# Replace first occurrence of substring with replacement.
542 59&nbsp;echo ${arrayZ[@]/fiv/XYZ} # one two three four XYZe XYZe
543 60&nbsp;# ^ # Applied to all elements of the array.
544 61&nbsp;
545 62&nbsp;# Replace all occurrences of substring.
546 63&nbsp;echo ${arrayZ[@]//iv/YY} # one two three four fYYe fYYe
547 64&nbsp; # Applied to all elements of the array.
548 65&nbsp;
549 66&nbsp;# Delete all occurrences of substring.
550 67&nbsp;# Not specifing a replacement defaults to 'delete' ...
551 68&nbsp;echo ${arrayZ[@]//fi/} # one two three four ve ve
552 69&nbsp;# ^^ # Applied to all elements of the array.
553 70&nbsp;
554 71&nbsp;# Replace front-end occurrences of substring.
555 72&nbsp;echo ${arrayZ[@]/#fi/XY} # one two three four XYve XYve
556 73&nbsp;# ^ # Applied to all elements of the array.
557 74&nbsp;
558 75&nbsp;# Replace back-end occurrences of substring.
559 76&nbsp;echo ${arrayZ[@]/%ve/ZZ} # one two three four fiZZ fiZZ
560 77&nbsp;# ^ # Applied to all elements of the array.
561 78&nbsp;
562 79&nbsp;echo ${arrayZ[@]/%o/XX} # one twXX three four five five
563 80&nbsp;# ^ # Why?
564 81&nbsp;
565 82&nbsp;echo "-----------------------------"
566 83&nbsp;
567 84&nbsp;
568 85&nbsp;replacement() {
569 86&nbsp; echo -n "!!!"
570 87&nbsp;}
571 88&nbsp;
572 89&nbsp;echo ${arrayZ[@]/%e/$(replacement)}
573 90&nbsp;# ^ ^^^^^^^^^^^^^^
574 91&nbsp;# on!!! two thre!!! four fiv!!! fiv!!!
575 92&nbsp;# The stdout of replacement() is the replacement string.
576 93&nbsp;# Q.E.D: The replacement action is, in effect, an 'assignment.'
577 94&nbsp;
578 95&nbsp;echo "------------------------------------"
579 96&nbsp;
580 97&nbsp;# Accessing the "for-each":
581 98&nbsp;echo ${arrayZ[@]//*/$(replacement optional_arguments)}
582 99&nbsp;# ^^ ^^^^^^^^^^^^^
583 100&nbsp;# !!! !!! !!! !!! !!! !!!
584 101&nbsp;
585 102&nbsp;# Now, if Bash would only pass the matched string
586 103&nbsp;#+ to the function being called . . .
587 104&nbsp;
588 105&nbsp;echo
589 106&nbsp;
590 107&nbsp;exit 0
591 108&nbsp;
592 109&nbsp;# Before reaching for a Big Hammer -- Perl, Python, or all the rest --
593 110&nbsp;# recall:
594 111&nbsp;# $( ... ) is command substitution.
595 112&nbsp;# A function runs as a sub-process.
596 113&nbsp;# A function writes its output (if echo-ed) to stdout.
597 114&nbsp;# Assignment, in conjunction with "echo" and command substitution,
598 115&nbsp;#+ can read a function's stdout.
599 116&nbsp;# The name[@] notation specifies (the equivalent of) a "for-each"
600 117&nbsp;#+ operation.
601 118&nbsp;# Bash is more powerful than you think!</PRE
602 ></TD
603 ></TR
604 ></TABLE
605 ><HR></DIV
606 ><P
607 ><A
608 HREF="commandsub.html#COMMANDSUBREF"
609 >Command substitution</A
610 > can
611 construct the individual elements of an array.</P
612 ><DIV
613 CLASS="EXAMPLE"
614 ><HR><A
615 NAME="SCRIPTARRAY"
616 ></A
617 ><P
618 ><B
619 >Example 27-5. Loading the contents of a script into an array</B
620 ></P
621 ><TABLE
622 BORDER="0"
623 BGCOLOR="#E0E0E0"
624 WIDTH="100%"
625 ><TR
626 ><TD
627 ><PRE
628 CLASS="PROGRAMLISTING"
629 > 1&nbsp;#!/bin/bash
630 2&nbsp;# script-array.sh: Loads this script into an array.
631 3&nbsp;# Inspired by an e-mail from Chris Martin (thanks!).
632 4&nbsp;
633 5&nbsp;script_contents=( $(cat "$0") ) # Stores contents of this script ($0)
634 6&nbsp; #+ in an array.
635 7&nbsp;
636 8&nbsp;for element in $(seq 0 $((${#script_contents[@]} - 1)))
637 9&nbsp; do # ${#script_contents[@]}
638 10&nbsp; #+ gives number of elements in the array.
639 11&nbsp; #
640 12&nbsp; # Question:
641 13&nbsp; # Why is seq 0 necessary?
642 14&nbsp; # Try changing it to seq 1.
643 15&nbsp; echo -n "${script_contents[$element]}"
644 16&nbsp; # List each field of this script on a single line.
645 17&nbsp;# echo -n "${script_contents[element]}" also works because of ${ ... }.
646 18&nbsp; echo -n " -- " # Use " -- " as a field separator.
647 19&nbsp;done
648 20&nbsp;
649 21&nbsp;echo
650 22&nbsp;
651 23&nbsp;exit 0
652 24&nbsp;
653 25&nbsp;# Exercise:
654 26&nbsp;# --------
655 27&nbsp;# Modify this script so it lists itself
656 28&nbsp;#+ in its original format,
657 29&nbsp;#+ complete with whitespace, line breaks, etc.</PRE
658 ></TD
659 ></TR
660 ></TABLE
661 ><HR></DIV
662 ><P
663 >In an array context, some Bash <A
664 HREF="internal.html#BUILTINREF"
665 >builtins</A
666 > have a slightly
667 altered meaning. <A
668 NAME="ARRAYUNSET"
669 ></A
670 >For example, <A
671 HREF="internal.html#UNSETREF"
672 >unset</A
673 > deletes array elements, or even
674 an entire array.</P
675 ><P
676 ><A
677 NAME="ARRAYSPECIALPROPS"
678 ></A
679 ></P
680 ><DIV
681 CLASS="EXAMPLE"
682 ><HR><A
683 NAME="EX67"
684 ></A
685 ><P
686 ><B
687 >Example 27-6. Some special properties of arrays</B
688 ></P
689 ><TABLE
690 BORDER="0"
691 BGCOLOR="#E0E0E0"
692 WIDTH="100%"
693 ><TR
694 ><TD
695 ><PRE
696 CLASS="PROGRAMLISTING"
697 > 1&nbsp;#!/bin/bash
698 2&nbsp;
699 3&nbsp;declare -a colors
700 4&nbsp;# All subsequent commands in this script will treat
701 5&nbsp;#+ the variable "colors" as an array.
702 6&nbsp;
703 7&nbsp;echo "Enter your favorite colors (separated from each other by a space)."
704 8&nbsp;
705 9&nbsp;read -a colors # Enter at least 3 colors to demonstrate features below.
706 10&nbsp;# Special option to 'read' command,
707 11&nbsp;#+ allowing assignment of elements in an array.
708 12&nbsp;
709 13&nbsp;echo
710 14&nbsp;
711 15&nbsp;element_count=${#colors[@]}
712 16&nbsp;# Special syntax to extract number of elements in array.
713 17&nbsp;# element_count=${#colors[*]} works also.
714 18&nbsp;#
715 19&nbsp;# The "@" variable allows word splitting within quotes
716 20&nbsp;#+ (extracts variables separated by whitespace).
717 21&nbsp;#
718 22&nbsp;# This corresponds to the behavior of "$@" and "$*"
719 23&nbsp;#+ in positional parameters.
720 24&nbsp;
721 25&nbsp;index=0
722 26&nbsp;
723 27&nbsp;while [ "$index" -lt "$element_count" ]
724 28&nbsp;do # List all the elements in the array.
725 29&nbsp; echo ${colors[$index]}
726 30&nbsp; # ${colors[index]} also works because it's within ${ ... } brackets.
727 31&nbsp; let "index = $index + 1"
728 32&nbsp; # Or:
729 33&nbsp; # ((index++))
730 34&nbsp;done
731 35&nbsp;# Each array element listed on a separate line.
732 36&nbsp;# If this is not desired, use echo -n "${colors[$index]} "
733 37&nbsp;#
734 38&nbsp;# Doing it with a "for" loop instead:
735 39&nbsp;# for i in "${colors[@]}"
736 40&nbsp;# do
737 41&nbsp;# echo "$i"
738 42&nbsp;# done
739 43&nbsp;# (Thanks, S.C.)
740 44&nbsp;
741 45&nbsp;echo
742 46&nbsp;
743 47&nbsp;# Again, list all the elements in the array, but using a more elegant method.
744 48&nbsp; echo ${colors[@]} # echo ${colors[*]} also works.
745 49&nbsp;
746 50&nbsp;echo
747 51&nbsp;
748 52&nbsp;# The "unset" command deletes elements of an array, or entire array.
749 53&nbsp;unset colors[1] # Remove 2nd element of array.
750 54&nbsp; # Same effect as colors[1]=
751 55&nbsp;echo ${colors[@]} # List array again, missing 2nd element.
752 56&nbsp;
753 57&nbsp;unset colors # Delete entire array.
754 58&nbsp; # unset colors[*] and
755 59&nbsp; #+ unset colors[@] also work.
756 60&nbsp;echo; echo -n "Colors gone."
757 61&nbsp;echo ${colors[@]} # List array again, now empty.
758 62&nbsp;
759 63&nbsp;exit 0</PRE
760 ></TD
761 ></TR
762 ></TABLE
763 ><HR></DIV
764 ><P
765 ><A
766 NAME="ARRAYNUMELEMENTS"
767 ></A
768 ></P
769 ><P
770 >As seen in the previous example, either
771 <B
772 CLASS="COMMAND"
773 >${array_name[@]}</B
774 > or
775 <B
776 CLASS="COMMAND"
777 >${array_name[*]}</B
778 > refers to
779 <SPAN
780 CLASS="emphasis"
781 ><I
782 CLASS="EMPHASIS"
783 >all</I
784 ></SPAN
785 > the elements of the array.
786 Similarly, to get a count of the number of elements in an
787 array, use either <B
788 CLASS="COMMAND"
789 >${#array_name[@]}</B
790 >
791 or <B
792 CLASS="COMMAND"
793 >${#array_name[*]}</B
794 >.
795 <B
796 CLASS="COMMAND"
797 >${#array_name}</B
798 > is the length (number of
799 characters) of <B
800 CLASS="COMMAND"
801 >${array_name[0]}</B
802 >, the first
803 element of the array.</P
804 ><P
805 ><A
806 NAME="EMPTYARRAY0"
807 ></A
808 ></P
809 ><DIV
810 CLASS="EXAMPLE"
811 ><HR><A
812 NAME="EMPTYARRAY"
813 ></A
814 ><P
815 ><B
816 >Example 27-7. Of empty arrays and empty elements</B
817 ></P
818 ><TABLE
819 BORDER="0"
820 BGCOLOR="#E0E0E0"
821 WIDTH="100%"
822 ><TR
823 ><TD
824 ><PRE
825 CLASS="PROGRAMLISTING"
826 > 1&nbsp;#!/bin/bash
827 2&nbsp;# empty-array.sh
828 3&nbsp;
829 4&nbsp;# Thanks to Stephane Chazelas for the original example,
830 5&nbsp;#+ and to Michael Zick and Omair Eshkenazi, for extending it.
831 6&nbsp;# And to Nathan Coulter for clarifications and corrections.
832 7&nbsp;
833 8&nbsp;
834 9&nbsp;# An empty array is not the same as an array with empty elements.
835 10&nbsp;
836 11&nbsp; array0=( first second third )
837 12&nbsp; array1=( '' ) # "array1" consists of one empty element.
838 13&nbsp; array2=( ) # No elements . . . "array2" is empty.
839 14&nbsp; array3=( ) # What about this array?
840 15&nbsp;
841 16&nbsp;
842 17&nbsp;echo
843 18&nbsp;ListArray()
844 19&nbsp;{
845 20&nbsp;echo
846 21&nbsp;echo "Elements in array0: ${array0[@]}"
847 22&nbsp;echo "Elements in array1: ${array1[@]}"
848 23&nbsp;echo "Elements in array2: ${array2[@]}"
849 24&nbsp;echo "Elements in array3: ${array3[@]}"
850 25&nbsp;echo
851 26&nbsp;echo "Length of first element in array0 = ${#array0}"
852 27&nbsp;echo "Length of first element in array1 = ${#array1}"
853 28&nbsp;echo "Length of first element in array2 = ${#array2}"
854 29&nbsp;echo "Length of first element in array3 = ${#array3}"
855 30&nbsp;echo
856 31&nbsp;echo "Number of elements in array0 = ${#array0[*]}" # 3
857 32&nbsp;echo "Number of elements in array1 = ${#array1[*]}" # 1 (Surprise!)
858 33&nbsp;echo "Number of elements in array2 = ${#array2[*]}" # 0
859 34&nbsp;echo "Number of elements in array3 = ${#array3[*]}" # 0
860 35&nbsp;}
861 36&nbsp;
862 37&nbsp;# ===================================================================
863 38&nbsp;
864 39&nbsp;ListArray
865 40&nbsp;
866 41&nbsp;# Try extending those arrays.
867 42&nbsp;
868 43&nbsp;# Adding an element to an array.
869 44&nbsp;array0=( "${array0[@]}" "new1" )
870 45&nbsp;array1=( "${array1[@]}" "new1" )
871 46&nbsp;array2=( "${array2[@]}" "new1" )
872 47&nbsp;array3=( "${array3[@]}" "new1" )
873 48&nbsp;
874 49&nbsp;ListArray
875 50&nbsp;
876 51&nbsp;# or
877 52&nbsp;array0[${#array0[*]}]="new2"
878 53&nbsp;array1[${#array1[*]}]="new2"
879 54&nbsp;array2[${#array2[*]}]="new2"
880 55&nbsp;array3[${#array3[*]}]="new2"
881 56&nbsp;
882 57&nbsp;ListArray
883 58&nbsp;
884 59&nbsp;# When extended as above, arrays are 'stacks' ...
885 60&nbsp;# Above is the 'push' ...
886 61&nbsp;# The stack 'height' is:
887 62&nbsp;height=${#array2[@]}
888 63&nbsp;echo
889 64&nbsp;echo "Stack height for array2 = $height"
890 65&nbsp;
891 66&nbsp;# The 'pop' is:
892 67&nbsp;unset array2[${#array2[@]}-1] # Arrays are zero-based,
893 68&nbsp;height=${#array2[@]} #+ which means first element has index 0.
894 69&nbsp;echo
895 70&nbsp;echo "POP"
896 71&nbsp;echo "New stack height for array2 = $height"
897 72&nbsp;
898 73&nbsp;ListArray
899 74&nbsp;
900 75&nbsp;# List only 2nd and 3rd elements of array0.
901 76&nbsp;from=1 # Zero-based numbering.
902 77&nbsp;to=2
903 78&nbsp;array3=( ${array0[@]:1:2} )
904 79&nbsp;echo
905 80&nbsp;echo "Elements in array3: ${array3[@]}"
906 81&nbsp;
907 82&nbsp;# Works like a string (array of characters).
908 83&nbsp;# Try some other "string" forms.
909 84&nbsp;
910 85&nbsp;# Replacement:
911 86&nbsp;array4=( ${array0[@]/second/2nd} )
912 87&nbsp;echo
913 88&nbsp;echo "Elements in array4: ${array4[@]}"
914 89&nbsp;
915 90&nbsp;# Replace all matching wildcarded string.
916 91&nbsp;array5=( ${array0[@]//new?/old} )
917 92&nbsp;echo
918 93&nbsp;echo "Elements in array5: ${array5[@]}"
919 94&nbsp;
920 95&nbsp;# Just when you are getting the feel for this . . .
921 96&nbsp;array6=( ${array0[@]#*new} )
922 97&nbsp;echo # This one might surprise you.
923 98&nbsp;echo "Elements in array6: ${array6[@]}"
924 99&nbsp;
925 100&nbsp;array7=( ${array0[@]#new1} )
926 101&nbsp;echo # After array6 this should not be a surprise.
927 102&nbsp;echo "Elements in array7: ${array7[@]}"
928 103&nbsp;
929 104&nbsp;# Which looks a lot like . . .
930 105&nbsp;array8=( ${array0[@]/new1/} )
931 106&nbsp;echo
932 107&nbsp;echo "Elements in array8: ${array8[@]}"
933 108&nbsp;
934 109&nbsp;# So what can one say about this?
935 110&nbsp;
936 111&nbsp;# The string operations are performed on
937 112&nbsp;#+ each of the elements in var[@] in succession.
938 113&nbsp;# Therefore : Bash supports string vector operations.
939 114&nbsp;# If the result is a zero length string,
940 115&nbsp;#+ that element disappears in the resulting assignment.
941 116&nbsp;# However, if the expansion is in quotes, the null elements remain.
942 117&nbsp;
943 118&nbsp;# Michael Zick: Question, are those strings hard or soft quotes?
944 119&nbsp;# Nathan Coulter: There is no such thing as "soft quotes."
945 120&nbsp;#! What's really happening is that
946 121&nbsp;#!+ the pattern matching happens after
947 122&nbsp;#!+ all the other expansions of [word]
948 123&nbsp;#!+ in cases like ${parameter#word}.
949 124&nbsp;
950 125&nbsp;
951 126&nbsp;zap='new*'
952 127&nbsp;array9=( ${array0[@]/$zap/} )
953 128&nbsp;echo
954 129&nbsp;echo "Number of elements in array9: ${#array9[@]}"
955 130&nbsp;array9=( "${array0[@]/$zap/}" )
956 131&nbsp;echo "Elements in array9: ${array9[@]}"
957 132&nbsp;# This time the null elements remain.
958 133&nbsp;echo "Number of elements in array9: ${#array9[@]}"
959 134&nbsp;
960 135&nbsp;
961 136&nbsp;# Just when you thought you were still in Kansas . . .
962 137&nbsp;array10=( ${array0[@]#$zap} )
963 138&nbsp;echo
964 139&nbsp;echo "Elements in array10: ${array10[@]}"
965 140&nbsp;# But, the asterisk in zap won't be interpreted if quoted.
966 141&nbsp;array10=( ${array0[@]#"$zap"} )
967 142&nbsp;echo
968 143&nbsp;echo "Elements in array10: ${array10[@]}"
969 144&nbsp;# Well, maybe we _are_ still in Kansas . . .
970 145&nbsp;# (Revisions to above code block by Nathan Coulter.)
971 146&nbsp;
972 147&nbsp;
973 148&nbsp;# Compare array7 with array10.
974 149&nbsp;# Compare array8 with array9.
975 150&nbsp;
976 151&nbsp;# Reiterating: No such thing as soft quotes!
977 152&nbsp;# Nathan Coulter explains:
978 153&nbsp;# Pattern matching of 'word' in ${parameter#word} is done after
979 154&nbsp;#+ parameter expansion and *before* quote removal.
980 155&nbsp;# In the normal case, pattern matching is done *after* quote removal.
981 156&nbsp;
982 157&nbsp;exit</PRE
983 ></TD
984 ></TR
985 ></TABLE
986 ><HR></DIV
987 ><P
988 >The relationship of <B
989 CLASS="COMMAND"
990 >${array_name[@]}</B
991 >
992 and <B
993 CLASS="COMMAND"
994 >${array_name[*]}</B
995 > is analogous to that
996 between <A
997 HREF="variables2.html#APPREF"
998 >$@ and $*</A
999 >. This powerful
1000 array notation has a number of uses.</P
1001 ><P
1002 ><A
1003 NAME="COPYARRAY0"
1004 ></A
1005 ></P
1006 ><P
1007 > <TABLE
1008 BORDER="0"
1009 BGCOLOR="#E0E0E0"
1010 WIDTH="100%"
1011 ><TR
1012 ><TD
1013 ><PRE
1014 CLASS="PROGRAMLISTING"
1015 > 1&nbsp;# Copying an array.
1016 2&nbsp;array2=( "${array1[@]}" )
1017 3&nbsp;# or
1018 4&nbsp;array2="${array1[@]}"
1019 5&nbsp;#
1020 6&nbsp;# However, this fails with "sparse" arrays,
1021 7&nbsp;#+ arrays with holes (missing elements) in them,
1022 8&nbsp;#+ as Jochen DeSmet points out.
1023 9&nbsp;# ------------------------------------------
1024 10&nbsp; array1[0]=0
1025 11&nbsp;# array1[1] not assigned
1026 12&nbsp; array1[2]=2
1027 13&nbsp; array2=( "${array1[@]}" ) # Copy it?
1028 14&nbsp;
1029 15&nbsp;echo ${array2[0]} # 0
1030 16&nbsp;echo ${array2[2]} # (null), should be 2
1031 17&nbsp;# ------------------------------------------
1032 18&nbsp;
1033 19&nbsp;
1034 20&nbsp;
1035 21&nbsp;# Adding an element to an array.
1036 22&nbsp;array=( "${array[@]}" "new element" )
1037 23&nbsp;# or
1038 24&nbsp;array[${#array[*]}]="new element"
1039 25&nbsp;
1040 26&nbsp;# Thanks, S.C.</PRE
1041 ></TD
1042 ></TR
1043 ></TABLE
1044 >
1045 </P
1046 ><P
1047 ><A
1048 NAME="ARRAYINITCS"
1049 ></A
1050 ></P
1051 ><DIV
1052 CLASS="TIP"
1053 ><TABLE
1054 CLASS="TIP"
1055 WIDTH="100%"
1056 BORDER="0"
1057 ><TR
1058 ><TD
1059 WIDTH="25"
1060 ALIGN="CENTER"
1061 VALIGN="TOP"
1062 ><IMG
1063 SRC="common/tip.png"
1064 HSPACE="5"
1065 ALT="Tip"></TD
1066 ><TD
1067 ALIGN="LEFT"
1068 VALIGN="TOP"
1069 ><P
1070 >The <B
1071 CLASS="COMMAND"
1072 >array=( element1 element2 ... elementN )</B
1073 >
1074 initialization operation, with the help of <A
1075 HREF="commandsub.html#COMMANDSUBREF"
1076 >command substitution</A
1077 >, makes it
1078 possible to load the contents of a text file into an array.</P
1079 ><P
1080 >
1081 <TABLE
1082 BORDER="0"
1083 BGCOLOR="#E0E0E0"
1084 WIDTH="100%"
1085 ><TR
1086 ><TD
1087 ><PRE
1088 CLASS="PROGRAMLISTING"
1089 > 1&nbsp;#!/bin/bash
1090 2&nbsp;
1091 3&nbsp;filename=sample_file
1092 4&nbsp;
1093 5&nbsp;# cat sample_file
1094 6&nbsp;#
1095 7&nbsp;# 1 a b c
1096 8&nbsp;# 2 d e fg
1097 9&nbsp;
1098 10&nbsp;
1099 11&nbsp;declare -a array1
1100 12&nbsp;
1101 13&nbsp;array1=( `cat "$filename"`) # Loads contents
1102 14&nbsp;# List file to stdout #+ of $filename into array1.
1103 15&nbsp;#
1104 16&nbsp;# array1=( `cat "$filename" | tr '\n' ' '`)
1105 17&nbsp;# change linefeeds in file to spaces.
1106 18&nbsp;# Not necessary because Bash does word splitting,
1107 19&nbsp;#+ changing linefeeds to spaces.
1108 20&nbsp;
1109 21&nbsp;echo ${array1[@]} # List the array.
1110 22&nbsp;# 1 a b c 2 d e fg
1111 23&nbsp;#
1112 24&nbsp;# Each whitespace-separated "word" in the file
1113 25&nbsp;#+ has been assigned to an element of the array.
1114 26&nbsp;
1115 27&nbsp;element_count=${#array1[*]}
1116 28&nbsp;echo $element_count # 8</PRE
1117 ></TD
1118 ></TR
1119 ></TABLE
1120 >
1121 </P
1122 ></TD
1123 ></TR
1124 ></TABLE
1125 ></DIV
1126 ><P
1127 >Clever scripting makes it possible to add array operations.</P
1128 ><P
1129 ><A
1130 NAME="ARRAYASSIGN0"
1131 ></A
1132 ></P
1133 ><DIV
1134 CLASS="EXAMPLE"
1135 ><HR><A
1136 NAME="ARRAYASSIGN"
1137 ></A
1138 ><P
1139 ><B
1140 >Example 27-8. Initializing arrays</B
1141 ></P
1142 ><TABLE
1143 BORDER="0"
1144 BGCOLOR="#E0E0E0"
1145 WIDTH="100%"
1146 ><TR
1147 ><TD
1148 ><PRE
1149 CLASS="PROGRAMLISTING"
1150 > 1&nbsp;#! /bin/bash
1151 2&nbsp;# array-assign.bash
1152 3&nbsp;
1153 4&nbsp;# Array operations are Bash-specific,
1154 5&nbsp;#+ hence the ".bash" in the script name.
1155 6&nbsp;
1156 7&nbsp;# Copyright (c) Michael S. Zick, 2003, All rights reserved.
1157 8&nbsp;# License: Unrestricted reuse in any form, for any purpose.
1158 9&nbsp;# Version: $ID$
1159 10&nbsp;#
1160 11&nbsp;# Clarification and additional comments by William Park.
1161 12&nbsp;
1162 13&nbsp;# Based on an example provided by Stephane Chazelas
1163 14&nbsp;#+ which appeared in an earlier version of the
1164 15&nbsp;#+ Advanced Bash Scripting Guide.
1165 16&nbsp;
1166 17&nbsp;# Output format of the 'times' command:
1167 18&nbsp;# User CPU &#60;space&#62; System CPU
1168 19&nbsp;# User CPU of dead children &#60;space&#62; System CPU of dead children
1169 20&nbsp;
1170 21&nbsp;# Bash has two versions of assigning all elements of an array
1171 22&nbsp;#+ to a new array variable.
1172 23&nbsp;# Both drop 'null reference' elements
1173 24&nbsp;#+ in Bash versions 2.04 and later.
1174 25&nbsp;# An additional array assignment that maintains the relationship of
1175 26&nbsp;#+ [subscript]=value for arrays may be added to newer versions.
1176 27&nbsp;
1177 28&nbsp;# Constructs a large array using an internal command,
1178 29&nbsp;#+ but anything creating an array of several thousand elements
1179 30&nbsp;#+ will do just fine.
1180 31&nbsp;
1181 32&nbsp;declare -a bigOne=( /dev/* ) # All the files in /dev . . .
1182 33&nbsp;echo
1183 34&nbsp;echo 'Conditions: Unquoted, default IFS, All-Elements-Of'
1184 35&nbsp;echo "Number of elements in array is ${#bigOne[@]}"
1185 36&nbsp;
1186 37&nbsp;# set -vx
1187 38&nbsp;
1188 39&nbsp;
1189 40&nbsp;
1190 41&nbsp;echo
1191 42&nbsp;echo '- - testing: =( ${array[@]} ) - -'
1192 43&nbsp;times
1193 44&nbsp;declare -a bigTwo=( ${bigOne[@]} )
1194 45&nbsp;# Note parens: ^ ^
1195 46&nbsp;times
1196 47&nbsp;
1197 48&nbsp;
1198 49&nbsp;echo
1199 50&nbsp;echo '- - testing: =${array[@]} - -'
1200 51&nbsp;times
1201 52&nbsp;declare -a bigThree=${bigOne[@]}
1202 53&nbsp;# No parentheses this time.
1203 54&nbsp;times
1204 55&nbsp;
1205 56&nbsp;# Comparing the numbers shows that the second form, pointed out
1206 57&nbsp;#+ by Stephane Chazelas, is faster.
1207 58&nbsp;#
1208 59&nbsp;# As William Park explains:
1209 60&nbsp;#+ The bigTwo array assigned element by element (because of parentheses),
1210 61&nbsp;#+ whereas bigThree assigned as a single string.
1211 62&nbsp;# So, in essence, you have:
1212 63&nbsp;# bigTwo=( [0]="..." [1]="..." [2]="..." ... )
1213 64&nbsp;# bigThree=( [0]="... ... ..." )
1214 65&nbsp;#
1215 66&nbsp;# Verify this by: echo ${bigTwo[0]}
1216 67&nbsp;# echo ${bigThree[0]}
1217 68&nbsp;
1218 69&nbsp;
1219 70&nbsp;# I will continue to use the first form in my example descriptions
1220 71&nbsp;#+ because I think it is a better illustration of what is happening.
1221 72&nbsp;
1222 73&nbsp;# The reusable portions of my examples will actual contain
1223 74&nbsp;#+ the second form where appropriate because of the speedup.
1224 75&nbsp;
1225 76&nbsp;# MSZ: Sorry about that earlier oversight folks.
1226 77&nbsp;
1227 78&nbsp;
1228 79&nbsp;# Note:
1229 80&nbsp;# ----
1230 81&nbsp;# The "declare -a" statements in lines 32 and 44
1231 82&nbsp;#+ are not strictly necessary, since it is implicit
1232 83&nbsp;#+ in the Array=( ... ) assignment form.
1233 84&nbsp;# However, eliminating these declarations slows down
1234 85&nbsp;#+ the execution of the following sections of the script.
1235 86&nbsp;# Try it, and see.
1236 87&nbsp;
1237 88&nbsp;exit 0</PRE
1238 ></TD
1239 ></TR
1240 ></TABLE
1241 ><HR></DIV
1242 ><DIV
1243 CLASS="NOTE"
1244 ><TABLE
1245 CLASS="NOTE"
1246 WIDTH="100%"
1247 BORDER="0"
1248 ><TR
1249 ><TD
1250 WIDTH="25"
1251 ALIGN="CENTER"
1252 VALIGN="TOP"
1253 ><IMG
1254 SRC="common/note.png"
1255 HSPACE="5"
1256 ALT="Note"></TD
1257 ><TD
1258 ALIGN="LEFT"
1259 VALIGN="TOP"
1260 ><P
1261 >Adding a superfluous <B
1262 CLASS="COMMAND"
1263 >declare -a</B
1264 >
1265 statement to an array declaration may speed up execution of
1266 subsequent operations on the array.</P
1267 ></TD
1268 ></TR
1269 ></TABLE
1270 ></DIV
1271 ><P
1272 ><A
1273 NAME="ARRAYAPPEND0"
1274 ></A
1275 ></P
1276 ><DIV
1277 CLASS="EXAMPLE"
1278 ><HR><A
1279 NAME="COPYARRAY"
1280 ></A
1281 ><P
1282 ><B
1283 >Example 27-9. Copying and concatenating arrays</B
1284 ></P
1285 ><TABLE
1286 BORDER="0"
1287 BGCOLOR="#E0E0E0"
1288 WIDTH="100%"
1289 ><TR
1290 ><TD
1291 ><PRE
1292 CLASS="PROGRAMLISTING"
1293 > 1&nbsp;#! /bin/bash
1294 2&nbsp;# CopyArray.sh
1295 3&nbsp;#
1296 4&nbsp;# This script written by Michael Zick.
1297 5&nbsp;# Used here with permission.
1298 6&nbsp;
1299 7&nbsp;# How-To "Pass by Name &#38; Return by Name"
1300 8&nbsp;#+ or "Building your own assignment statement".
1301 9&nbsp;
1302 10&nbsp;
1303 11&nbsp;CpArray_Mac() {
1304 12&nbsp;
1305 13&nbsp;# Assignment Command Statement Builder
1306 14&nbsp;
1307 15&nbsp; echo -n 'eval '
1308 16&nbsp; echo -n "$2" # Destination name
1309 17&nbsp; echo -n '=( ${'
1310 18&nbsp; echo -n "$1" # Source name
1311 19&nbsp; echo -n '[@]} )'
1312 20&nbsp;
1313 21&nbsp;# That could all be a single command.
1314 22&nbsp;# Matter of style only.
1315 23&nbsp;}
1316 24&nbsp;
1317 25&nbsp;declare -f CopyArray # Function "Pointer"
1318 26&nbsp;CopyArray=CpArray_Mac # Statement Builder
1319 27&nbsp;
1320 28&nbsp;Hype()
1321 29&nbsp;{
1322 30&nbsp;
1323 31&nbsp;# Hype the array named $1.
1324 32&nbsp;# (Splice it together with array containing "Really Rocks".)
1325 33&nbsp;# Return in array named $2.
1326 34&nbsp;
1327 35&nbsp; local -a TMP
1328 36&nbsp; local -a hype=( Really Rocks )
1329 37&nbsp;
1330 38&nbsp; $($CopyArray $1 TMP)
1331 39&nbsp; TMP=( ${TMP[@]} ${hype[@]} )
1332 40&nbsp; $($CopyArray TMP $2)
1333 41&nbsp;}
1334 42&nbsp;
1335 43&nbsp;declare -a before=( Advanced Bash Scripting )
1336 44&nbsp;declare -a after
1337 45&nbsp;
1338 46&nbsp;echo "Array Before = ${before[@]}"
1339 47&nbsp;
1340 48&nbsp;Hype before after
1341 49&nbsp;
1342 50&nbsp;echo "Array After = ${after[@]}"
1343 51&nbsp;
1344 52&nbsp;# Too much hype?
1345 53&nbsp;
1346 54&nbsp;echo "What ${after[@]:3:2}?"
1347 55&nbsp;
1348 56&nbsp;declare -a modest=( ${after[@]:2:1} ${after[@]:3:2} )
1349 57&nbsp;# ---- substring extraction ----
1350 58&nbsp;
1351 59&nbsp;echo "Array Modest = ${modest[@]}"
1352 60&nbsp;
1353 61&nbsp;# What happened to 'before' ?
1354 62&nbsp;
1355 63&nbsp;echo "Array Before = ${before[@]}"
1356 64&nbsp;
1357 65&nbsp;exit 0</PRE
1358 ></TD
1359 ></TR
1360 ></TABLE
1361 ><HR></DIV
1362 ><DIV
1363 CLASS="EXAMPLE"
1364 ><HR><A
1365 NAME="ARRAYAPPEND"
1366 ></A
1367 ><P
1368 ><B
1369 >Example 27-10. More on concatenating arrays</B
1370 ></P
1371 ><TABLE
1372 BORDER="0"
1373 BGCOLOR="#E0E0E0"
1374 WIDTH="100%"
1375 ><TR
1376 ><TD
1377 ><PRE
1378 CLASS="PROGRAMLISTING"
1379 > 1&nbsp;#! /bin/bash
1380 2&nbsp;# array-append.bash
1381 3&nbsp;
1382 4&nbsp;# Copyright (c) Michael S. Zick, 2003, All rights reserved.
1383 5&nbsp;# License: Unrestricted reuse in any form, for any purpose.
1384 6&nbsp;# Version: $ID$
1385 7&nbsp;#
1386 8&nbsp;# Slightly modified in formatting by M.C.
1387 9&nbsp;
1388 10&nbsp;
1389 11&nbsp;# Array operations are Bash-specific.
1390 12&nbsp;# Legacy UNIX /bin/sh lacks equivalents.
1391 13&nbsp;
1392 14&nbsp;
1393 15&nbsp;# Pipe the output of this script to 'more'
1394 16&nbsp;#+ so it doesn't scroll off the terminal.
1395 17&nbsp;# Or, redirect output to a file.
1396 18&nbsp;
1397 19&nbsp;
1398 20&nbsp;declare -a array1=( zero1 one1 two1 )
1399 21&nbsp;# Subscript packed.
1400 22&nbsp;declare -a array2=( [0]=zero2 [2]=two2 [3]=three2 )
1401 23&nbsp;# Subscript sparse -- [1] is not defined.
1402 24&nbsp;
1403 25&nbsp;echo
1404 26&nbsp;echo '- Confirm that the array is really subscript sparse. -'
1405 27&nbsp;echo "Number of elements: 4" # Hard-coded for illustration.
1406 28&nbsp;for (( i = 0 ; i &#60; 4 ; i++ ))
1407 29&nbsp;do
1408 30&nbsp; echo "Element [$i]: ${array2[$i]}"
1409 31&nbsp;done
1410 32&nbsp;# See also the more general code example in basics-reviewed.bash.
1411 33&nbsp;
1412 34&nbsp;
1413 35&nbsp;declare -a dest
1414 36&nbsp;
1415 37&nbsp;# Combine (append) two arrays into a third array.
1416 38&nbsp;echo
1417 39&nbsp;echo 'Conditions: Unquoted, default IFS, All-Elements-Of operator'
1418 40&nbsp;echo '- Undefined elements not present, subscripts not maintained. -'
1419 41&nbsp;# # The undefined elements do not exist; they are not being dropped.
1420 42&nbsp;
1421 43&nbsp;dest=( ${array1[@]} ${array2[@]} )
1422 44&nbsp;# dest=${array1[@]}${array2[@]} # Strange results, possibly a bug.
1423 45&nbsp;
1424 46&nbsp;# Now, list the result.
1425 47&nbsp;echo
1426 48&nbsp;echo '- - Testing Array Append - -'
1427 49&nbsp;cnt=${#dest[@]}
1428 50&nbsp;
1429 51&nbsp;echo "Number of elements: $cnt"
1430 52&nbsp;for (( i = 0 ; i &#60; cnt ; i++ ))
1431 53&nbsp;do
1432 54&nbsp; echo "Element [$i]: ${dest[$i]}"
1433 55&nbsp;done
1434 56&nbsp;
1435 57&nbsp;# Assign an array to a single array element (twice).
1436 58&nbsp;dest[0]=${array1[@]}
1437 59&nbsp;dest[1]=${array2[@]}
1438 60&nbsp;
1439 61&nbsp;# List the result.
1440 62&nbsp;echo
1441 63&nbsp;echo '- - Testing modified array - -'
1442 64&nbsp;cnt=${#dest[@]}
1443 65&nbsp;
1444 66&nbsp;echo "Number of elements: $cnt"
1445 67&nbsp;for (( i = 0 ; i &#60; cnt ; i++ ))
1446 68&nbsp;do
1447 69&nbsp; echo "Element [$i]: ${dest[$i]}"
1448 70&nbsp;done
1449 71&nbsp;
1450 72&nbsp;# Examine the modified second element.
1451 73&nbsp;echo
1452 74&nbsp;echo '- - Reassign and list second element - -'
1453 75&nbsp;
1454 76&nbsp;declare -a subArray=${dest[1]}
1455 77&nbsp;cnt=${#subArray[@]}
1456 78&nbsp;
1457 79&nbsp;echo "Number of elements: $cnt"
1458 80&nbsp;for (( i = 0 ; i &#60; cnt ; i++ ))
1459 81&nbsp;do
1460 82&nbsp; echo "Element [$i]: ${subArray[$i]}"
1461 83&nbsp;done
1462 84&nbsp;
1463 85&nbsp;# The assignment of an entire array to a single element
1464 86&nbsp;#+ of another array using the '=${ ... }' array assignment
1465 87&nbsp;#+ has converted the array being assigned into a string,
1466 88&nbsp;#+ with the elements separated by a space (the first character of IFS).
1467 89&nbsp;
1468 90&nbsp;# If the original elements didn't contain whitespace . . .
1469 91&nbsp;# If the original array isn't subscript sparse . . .
1470 92&nbsp;# Then we could get the original array structure back again.
1471 93&nbsp;
1472 94&nbsp;# Restore from the modified second element.
1473 95&nbsp;echo
1474 96&nbsp;echo '- - Listing restored element - -'
1475 97&nbsp;
1476 98&nbsp;declare -a subArray=( ${dest[1]} )
1477 99&nbsp;cnt=${#subArray[@]}
1478 100&nbsp;
1479 101&nbsp;echo "Number of elements: $cnt"
1480 102&nbsp;for (( i = 0 ; i &#60; cnt ; i++ ))
1481 103&nbsp;do
1482 104&nbsp; echo "Element [$i]: ${subArray[$i]}"
1483 105&nbsp;done
1484 106&nbsp;echo '- - Do not depend on this behavior. - -'
1485 107&nbsp;echo '- - This behavior is subject to change - -'
1486 108&nbsp;echo '- - in versions of Bash newer than version 2.05b - -'
1487 109&nbsp;
1488 110&nbsp;# MSZ: Sorry about any earlier confusion folks.
1489 111&nbsp;
1490 112&nbsp;exit 0</PRE
1491 ></TD
1492 ></TR
1493 ></TABLE
1494 ><HR></DIV
1495 ><P
1496 >--</P
1497 ><P
1498 >Arrays permit deploying old familiar algorithms as shell scripts.
1499 Whether this is necessarily a good idea is left for the reader to
1500 decide.</P
1501 ><P
1502 ><A
1503 NAME="BUBBLESORT"
1504 ></A
1505 ></P
1506 ><DIV
1507 CLASS="EXAMPLE"
1508 ><HR><A
1509 NAME="BUBBLE"
1510 ></A
1511 ><P
1512 ><B
1513 >Example 27-11. The Bubble Sort</B
1514 ></P
1515 ><TABLE
1516 BORDER="0"
1517 BGCOLOR="#E0E0E0"
1518 WIDTH="100%"
1519 ><TR
1520 ><TD
1521 ><PRE
1522 CLASS="PROGRAMLISTING"
1523 > 1&nbsp;#!/bin/bash
1524 2&nbsp;# bubble.sh: Bubble sort, of sorts.
1525 3&nbsp;
1526 4&nbsp;# Recall the algorithm for a bubble sort. In this particular version...
1527 5&nbsp;
1528 6&nbsp;# With each successive pass through the array to be sorted,
1529 7&nbsp;#+ compare two adjacent elements, and swap them if out of order.
1530 8&nbsp;# At the end of the first pass, the "heaviest" element has sunk to bottom.
1531 9&nbsp;# At the end of the second pass, the next "heaviest" one has sunk next to bottom.
1532 10&nbsp;# And so forth.
1533 11&nbsp;# This means that each successive pass needs to traverse less of the array.
1534 12&nbsp;# You will therefore notice a speeding up in the printing of the later passes.
1535 13&nbsp;
1536 14&nbsp;
1537 15&nbsp;exchange()
1538 16&nbsp;{
1539 17&nbsp; # Swaps two members of the array.
1540 18&nbsp; local temp=${Countries[$1]} # Temporary storage
1541 19&nbsp; #+ for element getting swapped out.
1542 20&nbsp; Countries[$1]=${Countries[$2]}
1543 21&nbsp; Countries[$2]=$temp
1544 22&nbsp;
1545 23&nbsp; return
1546 24&nbsp;}
1547 25&nbsp;
1548 26&nbsp;declare -a Countries # Declare array,
1549 27&nbsp; #+ optional here since it's initialized below.
1550 28&nbsp;
1551 29&nbsp;# Is it permissable to split an array variable over multiple lines
1552 30&nbsp;#+ using an escape (\)?
1553 31&nbsp;# Yes.
1554 32&nbsp;
1555 33&nbsp;Countries=(Netherlands Ukraine Zaire Turkey Russia Yemen Syria \
1556 34&nbsp;Brazil Argentina Nicaragua Japan Mexico Venezuela Greece England \
1557 35&nbsp;Israel Peru Canada Oman Denmark Wales France Kenya \
1558 36&nbsp;Xanadu Qatar Liechtenstein Hungary)
1559 37&nbsp;
1560 38&nbsp;# "Xanadu" is the mythical place where, according to Coleridge,
1561 39&nbsp;#+ Kubla Khan did a pleasure dome decree.
1562 40&nbsp;
1563 41&nbsp;
1564 42&nbsp;clear # Clear the screen to start with.
1565 43&nbsp;
1566 44&nbsp;echo "0: ${Countries[*]}" # List entire array at pass 0.
1567 45&nbsp;
1568 46&nbsp;number_of_elements=${#Countries[@]}
1569 47&nbsp;let "comparisons = $number_of_elements - 1"
1570 48&nbsp;
1571 49&nbsp;count=1 # Pass number.
1572 50&nbsp;
1573 51&nbsp;while [ "$comparisons" -gt 0 ] # Beginning of outer loop
1574 52&nbsp;do
1575 53&nbsp;
1576 54&nbsp; index=0 # Reset index to start of array after each pass.
1577 55&nbsp;
1578 56&nbsp; while [ "$index" -lt "$comparisons" ] # Beginning of inner loop
1579 57&nbsp; do
1580 58&nbsp; if [ ${Countries[$index]} \&#62; ${Countries[`expr $index + 1`]} ]
1581 59&nbsp; # If out of order...
1582 60&nbsp; # Recalling that \&#62; is ASCII comparison operator
1583 61&nbsp; #+ within single brackets.
1584 62&nbsp;
1585 63&nbsp; # if [[ ${Countries[$index]} &#62; ${Countries[`expr $index + 1`]} ]]
1586 64&nbsp; #+ also works.
1587 65&nbsp; then
1588 66&nbsp; exchange $index `expr $index + 1` # Swap.
1589 67&nbsp; fi
1590 68&nbsp; let "index += 1" # Or, index+=1 on Bash, ver. 3.1 or newer.
1591 69&nbsp; done # End of inner loop
1592 70&nbsp;
1593 71&nbsp;# ----------------------------------------------------------------------
1594 72&nbsp;# Paulo Marcel Coelho Aragao suggests for-loops as a simpler altenative.
1595 73&nbsp;#
1596 74&nbsp;# for (( last = $number_of_elements - 1 ; last &#62; 0 ; last-- ))
1597 75&nbsp;## Fix by C.Y. Hunt ^ (Thanks!)
1598 76&nbsp;# do
1599 77&nbsp;# for (( i = 0 ; i &#60; last ; i++ ))
1600 78&nbsp;# do
1601 79&nbsp;# [[ "${Countries[$i]}" &#62; "${Countries[$((i+1))]}" ]] \
1602 80&nbsp;# &#38;&#38; exchange $i $((i+1))
1603 81&nbsp;# done
1604 82&nbsp;# done
1605 83&nbsp;# ----------------------------------------------------------------------
1606 84&nbsp;
1607 85&nbsp;
1608 86&nbsp;let "comparisons -= 1" # Since "heaviest" element bubbles to bottom,
1609 87&nbsp; #+ we need do one less comparison each pass.
1610 88&nbsp;
1611 89&nbsp;echo
1612 90&nbsp;echo "$count: ${Countries[@]}" # Print resultant array at end of each pass.
1613 91&nbsp;echo
1614 92&nbsp;let "count += 1" # Increment pass count.
1615 93&nbsp;
1616 94&nbsp;done # End of outer loop
1617 95&nbsp; # All done.
1618 96&nbsp;
1619 97&nbsp;exit 0</PRE
1620 ></TD
1621 ></TR
1622 ></TABLE
1623 ><HR></DIV
1624 ><P
1625 >--</P
1626 ><P
1627 ><A
1628 NAME="ARRAYNEST"
1629 ></A
1630 ></P
1631 ><P
1632 >Is it possible to nest arrays within arrays?</P
1633 ><P
1634 ><TABLE
1635 BORDER="0"
1636 BGCOLOR="#E0E0E0"
1637 WIDTH="100%"
1638 ><TR
1639 ><TD
1640 ><PRE
1641 CLASS="PROGRAMLISTING"
1642 > 1&nbsp;#!/bin/bash
1643 2&nbsp;# "Nested" array.
1644 3&nbsp;
1645 4&nbsp;# Michael Zick provided this example,
1646 5&nbsp;#+ with corrections and clarifications by William Park.
1647 6&nbsp;
1648 7&nbsp;AnArray=( $(ls --inode --ignore-backups --almost-all \
1649 8&nbsp; --directory --full-time --color=none --time=status \
1650 9&nbsp; --sort=time -l ${PWD} ) ) # Commands and options.
1651 10&nbsp;
1652 11&nbsp;# Spaces are significant . . . and don't quote anything in the above.
1653 12&nbsp;
1654 13&nbsp;SubArray=( ${AnArray[@]:11:1} ${AnArray[@]:6:5} )
1655 14&nbsp;# This array has six elements:
1656 15&nbsp;#+ SubArray=( [0]=${AnArray[11]} [1]=${AnArray[6]} [2]=${AnArray[7]}
1657 16&nbsp;# [3]=${AnArray[8]} [4]=${AnArray[9]} [5]=${AnArray[10]} )
1658 17&nbsp;#
1659 18&nbsp;# Arrays in Bash are (circularly) linked lists
1660 19&nbsp;#+ of type string (char *).
1661 20&nbsp;# So, this isn't actually a nested array,
1662 21&nbsp;#+ but it's functionally similar.
1663 22&nbsp;
1664 23&nbsp;echo "Current directory and date of last status change:"
1665 24&nbsp;echo "${SubArray[@]}"
1666 25&nbsp;
1667 26&nbsp;exit 0</PRE
1668 ></TD
1669 ></TR
1670 ></TABLE
1671 ></P
1672 ><P
1673 >--</P
1674 ><P
1675 >Embedded arrays in combination with <A
1676 HREF="bash2.html#VARREFNEW"
1677 >indirect references</A
1678 > create some fascinating
1679 possibilities</P
1680 ><P
1681 ><A
1682 NAME="ARRAYINDIR"
1683 ></A
1684 ></P
1685 ><DIV
1686 CLASS="EXAMPLE"
1687 ><HR><A
1688 NAME="EMBARR"
1689 ></A
1690 ><P
1691 ><B
1692 >Example 27-12. Embedded arrays and indirect references</B
1693 ></P
1694 ><TABLE
1695 BORDER="0"
1696 BGCOLOR="#E0E0E0"
1697 WIDTH="100%"
1698 ><TR
1699 ><TD
1700 ><PRE
1701 CLASS="PROGRAMLISTING"
1702 > 1&nbsp;#!/bin/bash
1703 2&nbsp;# embedded-arrays.sh
1704 3&nbsp;# Embedded arrays and indirect references.
1705 4&nbsp;
1706 5&nbsp;# This script by Dennis Leeuw.
1707 6&nbsp;# Used with permission.
1708 7&nbsp;# Modified by document author.
1709 8&nbsp;
1710 9&nbsp;
1711 10&nbsp;ARRAY1=(
1712 11&nbsp; VAR1_1=value11
1713 12&nbsp; VAR1_2=value12
1714 13&nbsp; VAR1_3=value13
1715 14&nbsp;)
1716 15&nbsp;
1717 16&nbsp;ARRAY2=(
1718 17&nbsp; VARIABLE="test"
1719 18&nbsp; STRING="VAR1=value1 VAR2=value2 VAR3=value3"
1720 19&nbsp; ARRAY21=${ARRAY1[*]}
1721 20&nbsp;) # Embed ARRAY1 within this second array.
1722 21&nbsp;
1723 22&nbsp;function print () {
1724 23&nbsp; OLD_IFS="$IFS"
1725 24&nbsp; IFS=$'\n' # To print each array element
1726 25&nbsp; #+ on a separate line.
1727 26&nbsp; TEST1="ARRAY2[*]"
1728 27&nbsp; local ${!TEST1} # See what happens if you delete this line.
1729 28&nbsp; # Indirect reference.
1730 29&nbsp; # This makes the components of $TEST1
1731 30&nbsp; #+ accessible to this function.
1732 31&nbsp;
1733 32&nbsp;
1734 33&nbsp; # Let's see what we've got so far.
1735 34&nbsp; echo
1736 35&nbsp; echo "\$TEST1 = $TEST1" # Just the name of the variable.
1737 36&nbsp; echo; echo
1738 37&nbsp; echo "{\$TEST1} = ${!TEST1}" # Contents of the variable.
1739 38&nbsp; # That's what an indirect
1740 39&nbsp; #+ reference does.
1741 40&nbsp; echo
1742 41&nbsp; echo "-------------------------------------------"; echo
1743 42&nbsp; echo
1744 43&nbsp;
1745 44&nbsp;
1746 45&nbsp; # Print variable
1747 46&nbsp; echo "Variable VARIABLE: $VARIABLE"
1748 47&nbsp;
1749 48&nbsp; # Print a string element
1750 49&nbsp; IFS="$OLD_IFS"
1751 50&nbsp; TEST2="STRING[*]"
1752 51&nbsp; local ${!TEST2} # Indirect reference (as above).
1753 52&nbsp; echo "String element VAR2: $VAR2 from STRING"
1754 53&nbsp;
1755 54&nbsp; # Print an array element
1756 55&nbsp; TEST2="ARRAY21[*]"
1757 56&nbsp; local ${!TEST2} # Indirect reference (as above).
1758 57&nbsp; echo "Array element VAR1_1: $VAR1_1 from ARRAY21"
1759 58&nbsp;}
1760 59&nbsp;
1761 60&nbsp;print
1762 61&nbsp;echo
1763 62&nbsp;
1764 63&nbsp;exit 0
1765 64&nbsp;
1766 65&nbsp;# As the author of the script notes,
1767 66&nbsp;#+ "you can easily expand it to create named-hashes in bash."
1768 67&nbsp;# (Difficult) exercise for the reader: implement this.</PRE
1769 ></TD
1770 ></TR
1771 ></TABLE
1772 ><HR></DIV
1773 ><P
1774 >--</P
1775 ><P
1776 ><A
1777 NAME="PRIMES0"
1778 ></A
1779 ></P
1780 ><P
1781 >Arrays enable implementing a shell script version of the
1782 <I
1783 CLASS="FIRSTTERM"
1784 >Sieve of Eratosthenes</I
1785 >. Of course, a
1786 resource-intensive application of this nature should really be
1787 written in a compiled language, such as C. It runs excruciatingly
1788 slowly as a script.</P
1789 ><DIV
1790 CLASS="EXAMPLE"
1791 ><HR><A
1792 NAME="EX68"
1793 ></A
1794 ><P
1795 ><B
1796 >Example 27-13. The Sieve of Eratosthenes</B
1797 ></P
1798 ><TABLE
1799 BORDER="0"
1800 BGCOLOR="#E0E0E0"
1801 WIDTH="100%"
1802 ><TR
1803 ><TD
1804 ><PRE
1805 CLASS="PROGRAMLISTING"
1806 > 1&nbsp;#!/bin/bash
1807 2&nbsp;# sieve.sh (ex68.sh)
1808 3&nbsp;
1809 4&nbsp;# Sieve of Eratosthenes
1810 5&nbsp;# Ancient algorithm for finding prime numbers.
1811 6&nbsp;
1812 7&nbsp;# This runs a couple of orders of magnitude slower
1813 8&nbsp;#+ than the equivalent program written in C.
1814 9&nbsp;
1815 10&nbsp;LOWER_LIMIT=1 # Starting with 1.
1816 11&nbsp;UPPER_LIMIT=1000 # Up to 1000.
1817 12&nbsp;# (You may set this higher . . . if you have time on your hands.)
1818 13&nbsp;
1819 14&nbsp;PRIME=1
1820 15&nbsp;NON_PRIME=0
1821 16&nbsp;
1822 17&nbsp;let SPLIT=UPPER_LIMIT/2
1823 18&nbsp;# Optimization:
1824 19&nbsp;# Need to test numbers only halfway to upper limit. Why?
1825 20&nbsp;
1826 21&nbsp;
1827 22&nbsp;declare -a Primes
1828 23&nbsp;# Primes[] is an array.
1829 24&nbsp;
1830 25&nbsp;
1831 26&nbsp;initialize ()
1832 27&nbsp;{
1833 28&nbsp;# Initialize the array.
1834 29&nbsp;
1835 30&nbsp;i=$LOWER_LIMIT
1836 31&nbsp;until [ "$i" -gt "$UPPER_LIMIT" ]
1837 32&nbsp;do
1838 33&nbsp; Primes[i]=$PRIME
1839 34&nbsp; let "i += 1"
1840 35&nbsp;done
1841 36&nbsp;# Assume all array members guilty (prime)
1842 37&nbsp;#+ until proven innocent.
1843 38&nbsp;}
1844 39&nbsp;
1845 40&nbsp;print_primes ()
1846 41&nbsp;{
1847 42&nbsp;# Print out the members of the Primes[] array tagged as prime.
1848 43&nbsp;
1849 44&nbsp;i=$LOWER_LIMIT
1850 45&nbsp;
1851 46&nbsp;until [ "$i" -gt "$UPPER_LIMIT" ]
1852 47&nbsp;do
1853 48&nbsp;
1854 49&nbsp; if [ "${Primes[i]}" -eq "$PRIME" ]
1855 50&nbsp; then
1856 51&nbsp; printf "%8d" $i
1857 52&nbsp; # 8 spaces per number gives nice, even columns.
1858 53&nbsp; fi
1859 54&nbsp;
1860 55&nbsp; let "i += 1"
1861 56&nbsp;
1862 57&nbsp;done
1863 58&nbsp;
1864 59&nbsp;}
1865 60&nbsp;
1866 61&nbsp;sift () # Sift out the non-primes.
1867 62&nbsp;{
1868 63&nbsp;
1869 64&nbsp;let i=$LOWER_LIMIT+1
1870 65&nbsp;# Let's start with 2.
1871 66&nbsp;
1872 67&nbsp;until [ "$i" -gt "$UPPER_LIMIT" ]
1873 68&nbsp;do
1874 69&nbsp;
1875 70&nbsp;if [ "${Primes[i]}" -eq "$PRIME" ]
1876 71&nbsp;# Don't bother sieving numbers already sieved (tagged as non-prime).
1877 72&nbsp;then
1878 73&nbsp;
1879 74&nbsp; t=$i
1880 75&nbsp;
1881 76&nbsp; while [ "$t" -le "$UPPER_LIMIT" ]
1882 77&nbsp; do
1883 78&nbsp; let "t += $i "
1884 79&nbsp; Primes[t]=$NON_PRIME
1885 80&nbsp; # Tag as non-prime all multiples.
1886 81&nbsp; done
1887 82&nbsp;
1888 83&nbsp;fi
1889 84&nbsp;
1890 85&nbsp; let "i += 1"
1891 86&nbsp;done
1892 87&nbsp;
1893 88&nbsp;
1894 89&nbsp;}
1895 90&nbsp;
1896 91&nbsp;
1897 92&nbsp;# ==============================================
1898 93&nbsp;# main ()
1899 94&nbsp;# Invoke the functions sequentially.
1900 95&nbsp;initialize
1901 96&nbsp;sift
1902 97&nbsp;print_primes
1903 98&nbsp;# This is what they call structured programming.
1904 99&nbsp;# ==============================================
1905 100&nbsp;
1906 101&nbsp;echo
1907 102&nbsp;
1908 103&nbsp;exit 0
1909 104&nbsp;
1910 105&nbsp;
1911 106&nbsp;
1912 107&nbsp;# -------------------------------------------------------- #
1913 108&nbsp;# Code below line will not execute, because of 'exit.'
1914 109&nbsp;
1915 110&nbsp;# This improved version of the Sieve, by Stephane Chazelas,
1916 111&nbsp;#+ executes somewhat faster.
1917 112&nbsp;
1918 113&nbsp;# Must invoke with command-line argument (limit of primes).
1919 114&nbsp;
1920 115&nbsp;UPPER_LIMIT=$1 # From command-line.
1921 116&nbsp;let SPLIT=UPPER_LIMIT/2 # Halfway to max number.
1922 117&nbsp;
1923 118&nbsp;Primes=( '' $(seq $UPPER_LIMIT) )
1924 119&nbsp;
1925 120&nbsp;i=1
1926 121&nbsp;until (( ( i += 1 ) &#62; SPLIT )) # Need check only halfway.
1927 122&nbsp;do
1928 123&nbsp; if [[ -n ${Primes[i]} ]]
1929 124&nbsp; then
1930 125&nbsp; t=$i
1931 126&nbsp; until (( ( t += i ) &#62; UPPER_LIMIT ))
1932 127&nbsp; do
1933 128&nbsp; Primes[t]=
1934 129&nbsp; done
1935 130&nbsp; fi
1936 131&nbsp;done
1937 132&nbsp;echo ${Primes[*]}
1938 133&nbsp;
1939 134&nbsp;exit $?</PRE
1940 ></TD
1941 ></TR
1942 ></TABLE
1943 ><HR></DIV
1944 ><DIV
1945 CLASS="EXAMPLE"
1946 ><HR><A
1947 NAME="EX68A"
1948 ></A
1949 ><P
1950 ><B
1951 >Example 27-14. The Sieve of Eratosthenes, Optimized</B
1952 ></P
1953 ><TABLE
1954 BORDER="0"
1955 BGCOLOR="#E0E0E0"
1956 WIDTH="100%"
1957 ><TR
1958 ><TD
1959 ><PRE
1960 CLASS="PROGRAMLISTING"
1961 > 1&nbsp;#!/bin/bash
1962 2&nbsp;# Optimized Sieve of Eratosthenes
1963 3&nbsp;# Script by Jared Martin, with very minor changes by ABS Guide author.
1964 4&nbsp;# Used in ABS Guide with permission (thanks!).
1965 5&nbsp;
1966 6&nbsp;# Based on script in Advanced Bash Scripting Guide.
1967 7&nbsp;# http://tldp.org/LDP/abs/html/arrays.html#PRIMES0 (ex68.sh).
1968 8&nbsp;
1969 9&nbsp;# http://www.cs.hmc.edu/~oneill/papers/Sieve-JFP.pdf (reference)
1970 10&nbsp;# Check results against http://primes.utm.edu/lists/small/1000.txt
1971 11&nbsp;
1972 12&nbsp;# Necessary but not sufficient would be, e.g.,
1973 13&nbsp;# (($(sieve 7919 | wc -w) == 1000)) &#38;&#38; echo "7919 is the 1000th prime"
1974 14&nbsp;
1975 15&nbsp;UPPER_LIMIT=${1:?"Need an upper limit of primes to search."}
1976 16&nbsp;
1977 17&nbsp;Primes=( '' $(seq ${UPPER_LIMIT}) )
1978 18&nbsp;
1979 19&nbsp;typeset -i i t
1980 20&nbsp;Primes[i=1]='' # 1 is not a prime.
1981 21&nbsp;until (( ( i += 1 ) &#62; (${UPPER_LIMIT}/i) )) # Need check only ith-way.
1982 22&nbsp; do # Why?
1983 23&nbsp; if ((${Primes[t=i*(i-1), i]}))
1984 24&nbsp; # Obscure, but instructive, use of arithmetic expansion in subscript.
1985 25&nbsp; then
1986 26&nbsp; until (( ( t += i ) &#62; ${UPPER_LIMIT} ))
1987 27&nbsp; do Primes[t]=; done
1988 28&nbsp; fi
1989 29&nbsp; done
1990 30&nbsp;
1991 31&nbsp;# echo ${Primes[*]}
1992 32&nbsp;echo # Change to original script for pretty-printing (80-col. display).
1993 33&nbsp;printf "%8d" ${Primes[*]}
1994 34&nbsp;echo; echo
1995 35&nbsp;
1996 36&nbsp;exit $?</PRE
1997 ></TD
1998 ></TR
1999 ></TABLE
2000 ><HR></DIV
2001 ><P
2002 >Compare these array-based prime number generators with
2003 alternatives that do not use arrays, <A
2004 HREF="contributed-scripts.html#PRIMES"
2005 >Example A-15</A
2006 >,
2007 and <A
2008 HREF="mathc.html#PRIMES2"
2009 >Example 16-46</A
2010 >.</P
2011 ><P
2012 >--</P
2013 ><P
2014 >Arrays lend themselves, to some extent, to emulating data
2015 structures for which Bash has no native support.</P
2016 ><P
2017 ><A
2018 NAME="STACKEX0"
2019 ></A
2020 ></P
2021 ><DIV
2022 CLASS="EXAMPLE"
2023 ><HR><A
2024 NAME="STACKEX"
2025 ></A
2026 ><P
2027 ><B
2028 >Example 27-15. Emulating a push-down stack</B
2029 ></P
2030 ><TABLE
2031 BORDER="0"
2032 BGCOLOR="#E0E0E0"
2033 WIDTH="100%"
2034 ><TR
2035 ><TD
2036 ><PRE
2037 CLASS="PROGRAMLISTING"
2038 > 1&nbsp;#!/bin/bash
2039 2&nbsp;# stack.sh: push-down stack simulation
2040 3&nbsp;
2041 4&nbsp;# Similar to the CPU stack, a push-down stack stores data items
2042 5&nbsp;#+ sequentially, but releases them in reverse order, last-in first-out.
2043 6&nbsp;
2044 7&nbsp;
2045 8&nbsp;BP=100 # Base Pointer of stack array.
2046 9&nbsp; # Begin at element 100.
2047 10&nbsp;
2048 11&nbsp;SP=$BP # Stack Pointer.
2049 12&nbsp; # Initialize it to "base" (bottom) of stack.
2050 13&nbsp;
2051 14&nbsp;Data= # Contents of stack location.
2052 15&nbsp; # Must use global variable,
2053 16&nbsp; #+ because of limitation on function return range.
2054 17&nbsp;
2055 18&nbsp;
2056 19&nbsp; # 100 Base pointer &#60;-- Base Pointer
2057 20&nbsp; # 99 First data item
2058 21&nbsp; # 98 Second data item
2059 22&nbsp; # ... More data
2060 23&nbsp; # Last data item &#60;-- Stack pointer
2061 24&nbsp;
2062 25&nbsp;
2063 26&nbsp;declare -a stack
2064 27&nbsp;
2065 28&nbsp;
2066 29&nbsp;push() # Push item on stack.
2067 30&nbsp;{
2068 31&nbsp;if [ -z "$1" ] # Nothing to push?
2069 32&nbsp;then
2070 33&nbsp; return
2071 34&nbsp;fi
2072 35&nbsp;
2073 36&nbsp;let "SP -= 1" # Bump stack pointer.
2074 37&nbsp;stack[$SP]=$1
2075 38&nbsp;
2076 39&nbsp;return
2077 40&nbsp;}
2078 41&nbsp;
2079 42&nbsp;pop() # Pop item off stack.
2080 43&nbsp;{
2081 44&nbsp;Data= # Empty out data item.
2082 45&nbsp;
2083 46&nbsp;if [ "$SP" -eq "$BP" ] # Stack empty?
2084 47&nbsp;then
2085 48&nbsp; return
2086 49&nbsp;fi # This also keeps SP from getting past 100,
2087 50&nbsp; #+ i.e., prevents a runaway stack.
2088 51&nbsp;
2089 52&nbsp;Data=${stack[$SP]}
2090 53&nbsp;let "SP += 1" # Bump stack pointer.
2091 54&nbsp;return
2092 55&nbsp;}
2093 56&nbsp;
2094 57&nbsp;status_report() # Find out what's happening.
2095 58&nbsp;{
2096 59&nbsp;echo "-------------------------------------"
2097 60&nbsp;echo "REPORT"
2098 61&nbsp;echo "Stack Pointer = $SP"
2099 62&nbsp;echo "Just popped \""$Data"\" off the stack."
2100 63&nbsp;echo "-------------------------------------"
2101 64&nbsp;echo
2102 65&nbsp;}
2103 66&nbsp;
2104 67&nbsp;
2105 68&nbsp;# =======================================================
2106 69&nbsp;# Now, for some fun.
2107 70&nbsp;
2108 71&nbsp;echo
2109 72&nbsp;
2110 73&nbsp;# See if you can pop anything off empty stack.
2111 74&nbsp;pop
2112 75&nbsp;status_report
2113 76&nbsp;
2114 77&nbsp;echo
2115 78&nbsp;
2116 79&nbsp;push garbage
2117 80&nbsp;pop
2118 81&nbsp;status_report # Garbage in, garbage out.
2119 82&nbsp;
2120 83&nbsp;value1=23; push $value1
2121 84&nbsp;value2=skidoo; push $value2
2122 85&nbsp;value3=LAST; push $value3
2123 86&nbsp;
2124 87&nbsp;pop # LAST
2125 88&nbsp;status_report
2126 89&nbsp;pop # skidoo
2127 90&nbsp;status_report
2128 91&nbsp;pop # 23
2129 92&nbsp;status_report # Last-in, first-out!
2130 93&nbsp;
2131 94&nbsp;# Notice how the stack pointer decrements with each push,
2132 95&nbsp;#+ and increments with each pop.
2133 96&nbsp;
2134 97&nbsp;echo
2135 98&nbsp;
2136 99&nbsp;exit 0
2137 100&nbsp;
2138 101&nbsp;# =======================================================
2139 102&nbsp;
2140 103&nbsp;
2141 104&nbsp;# Exercises:
2142 105&nbsp;# ---------
2143 106&nbsp;
2144 107&nbsp;# 1) Modify the "push()" function to permit pushing
2145 108&nbsp;# + multiple element on the stack with a single function call.
2146 109&nbsp;
2147 110&nbsp;# 2) Modify the "pop()" function to permit popping
2148 111&nbsp;# + multiple element from the stack with a single function call.
2149 112&nbsp;
2150 113&nbsp;# 3) Add error checking to the critical functions.
2151 114&nbsp;# That is, return an error code, depending on
2152 115&nbsp;# + successful or unsuccessful completion of the operation,
2153 116&nbsp;# + and take appropriate action.
2154 117&nbsp;
2155 118&nbsp;# 4) Using this script as a starting point,
2156 119&nbsp;# + write a stack-based 4-function calculator.</PRE
2157 ></TD
2158 ></TR
2159 ></TABLE
2160 ><HR></DIV
2161 ><P
2162 >--</P
2163 ><P
2164 >Fancy manipulation of array <SPAN
2165 CLASS="QUOTE"
2166 >"subscripts"</SPAN
2167 > may require
2168 intermediate variables. For projects involving this, again consider
2169 using a more powerful programming language, such as Perl or C.</P
2170 ><DIV
2171 CLASS="EXAMPLE"
2172 ><HR><A
2173 NAME="QFUNCTION"
2174 ></A
2175 ><P
2176 ><B
2177 >Example 27-16. Complex array application:
2178 <SPAN
2179 CLASS="emphasis"
2180 ><I
2181 CLASS="EMPHASIS"
2182 >Exploring a weird mathematical series</I
2183 ></SPAN
2184 ></B
2185 ></P
2186 ><TABLE
2187 BORDER="0"
2188 BGCOLOR="#E0E0E0"
2189 WIDTH="100%"
2190 ><TR
2191 ><TD
2192 ><PRE
2193 CLASS="PROGRAMLISTING"
2194 > 1&nbsp;#!/bin/bash
2195 2&nbsp;
2196 3&nbsp;# Douglas Hofstadter's notorious "Q-series":
2197 4&nbsp;
2198 5&nbsp;# Q(1) = Q(2) = 1
2199 6&nbsp;# Q(n) = Q(n - Q(n-1)) + Q(n - Q(n-2)), for n&#62;2
2200 7&nbsp;
2201 8&nbsp;# This is a "chaotic" integer series with strange
2202 9&nbsp;#+ and unpredictable behavior.
2203 10&nbsp;# The first 20 terms of the series are:
2204 11&nbsp;# 1 1 2 3 3 4 5 5 6 6 6 8 8 8 10 9 10 11 11 12
2205 12&nbsp;
2206 13&nbsp;# See Hofstadter's book, _Goedel, Escher, Bach: An Eternal Golden Braid_,
2207 14&nbsp;#+ p. 137, ff.
2208 15&nbsp;
2209 16&nbsp;
2210 17&nbsp;LIMIT=100 # Number of terms to calculate.
2211 18&nbsp;LINEWIDTH=20 # Number of terms printed per line.
2212 19&nbsp;
2213 20&nbsp;Q[1]=1 # First two terms of series are 1.
2214 21&nbsp;Q[2]=1
2215 22&nbsp;
2216 23&nbsp;echo
2217 24&nbsp;echo "Q-series [$LIMIT terms]:"
2218 25&nbsp;echo -n "${Q[1]} " # Output first two terms.
2219 26&nbsp;echo -n "${Q[2]} "
2220 27&nbsp;
2221 28&nbsp;for ((n=3; n &#60;= $LIMIT; n++)) # C-like loop expression.
2222 29&nbsp;do # Q[n] = Q[n - Q[n-1]] + Q[n - Q[n-2]] for n&#62;2
2223 30&nbsp;# Need to break the expression into intermediate terms,
2224 31&nbsp;#+ since Bash doesn't handle complex array arithmetic very well.
2225 32&nbsp;
2226 33&nbsp; let "n1 = $n - 1" # n-1
2227 34&nbsp; let "n2 = $n - 2" # n-2
2228 35&nbsp;
2229 36&nbsp; t0=`expr $n - ${Q[n1]}` # n - Q[n-1]
2230 37&nbsp; t1=`expr $n - ${Q[n2]}` # n - Q[n-2]
2231 38&nbsp;
2232 39&nbsp; T0=${Q[t0]} # Q[n - Q[n-1]]
2233 40&nbsp; T1=${Q[t1]} # Q[n - Q[n-2]]
2234 41&nbsp;
2235 42&nbsp;Q[n]=`expr $T0 + $T1` # Q[n - Q[n-1]] + Q[n - Q[n-2]]
2236 43&nbsp;echo -n "${Q[n]} "
2237 44&nbsp;
2238 45&nbsp;if [ `expr $n % $LINEWIDTH` -eq 0 ] # Format output.
2239 46&nbsp;then # ^ modulo
2240 47&nbsp; echo # Break lines into neat chunks.
2241 48&nbsp;fi
2242 49&nbsp;
2243 50&nbsp;done
2244 51&nbsp;
2245 52&nbsp;echo
2246 53&nbsp;
2247 54&nbsp;exit 0
2248 55&nbsp;
2249 56&nbsp;# This is an iterative implementation of the Q-series.
2250 57&nbsp;# The more intuitive recursive implementation is left as an exercise.
2251 58&nbsp;# Warning: calculating this series recursively takes a VERY long time
2252 59&nbsp;#+ via a script. C/C++ would be orders of magnitude faster.</PRE
2253 ></TD
2254 ></TR
2255 ></TABLE
2256 ><HR></DIV
2257 ><P
2258 >--</P
2259 ><P
2260 ><A
2261 NAME="ARRAYMULTIDIM"
2262 ></A
2263 ></P
2264 ><P
2265 >Bash supports only one-dimensional arrays, though a little
2266 trickery permits simulating multi-dimensional ones.</P
2267 ><DIV
2268 CLASS="EXAMPLE"
2269 ><HR><A
2270 NAME="TWODIM"
2271 ></A
2272 ><P
2273 ><B
2274 >Example 27-17. Simulating a two-dimensional array, then tilting it</B
2275 ></P
2276 ><TABLE
2277 BORDER="0"
2278 BGCOLOR="#E0E0E0"
2279 WIDTH="100%"
2280 ><TR
2281 ><TD
2282 ><PRE
2283 CLASS="PROGRAMLISTING"
2284 > 1&nbsp;#!/bin/bash
2285 2&nbsp;# twodim.sh: Simulating a two-dimensional array.
2286 3&nbsp;
2287 4&nbsp;# A one-dimensional array consists of a single row.
2288 5&nbsp;# A two-dimensional array stores rows sequentially.
2289 6&nbsp;
2290 7&nbsp;Rows=5
2291 8&nbsp;Columns=5
2292 9&nbsp;# 5 X 5 Array.
2293 10&nbsp;
2294 11&nbsp;declare -a alpha # char alpha [Rows] [Columns];
2295 12&nbsp; # Unnecessary declaration. Why?
2296 13&nbsp;
2297 14&nbsp;load_alpha ()
2298 15&nbsp;{
2299 16&nbsp;local rc=0
2300 17&nbsp;local index
2301 18&nbsp;
2302 19&nbsp;for i in A B C D E F G H I J K L M N O P Q R S T U V W X Y
2303 20&nbsp;do # Use different symbols if you like.
2304 21&nbsp; local row=`expr $rc / $Columns`
2305 22&nbsp; local column=`expr $rc % $Rows`
2306 23&nbsp; let "index = $row * $Rows + $column"
2307 24&nbsp; alpha[$index]=$i
2308 25&nbsp;# alpha[$row][$column]
2309 26&nbsp; let "rc += 1"
2310 27&nbsp;done
2311 28&nbsp;
2312 29&nbsp;# Simpler would be
2313 30&nbsp;#+ declare -a alpha=( A B C D E F G H I J K L M N O P Q R S T U V W X Y )
2314 31&nbsp;#+ but this somehow lacks the "flavor" of a two-dimensional array.
2315 32&nbsp;}
2316 33&nbsp;
2317 34&nbsp;print_alpha ()
2318 35&nbsp;{
2319 36&nbsp;local row=0
2320 37&nbsp;local index
2321 38&nbsp;
2322 39&nbsp;echo
2323 40&nbsp;
2324 41&nbsp;while [ "$row" -lt "$Rows" ] # Print out in "row major" order:
2325 42&nbsp;do #+ columns vary,
2326 43&nbsp; #+ while row (outer loop) remains the same.
2327 44&nbsp; local column=0
2328 45&nbsp;
2329 46&nbsp; echo -n " " # Lines up "square" array with rotated one.
2330 47&nbsp;
2331 48&nbsp; while [ "$column" -lt "$Columns" ]
2332 49&nbsp; do
2333 50&nbsp; let "index = $row * $Rows + $column"
2334 51&nbsp; echo -n "${alpha[index]} " # alpha[$row][$column]
2335 52&nbsp; let "column += 1"
2336 53&nbsp; done
2337 54&nbsp;
2338 55&nbsp; let "row += 1"
2339 56&nbsp; echo
2340 57&nbsp;
2341 58&nbsp;done
2342 59&nbsp;
2343 60&nbsp;# The simpler equivalent is
2344 61&nbsp;# echo ${alpha[*]} | xargs -n $Columns
2345 62&nbsp;
2346 63&nbsp;echo
2347 64&nbsp;}
2348 65&nbsp;
2349 66&nbsp;filter () # Filter out negative array indices.
2350 67&nbsp;{
2351 68&nbsp;
2352 69&nbsp;echo -n " " # Provides the tilt.
2353 70&nbsp; # Explain how.
2354 71&nbsp;
2355 72&nbsp;if [[ "$1" -ge 0 &#38;&#38; "$1" -lt "$Rows" &#38;&#38; "$2" -ge 0 &#38;&#38; "$2" -lt "$Columns" ]]
2356 73&nbsp;then
2357 74&nbsp; let "index = $1 * $Rows + $2"
2358 75&nbsp; # Now, print it rotated.
2359 76&nbsp; echo -n " ${alpha[index]}"
2360 77&nbsp; # alpha[$row][$column]
2361 78&nbsp;fi
2362 79&nbsp;
2363 80&nbsp;}
2364 81&nbsp;
2365 82&nbsp;
2366 83&nbsp;
2367 84&nbsp;
2368 85&nbsp;rotate () # Rotate the array 45 degrees --
2369 86&nbsp;{ #+ "balance" it on its lower lefthand corner.
2370 87&nbsp;local row
2371 88&nbsp;local column
2372 89&nbsp;
2373 90&nbsp;for (( row = Rows; row &#62; -Rows; row-- ))
2374 91&nbsp; do # Step through the array backwards. Why?
2375 92&nbsp;
2376 93&nbsp; for (( column = 0; column &#60; Columns; column++ ))
2377 94&nbsp; do
2378 95&nbsp;
2379 96&nbsp; if [ "$row" -ge 0 ]
2380 97&nbsp; then
2381 98&nbsp; let "t1 = $column - $row"
2382 99&nbsp; let "t2 = $column"
2383 100&nbsp; else
2384 101&nbsp; let "t1 = $column"
2385 102&nbsp; let "t2 = $column + $row"
2386 103&nbsp; fi
2387 104&nbsp;
2388 105&nbsp; filter $t1 $t2 # Filter out negative array indices.
2389 106&nbsp; # What happens if you don't do this?
2390 107&nbsp; done
2391 108&nbsp;
2392 109&nbsp; echo; echo
2393 110&nbsp;
2394 111&nbsp;done
2395 112&nbsp;
2396 113&nbsp;# Array rotation inspired by examples (pp. 143-146) in
2397 114&nbsp;#+ "Advanced C Programming on the IBM PC," by Herbert Mayer
2398 115&nbsp;#+ (see bibliography).
2399 116&nbsp;# This just goes to show that much of what can be done in C
2400 117&nbsp;#+ can also be done in shell scripting.
2401 118&nbsp;
2402 119&nbsp;}
2403 120&nbsp;
2404 121&nbsp;
2405 122&nbsp;#--------------- Now, let the show begin. ------------#
2406 123&nbsp;load_alpha # Load the array.
2407 124&nbsp;print_alpha # Print it out.
2408 125&nbsp;rotate # Rotate it 45 degrees counterclockwise.
2409 126&nbsp;#-----------------------------------------------------#
2410 127&nbsp;
2411 128&nbsp;exit 0
2412 129&nbsp;
2413 130&nbsp;# This is a rather contrived, not to mention inelegant simulation.
2414 131&nbsp;
2415 132&nbsp;# Exercises:
2416 133&nbsp;# ---------
2417 134&nbsp;# 1) Rewrite the array loading and printing functions
2418 135&nbsp;# in a more intuitive and less kludgy fashion.
2419 136&nbsp;#
2420 137&nbsp;# 2) Figure out how the array rotation functions work.
2421 138&nbsp;# Hint: think about the implications of backwards-indexing an array.
2422 139&nbsp;#
2423 140&nbsp;# 3) Rewrite this script to handle a non-square array,
2424 141&nbsp;# such as a 6 X 4 one.
2425 142&nbsp;# Try to minimize "distortion" when the array is rotated.</PRE
2426 ></TD
2427 ></TR
2428 ></TABLE
2429 ><HR></DIV
2430 ><P
2431 >A two-dimensional array is essentially equivalent to a
2432 one-dimensional one, but with additional addressing modes
2433 for referencing and manipulating the individual elements by
2434 <I
2435 CLASS="FIRSTTERM"
2436 >row</I
2437 > and <I
2438 CLASS="FIRSTTERM"
2439 >column</I
2440 >
2441 position.</P
2442 ><P
2443 >For an even more elaborate example of simulating a
2444 two-dimensional array, see <A
2445 HREF="contributed-scripts.html#LIFESLOW"
2446 >Example A-10</A
2447 >.</P
2448 ><P
2449 >--</P
2450 ><P
2451 >For more interesting scripts using arrays, see:
2452 <UL
2453 ><LI
2454 ><P
2455 ><A
2456 HREF="commandsub.html#AGRAM2"
2457 >Example 12-3</A
2458 ></P
2459 ></LI
2460 ><LI
2461 ><P
2462 ><A
2463 HREF="mathc.html#PRIMES2"
2464 >Example 16-46</A
2465 ></P
2466 ></LI
2467 ><LI
2468 ><P
2469 ><A
2470 HREF="contributed-scripts.html#HASHEX2"
2471 >Example A-22</A
2472 ></P
2473 ></LI
2474 ><LI
2475 ><P
2476 ><A
2477 HREF="contributed-scripts.html#HOMEWORK"
2478 >Example A-44</A
2479 ></P
2480 ></LI
2481 ><LI
2482 ><P
2483 ><A
2484 HREF="contributed-scripts.html#QKY"
2485 >Example A-41</A
2486 ></P
2487 ></LI
2488 ><LI
2489 ><P
2490 ><A
2491 HREF="contributed-scripts.html#NIM"
2492 >Example A-42</A
2493 ></P
2494 ></LI
2495 ></UL
2496 >
2497 </P
2498 ></DIV
2499 ><DIV
2500 CLASS="NAVFOOTER"
2501 ><HR
2502 ALIGN="LEFT"
2503 WIDTH="100%"><TABLE
2504 SUMMARY="Footer navigation table"
2505 WIDTH="100%"
2506 BORDER="0"
2507 CELLPADDING="0"
2508 CELLSPACING="0"
2509 ><TR
2510 ><TD
2511 WIDTH="33%"
2512 ALIGN="left"
2513 VALIGN="top"
2514 ><A
2515 HREF="list-cons.html"
2516 ACCESSKEY="P"
2517 >Prev</A
2518 ></TD
2519 ><TD
2520 WIDTH="34%"
2521 ALIGN="center"
2522 VALIGN="top"
2523 ><A
2524 HREF="index.html"
2525 ACCESSKEY="H"
2526 >Home</A
2527 ></TD
2528 ><TD
2529 WIDTH="33%"
2530 ALIGN="right"
2531 VALIGN="top"
2532 ><A
2533 HREF="ivr.html"
2534 ACCESSKEY="N"
2535 >Next</A
2536 ></TD
2537 ></TR
2538 ><TR
2539 ><TD
2540 WIDTH="33%"
2541 ALIGN="left"
2542 VALIGN="top"
2543 >List Constructs</TD
2544 ><TD
2545 WIDTH="34%"
2546 ALIGN="center"
2547 VALIGN="top"
2548 ><A
2549 HREF="part5.html"
2550 ACCESSKEY="U"
2551 >Up</A
2552 ></TD
2553 ><TD
2554 WIDTH="33%"
2555 ALIGN="right"
2556 VALIGN="top"
2557 >Indirect References</TD
2558 ></TR
2559 ></TABLE
2560 ></DIV
2561 ></BODY
2562 ></HTML
2563 >