| 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 #!/bin/bash |
| 156 | 2 |
| 157 | 3 |
| 158 | 4 area[11]=23 |
| 159 | 5 area[13]=37 |
| 160 | 6 area[51]=UFOs |
| 161 | 7 |
| 162 | 8 # Array members need not be consecutive or contiguous. |
| 163 | 9 |
| 164 | 10 # Some members of the array can be left uninitialized. |
| 165 | 11 # Gaps in the array are okay. |
| 166 | 12 # In fact, arrays with sparse data ("sparse arrays") |
| 167 | 13 #+ are useful in spreadsheet-processing software. |
| 168 | 14 |
| 169 | 15 |
| 170 | 16 echo -n "area[11] = " |
| 171 | 17 echo ${area[11]} # {curly brackets} needed. |
| 172 | 18 |
| 173 | 19 echo -n "area[13] = " |
| 174 | 20 echo ${area[13]} |
| 175 | 21 |
| 176 | 22 echo "Contents of area[51] are ${area[51]}." |
| 177 | 23 |
| 178 | 24 # Contents of uninitialized array variable print blank (null variable). |
| 179 | 25 echo -n "area[43] = " |
| 180 | 26 echo ${area[43]} |
| 181 | 27 echo "(area[43] unassigned)" |
| 182 | 28 |
| 183 | 29 echo |
| 184 | 30 |
| 185 | 31 # Sum of two array variables assigned to third |
| 186 | 32 area[5]=`expr ${area[11]} + ${area[13]}` |
| 187 | 33 echo "area[5] = area[11] + area[13]" |
| 188 | 34 echo -n "area[5] = " |
| 189 | 35 echo ${area[5]} |
| 190 | 36 |
| 191 | 37 area[6]=`expr ${area[11]} + ${area[51]}` |
| 192 | 38 echo "area[6] = area[11] + area[51]" |
| 193 | 39 echo -n "area[6] = " |
| 194 | 40 echo ${area[6]} |
| 195 | 41 # This fails because adding an integer to a string is not permitted. |
| 196 | 42 |
| 197 | 43 echo; echo; echo |
| 198 | 44 |
| 199 | 45 # ----------------------------------------------------------------- |
| 200 | 46 # Another array, "area2". |
| 201 | 47 # Another way of assigning array variables... |
| 202 | 48 # array_name=( XXX YYY ZZZ ... ) |
| 203 | 49 |
| 204 | 50 area2=( zero one two three four ) |
| 205 | 51 |
| 206 | 52 echo -n "area2[0] = " |
| 207 | 53 echo ${area2[0]} |
| 208 | 54 # Aha, zero-based indexing (first element of array is [0], not [1]). |
| 209 | 55 |
| 210 | 56 echo -n "area2[1] = " |
| 211 | 57 echo ${area2[1]} # [1] is second element of array. |
| 212 | 58 # ----------------------------------------------------------------- |
| 213 | 59 |
| 214 | 60 echo; echo; echo |
| 215 | 61 |
| 216 | 62 # ----------------------------------------------- |
| 217 | 63 # Yet another array, "area3". |
| 218 | 64 # Yet another way of assigning array variables... |
| 219 | 65 # array_name=([xx]=XXX [yy]=YYY ...) |
| 220 | 66 |
| 221 | 67 area3=([17]=seventeen [24]=twenty-four) |
| 222 | 68 |
| 223 | 69 echo -n "area3[17] = " |
| 224 | 70 echo ${area3[17]} |
| 225 | 71 |
| 226 | 72 echo -n "area3[24] = " |
| 227 | 73 echo ${area3[24]} |
| 228 | 74 # ----------------------------------------------- |
| 229 | 75 |
| 230 | 76 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 base64_charset=( {A..Z} {a..z} {0..9} + / = ) |
| 257 | 2 # Using extended brace expansion |
| 258 | 3 #+ to initialize the elements of the array. |
| 259 | 4 # Excerpted from vladz's "base64.sh" script |
| 260 | 5 #+ 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 string=abcABC123ABCabc |
| 294 | 2 echo ${string[@]} # abcABC123ABCabc |
| 295 | 3 echo ${string[*]} # abcABC123ABCabc |
| 296 | 4 echo ${string[0]} # abcABC123ABCabc |
| 297 | 5 echo ${string[1]} # No output! |
| 298 | 6 # Why? |
| 299 | 7 echo ${#string[@]} # 1 |
| 300 | 8 # One element in the array. |
| 301 | 9 # The string itself. |
| 302 | 10 |
| 303 | 11 # 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 #!/bin/bash |
| 336 | 2 # poem.sh: Pretty-prints one of the ABS Guide author's favorite poems. |
| 337 | 3 |
| 338 | 4 # Lines of the poem (single stanza). |
| 339 | 5 Line[1]="I do not know which to prefer," |
| 340 | 6 Line[2]="The beauty of inflections" |
| 341 | 7 Line[3]="Or the beauty of innuendoes," |
| 342 | 8 Line[4]="The blackbird whistling" |
| 343 | 9 Line[5]="Or just after." |
| 344 | 10 # Note that quoting permits embedding whitespace. |
| 345 | 11 |
| 346 | 12 # Attribution. |
| 347 | 13 Attrib[1]=" Wallace Stevens" |
| 348 | 14 Attrib[2]="\"Thirteen Ways of Looking at a Blackbird\"" |
| 349 | 15 # This poem is in the Public Domain (copyright expired). |
| 350 | 16 |
| 351 | 17 echo |
| 352 | 18 |
| 353 | 19 tput bold # Bold print. |
| 354 | 20 |
| 355 | 21 for index in 1 2 3 4 5 # Five lines. |
| 356 | 22 do |
| 357 | 23 printf " %s\n" "${Line[index]}" |
| 358 | 24 done |
| 359 | 25 |
| 360 | 26 for index in 1 2 # Two attribution lines. |
| 361 | 27 do |
| 362 | 28 printf " %s\n" "${Attrib[index]}" |
| 363 | 29 done |
| 364 | 30 |
| 365 | 31 tput sgr0 # Reset terminal. |
| 366 | 32 # See 'tput' docs. |
| 367 | 33 |
| 368 | 34 echo |
| 369 | 35 |
| 370 | 36 exit 0 |
| 371 | 37 |
| 372 | 38 # Exercise: |
| 373 | 39 # -------- |
| 374 | 40 # 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 #!/bin/bash |
| 406 | 2 # array-ops.sh: More fun with arrays. |
| 407 | 3 |
| 408 | 4 |
| 409 | 5 array=( zero one two three four five ) |
| 410 | 6 # Element 0 1 2 3 4 5 |
| 411 | 7 |
| 412 | 8 echo ${array[0]} # zero |
| 413 | 9 echo ${array:0} # zero |
| 414 | 10 # Parameter expansion of first element, |
| 415 | 11 #+ starting at position # 0 (1st character). |
| 416 | 12 echo ${array:1} # ero |
| 417 | 13 # Parameter expansion of first element, |
| 418 | 14 #+ starting at position # 1 (2nd character). |
| 419 | 15 |
| 420 | 16 echo "--------------" |
| 421 | 17 |
| 422 | 18 echo ${#array[0]} # 4 |
| 423 | 19 # Length of first element of array. |
| 424 | 20 echo ${#array} # 4 |
| 425 | 21 # Length of first element of array. |
| 426 | 22 # (Alternate notation) |
| 427 | 23 |
| 428 | 24 echo ${#array[1]} # 3 |
| 429 | 25 # Length of second element of array. |
| 430 | 26 # Arrays in Bash have zero-based indexing. |
| 431 | 27 |
| 432 | 28 echo ${#array[*]} # 6 |
| 433 | 29 # Number of elements in array. |
| 434 | 30 echo ${#array[@]} # 6 |
| 435 | 31 # Number of elements in array. |
| 436 | 32 |
| 437 | 33 echo "--------------" |
| 438 | 34 |
| 439 | 35 array2=( [0]="first element" [1]="second element" [3]="fourth element" ) |
| 440 | 36 # ^ ^ ^ ^ ^ ^ ^ ^ ^ |
| 441 | 37 # Quoting permits embedding whitespace within individual array elements. |
| 442 | 38 |
| 443 | 39 echo ${array2[0]} # first element |
| 444 | 40 echo ${array2[1]} # second element |
| 445 | 41 echo ${array2[2]} # |
| 446 | 42 # Skipped in initialization, and therefore null. |
| 447 | 43 echo ${array2[3]} # fourth element |
| 448 | 44 echo ${#array2[0]} # 13 (length of first element) |
| 449 | 45 echo ${#array2[*]} # 3 (number of elements in array) |
| 450 | 46 |
| 451 | 47 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 #!/bin/bash |
| 485 | 2 # array-strops.sh: String operations on arrays. |
| 486 | 3 |
| 487 | 4 # Script by Michael Zick. |
| 488 | 5 # Used in ABS Guide with permission. |
| 489 | 6 # Fixups: 05 May 08, 04 Aug 08. |
| 490 | 7 |
| 491 | 8 # In general, any string operation using the ${name ... } notation |
| 492 | 9 #+ can be applied to all string elements in an array, |
| 493 | 10 #+ with the ${name[@] ... } or ${name[*] ...} notation. |
| 494 | 11 |
| 495 | 12 |
| 496 | 13 arrayZ=( one two three four five five ) |
| 497 | 14 |
| 498 | 15 echo |
| 499 | 16 |
| 500 | 17 # Trailing Substring Extraction |
| 501 | 18 echo ${arrayZ[@]:0} # one two three four five five |
| 502 | 19 # ^ All elements. |
| 503 | 20 |
| 504 | 21 echo ${arrayZ[@]:1} # two three four five five |
| 505 | 22 # ^ All elements following element[0]. |
| 506 | 23 |
| 507 | 24 echo ${arrayZ[@]:1:2} # two three |
| 508 | 25 # ^ Only the two elements after element[0]. |
| 509 | 26 |
| 510 | 27 echo "---------" |
| 511 | 28 |
| 512 | 29 |
| 513 | 30 # Substring Removal |
| 514 | 31 |
| 515 | 32 # Removes shortest match from front of string(s). |
| 516 | 33 |
| 517 | 34 echo ${arrayZ[@]#f*r} # one two three five five |
| 518 | 35 # ^ # Applied to all elements of the array. |
| 519 | 36 # Matches "four" and removes it. |
| 520 | 37 |
| 521 | 38 # Longest match from front of string(s) |
| 522 | 39 echo ${arrayZ[@]##t*e} # one two four five five |
| 523 | 40 # ^^ # Applied to all elements of the array. |
| 524 | 41 # Matches "three" and removes it. |
| 525 | 42 |
| 526 | 43 # Shortest match from back of string(s) |
| 527 | 44 echo ${arrayZ[@]%h*e} # one two t four five five |
| 528 | 45 # ^ # Applied to all elements of the array. |
| 529 | 46 # Matches "hree" and removes it. |
| 530 | 47 |
| 531 | 48 # Longest match from back of string(s) |
| 532 | 49 echo ${arrayZ[@]%%t*e} # one two four five five |
| 533 | 50 # ^^ # Applied to all elements of the array. |
| 534 | 51 # Matches "three" and removes it. |
| 535 | 52 |
| 536 | 53 echo "----------------------" |
| 537 | 54 |
| 538 | 55 |
| 539 | 56 # Substring Replacement |
| 540 | 57 |
| 541 | 58 # Replace first occurrence of substring with replacement. |
| 542 | 59 echo ${arrayZ[@]/fiv/XYZ} # one two three four XYZe XYZe |
| 543 | 60 # ^ # Applied to all elements of the array. |
| 544 | 61 |
| 545 | 62 # Replace all occurrences of substring. |
| 546 | 63 echo ${arrayZ[@]//iv/YY} # one two three four fYYe fYYe |
| 547 | 64 # Applied to all elements of the array. |
| 548 | 65 |
| 549 | 66 # Delete all occurrences of substring. |
| 550 | 67 # Not specifing a replacement defaults to 'delete' ... |
| 551 | 68 echo ${arrayZ[@]//fi/} # one two three four ve ve |
| 552 | 69 # ^^ # Applied to all elements of the array. |
| 553 | 70 |
| 554 | 71 # Replace front-end occurrences of substring. |
| 555 | 72 echo ${arrayZ[@]/#fi/XY} # one two three four XYve XYve |
| 556 | 73 # ^ # Applied to all elements of the array. |
| 557 | 74 |
| 558 | 75 # Replace back-end occurrences of substring. |
| 559 | 76 echo ${arrayZ[@]/%ve/ZZ} # one two three four fiZZ fiZZ |
| 560 | 77 # ^ # Applied to all elements of the array. |
| 561 | 78 |
| 562 | 79 echo ${arrayZ[@]/%o/XX} # one twXX three four five five |
| 563 | 80 # ^ # Why? |
| 564 | 81 |
| 565 | 82 echo "-----------------------------" |
| 566 | 83 |
| 567 | 84 |
| 568 | 85 replacement() { |
| 569 | 86 echo -n "!!!" |
| 570 | 87 } |
| 571 | 88 |
| 572 | 89 echo ${arrayZ[@]/%e/$(replacement)} |
| 573 | 90 # ^ ^^^^^^^^^^^^^^ |
| 574 | 91 # on!!! two thre!!! four fiv!!! fiv!!! |
| 575 | 92 # The stdout of replacement() is the replacement string. |
| 576 | 93 # Q.E.D: The replacement action is, in effect, an 'assignment.' |
| 577 | 94 |
| 578 | 95 echo "------------------------------------" |
| 579 | 96 |
| 580 | 97 # Accessing the "for-each": |
| 581 | 98 echo ${arrayZ[@]//*/$(replacement optional_arguments)} |
| 582 | 99 # ^^ ^^^^^^^^^^^^^ |
| 583 | 100 # !!! !!! !!! !!! !!! !!! |
| 584 | 101 |
| 585 | 102 # Now, if Bash would only pass the matched string |
| 586 | 103 #+ to the function being called . . . |
| 587 | 104 |
| 588 | 105 echo |
| 589 | 106 |
| 590 | 107 exit 0 |
| 591 | 108 |
| 592 | 109 # Before reaching for a Big Hammer -- Perl, Python, or all the rest -- |
| 593 | 110 # recall: |
| 594 | 111 # $( ... ) is command substitution. |
| 595 | 112 # A function runs as a sub-process. |
| 596 | 113 # A function writes its output (if echo-ed) to stdout. |
| 597 | 114 # Assignment, in conjunction with "echo" and command substitution, |
| 598 | 115 #+ can read a function's stdout. |
| 599 | 116 # The name[@] notation specifies (the equivalent of) a "for-each" |
| 600 | 117 #+ operation. |
| 601 | 118 # 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 #!/bin/bash |
| 630 | 2 # script-array.sh: Loads this script into an array. |
| 631 | 3 # Inspired by an e-mail from Chris Martin (thanks!). |
| 632 | 4 |
| 633 | 5 script_contents=( $(cat "$0") ) # Stores contents of this script ($0) |
| 634 | 6 #+ in an array. |
| 635 | 7 |
| 636 | 8 for element in $(seq 0 $((${#script_contents[@]} - 1))) |
| 637 | 9 do # ${#script_contents[@]} |
| 638 | 10 #+ gives number of elements in the array. |
| 639 | 11 # |
| 640 | 12 # Question: |
| 641 | 13 # Why is seq 0 necessary? |
| 642 | 14 # Try changing it to seq 1. |
| 643 | 15 echo -n "${script_contents[$element]}" |
| 644 | 16 # List each field of this script on a single line. |
| 645 | 17 # echo -n "${script_contents[element]}" also works because of ${ ... }. |
| 646 | 18 echo -n " -- " # Use " -- " as a field separator. |
| 647 | 19 done |
| 648 | 20 |
| 649 | 21 echo |
| 650 | 22 |
| 651 | 23 exit 0 |
| 652 | 24 |
| 653 | 25 # Exercise: |
| 654 | 26 # -------- |
| 655 | 27 # Modify this script so it lists itself |
| 656 | 28 #+ in its original format, |
| 657 | 29 #+ 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 #!/bin/bash |
| 698 | 2 |
| 699 | 3 declare -a colors |
| 700 | 4 # All subsequent commands in this script will treat |
| 701 | 5 #+ the variable "colors" as an array. |
| 702 | 6 |
| 703 | 7 echo "Enter your favorite colors (separated from each other by a space)." |
| 704 | 8 |
| 705 | 9 read -a colors # Enter at least 3 colors to demonstrate features below. |
| 706 | 10 # Special option to 'read' command, |
| 707 | 11 #+ allowing assignment of elements in an array. |
| 708 | 12 |
| 709 | 13 echo |
| 710 | 14 |
| 711 | 15 element_count=${#colors[@]} |
| 712 | 16 # Special syntax to extract number of elements in array. |
| 713 | 17 # element_count=${#colors[*]} works also. |
| 714 | 18 # |
| 715 | 19 # The "@" variable allows word splitting within quotes |
| 716 | 20 #+ (extracts variables separated by whitespace). |
| 717 | 21 # |
| 718 | 22 # This corresponds to the behavior of "$@" and "$*" |
| 719 | 23 #+ in positional parameters. |
| 720 | 24 |
| 721 | 25 index=0 |
| 722 | 26 |
| 723 | 27 while [ "$index" -lt "$element_count" ] |
| 724 | 28 do # List all the elements in the array. |
| 725 | 29 echo ${colors[$index]} |
| 726 | 30 # ${colors[index]} also works because it's within ${ ... } brackets. |
| 727 | 31 let "index = $index + 1" |
| 728 | 32 # Or: |
| 729 | 33 # ((index++)) |
| 730 | 34 done |
| 731 | 35 # Each array element listed on a separate line. |
| 732 | 36 # If this is not desired, use echo -n "${colors[$index]} " |
| 733 | 37 # |
| 734 | 38 # Doing it with a "for" loop instead: |
| 735 | 39 # for i in "${colors[@]}" |
| 736 | 40 # do |
| 737 | 41 # echo "$i" |
| 738 | 42 # done |
| 739 | 43 # (Thanks, S.C.) |
| 740 | 44 |
| 741 | 45 echo |
| 742 | 46 |
| 743 | 47 # Again, list all the elements in the array, but using a more elegant method. |
| 744 | 48 echo ${colors[@]} # echo ${colors[*]} also works. |
| 745 | 49 |
| 746 | 50 echo |
| 747 | 51 |
| 748 | 52 # The "unset" command deletes elements of an array, or entire array. |
| 749 | 53 unset colors[1] # Remove 2nd element of array. |
| 750 | 54 # Same effect as colors[1]= |
| 751 | 55 echo ${colors[@]} # List array again, missing 2nd element. |
| 752 | 56 |
| 753 | 57 unset colors # Delete entire array. |
| 754 | 58 # unset colors[*] and |
| 755 | 59 #+ unset colors[@] also work. |
| 756 | 60 echo; echo -n "Colors gone." |
| 757 | 61 echo ${colors[@]} # List array again, now empty. |
| 758 | 62 |
| 759 | 63 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 #!/bin/bash |
| 827 | 2 # empty-array.sh |
| 828 | 3 |
| 829 | 4 # Thanks to Stephane Chazelas for the original example, |
| 830 | 5 #+ and to Michael Zick and Omair Eshkenazi, for extending it. |
| 831 | 6 # And to Nathan Coulter for clarifications and corrections. |
| 832 | 7 |
| 833 | 8 |
| 834 | 9 # An empty array is not the same as an array with empty elements. |
| 835 | 10 |
| 836 | 11 array0=( first second third ) |
| 837 | 12 array1=( '' ) # "array1" consists of one empty element. |
| 838 | 13 array2=( ) # No elements . . . "array2" is empty. |
| 839 | 14 array3=( ) # What about this array? |
| 840 | 15 |
| 841 | 16 |
| 842 | 17 echo |
| 843 | 18 ListArray() |
| 844 | 19 { |
| 845 | 20 echo |
| 846 | 21 echo "Elements in array0: ${array0[@]}" |
| 847 | 22 echo "Elements in array1: ${array1[@]}" |
| 848 | 23 echo "Elements in array2: ${array2[@]}" |
| 849 | 24 echo "Elements in array3: ${array3[@]}" |
| 850 | 25 echo |
| 851 | 26 echo "Length of first element in array0 = ${#array0}" |
| 852 | 27 echo "Length of first element in array1 = ${#array1}" |
| 853 | 28 echo "Length of first element in array2 = ${#array2}" |
| 854 | 29 echo "Length of first element in array3 = ${#array3}" |
| 855 | 30 echo |
| 856 | 31 echo "Number of elements in array0 = ${#array0[*]}" # 3 |
| 857 | 32 echo "Number of elements in array1 = ${#array1[*]}" # 1 (Surprise!) |
| 858 | 33 echo "Number of elements in array2 = ${#array2[*]}" # 0 |
| 859 | 34 echo "Number of elements in array3 = ${#array3[*]}" # 0 |
| 860 | 35 } |
| 861 | 36 |
| 862 | 37 # =================================================================== |
| 863 | 38 |
| 864 | 39 ListArray |
| 865 | 40 |
| 866 | 41 # Try extending those arrays. |
| 867 | 42 |
| 868 | 43 # Adding an element to an array. |
| 869 | 44 array0=( "${array0[@]}" "new1" ) |
| 870 | 45 array1=( "${array1[@]}" "new1" ) |
| 871 | 46 array2=( "${array2[@]}" "new1" ) |
| 872 | 47 array3=( "${array3[@]}" "new1" ) |
| 873 | 48 |
| 874 | 49 ListArray |
| 875 | 50 |
| 876 | 51 # or |
| 877 | 52 array0[${#array0[*]}]="new2" |
| 878 | 53 array1[${#array1[*]}]="new2" |
| 879 | 54 array2[${#array2[*]}]="new2" |
| 880 | 55 array3[${#array3[*]}]="new2" |
| 881 | 56 |
| 882 | 57 ListArray |
| 883 | 58 |
| 884 | 59 # When extended as above, arrays are 'stacks' ... |
| 885 | 60 # Above is the 'push' ... |
| 886 | 61 # The stack 'height' is: |
| 887 | 62 height=${#array2[@]} |
| 888 | 63 echo |
| 889 | 64 echo "Stack height for array2 = $height" |
| 890 | 65 |
| 891 | 66 # The 'pop' is: |
| 892 | 67 unset array2[${#array2[@]}-1] # Arrays are zero-based, |
| 893 | 68 height=${#array2[@]} #+ which means first element has index 0. |
| 894 | 69 echo |
| 895 | 70 echo "POP" |
| 896 | 71 echo "New stack height for array2 = $height" |
| 897 | 72 |
| 898 | 73 ListArray |
| 899 | 74 |
| 900 | 75 # List only 2nd and 3rd elements of array0. |
| 901 | 76 from=1 # Zero-based numbering. |
| 902 | 77 to=2 |
| 903 | 78 array3=( ${array0[@]:1:2} ) |
| 904 | 79 echo |
| 905 | 80 echo "Elements in array3: ${array3[@]}" |
| 906 | 81 |
| 907 | 82 # Works like a string (array of characters). |
| 908 | 83 # Try some other "string" forms. |
| 909 | 84 |
| 910 | 85 # Replacement: |
| 911 | 86 array4=( ${array0[@]/second/2nd} ) |
| 912 | 87 echo |
| 913 | 88 echo "Elements in array4: ${array4[@]}" |
| 914 | 89 |
| 915 | 90 # Replace all matching wildcarded string. |
| 916 | 91 array5=( ${array0[@]//new?/old} ) |
| 917 | 92 echo |
| 918 | 93 echo "Elements in array5: ${array5[@]}" |
| 919 | 94 |
| 920 | 95 # Just when you are getting the feel for this . . . |
| 921 | 96 array6=( ${array0[@]#*new} ) |
| 922 | 97 echo # This one might surprise you. |
| 923 | 98 echo "Elements in array6: ${array6[@]}" |
| 924 | 99 |
| 925 | 100 array7=( ${array0[@]#new1} ) |
| 926 | 101 echo # After array6 this should not be a surprise. |
| 927 | 102 echo "Elements in array7: ${array7[@]}" |
| 928 | 103 |
| 929 | 104 # Which looks a lot like . . . |
| 930 | 105 array8=( ${array0[@]/new1/} ) |
| 931 | 106 echo |
| 932 | 107 echo "Elements in array8: ${array8[@]}" |
| 933 | 108 |
| 934 | 109 # So what can one say about this? |
| 935 | 110 |
| 936 | 111 # The string operations are performed on |
| 937 | 112 #+ each of the elements in var[@] in succession. |
| 938 | 113 # Therefore : Bash supports string vector operations. |
| 939 | 114 # If the result is a zero length string, |
| 940 | 115 #+ that element disappears in the resulting assignment. |
| 941 | 116 # However, if the expansion is in quotes, the null elements remain. |
| 942 | 117 |
| 943 | 118 # Michael Zick: Question, are those strings hard or soft quotes? |
| 944 | 119 # Nathan Coulter: There is no such thing as "soft quotes." |
| 945 | 120 #! What's really happening is that |
| 946 | 121 #!+ the pattern matching happens after |
| 947 | 122 #!+ all the other expansions of [word] |
| 948 | 123 #!+ in cases like ${parameter#word}. |
| 949 | 124 |
| 950 | 125 |
| 951 | 126 zap='new*' |
| 952 | 127 array9=( ${array0[@]/$zap/} ) |
| 953 | 128 echo |
| 954 | 129 echo "Number of elements in array9: ${#array9[@]}" |
| 955 | 130 array9=( "${array0[@]/$zap/}" ) |
| 956 | 131 echo "Elements in array9: ${array9[@]}" |
| 957 | 132 # This time the null elements remain. |
| 958 | 133 echo "Number of elements in array9: ${#array9[@]}" |
| 959 | 134 |
| 960 | 135 |
| 961 | 136 # Just when you thought you were still in Kansas . . . |
| 962 | 137 array10=( ${array0[@]#$zap} ) |
| 963 | 138 echo |
| 964 | 139 echo "Elements in array10: ${array10[@]}" |
| 965 | 140 # But, the asterisk in zap won't be interpreted if quoted. |
| 966 | 141 array10=( ${array0[@]#"$zap"} ) |
| 967 | 142 echo |
| 968 | 143 echo "Elements in array10: ${array10[@]}" |
| 969 | 144 # Well, maybe we _are_ still in Kansas . . . |
| 970 | 145 # (Revisions to above code block by Nathan Coulter.) |
| 971 | 146 |
| 972 | 147 |
| 973 | 148 # Compare array7 with array10. |
| 974 | 149 # Compare array8 with array9. |
| 975 | 150 |
| 976 | 151 # Reiterating: No such thing as soft quotes! |
| 977 | 152 # Nathan Coulter explains: |
| 978 | 153 # Pattern matching of 'word' in ${parameter#word} is done after |
| 979 | 154 #+ parameter expansion and *before* quote removal. |
| 980 | 155 # In the normal case, pattern matching is done *after* quote removal. |
| 981 | 156 |
| 982 | 157 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 # Copying an array. |
| 1016 | 2 array2=( "${array1[@]}" ) |
| 1017 | 3 # or |
| 1018 | 4 array2="${array1[@]}" |
| 1019 | 5 # |
| 1020 | 6 # However, this fails with "sparse" arrays, |
| 1021 | 7 #+ arrays with holes (missing elements) in them, |
| 1022 | 8 #+ as Jochen DeSmet points out. |
| 1023 | 9 # ------------------------------------------ |
| 1024 | 10 array1[0]=0 |
| 1025 | 11 # array1[1] not assigned |
| 1026 | 12 array1[2]=2 |
| 1027 | 13 array2=( "${array1[@]}" ) # Copy it? |
| 1028 | 14 |
| 1029 | 15 echo ${array2[0]} # 0 |
| 1030 | 16 echo ${array2[2]} # (null), should be 2 |
| 1031 | 17 # ------------------------------------------ |
| 1032 | 18 |
| 1033 | 19 |
| 1034 | 20 |
| 1035 | 21 # Adding an element to an array. |
| 1036 | 22 array=( "${array[@]}" "new element" ) |
| 1037 | 23 # or |
| 1038 | 24 array[${#array[*]}]="new element" |
| 1039 | 25 |
| 1040 | 26 # 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 #!/bin/bash |
| 1090 | 2 |
| 1091 | 3 filename=sample_file |
| 1092 | 4 |
| 1093 | 5 # cat sample_file |
| 1094 | 6 # |
| 1095 | 7 # 1 a b c |
| 1096 | 8 # 2 d e fg |
| 1097 | 9 |
| 1098 | 10 |
| 1099 | 11 declare -a array1 |
| 1100 | 12 |
| 1101 | 13 array1=( `cat "$filename"`) # Loads contents |
| 1102 | 14 # List file to stdout #+ of $filename into array1. |
| 1103 | 15 # |
| 1104 | 16 # array1=( `cat "$filename" | tr '\n' ' '`) |
| 1105 | 17 # change linefeeds in file to spaces. |
| 1106 | 18 # Not necessary because Bash does word splitting, |
| 1107 | 19 #+ changing linefeeds to spaces. |
| 1108 | 20 |
| 1109 | 21 echo ${array1[@]} # List the array. |
| 1110 | 22 # 1 a b c 2 d e fg |
| 1111 | 23 # |
| 1112 | 24 # Each whitespace-separated "word" in the file |
| 1113 | 25 #+ has been assigned to an element of the array. |
| 1114 | 26 |
| 1115 | 27 element_count=${#array1[*]} |
| 1116 | 28 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 #! /bin/bash |
| 1151 | 2 # array-assign.bash |
| 1152 | 3 |
| 1153 | 4 # Array operations are Bash-specific, |
| 1154 | 5 #+ hence the ".bash" in the script name. |
| 1155 | 6 |
| 1156 | 7 # Copyright (c) Michael S. Zick, 2003, All rights reserved. |
| 1157 | 8 # License: Unrestricted reuse in any form, for any purpose. |
| 1158 | 9 # Version: $ID$ |
| 1159 | 10 # |
| 1160 | 11 # Clarification and additional comments by William Park. |
| 1161 | 12 |
| 1162 | 13 # Based on an example provided by Stephane Chazelas |
| 1163 | 14 #+ which appeared in an earlier version of the |
| 1164 | 15 #+ Advanced Bash Scripting Guide. |
| 1165 | 16 |
| 1166 | 17 # Output format of the 'times' command: |
| 1167 | 18 # User CPU <space> System CPU |
| 1168 | 19 # User CPU of dead children <space> System CPU of dead children |
| 1169 | 20 |
| 1170 | 21 # Bash has two versions of assigning all elements of an array |
| 1171 | 22 #+ to a new array variable. |
| 1172 | 23 # Both drop 'null reference' elements |
| 1173 | 24 #+ in Bash versions 2.04 and later. |
| 1174 | 25 # An additional array assignment that maintains the relationship of |
| 1175 | 26 #+ [subscript]=value for arrays may be added to newer versions. |
| 1176 | 27 |
| 1177 | 28 # Constructs a large array using an internal command, |
| 1178 | 29 #+ but anything creating an array of several thousand elements |
| 1179 | 30 #+ will do just fine. |
| 1180 | 31 |
| 1181 | 32 declare -a bigOne=( /dev/* ) # All the files in /dev . . . |
| 1182 | 33 echo |
| 1183 | 34 echo 'Conditions: Unquoted, default IFS, All-Elements-Of' |
| 1184 | 35 echo "Number of elements in array is ${#bigOne[@]}" |
| 1185 | 36 |
| 1186 | 37 # set -vx |
| 1187 | 38 |
| 1188 | 39 |
| 1189 | 40 |
| 1190 | 41 echo |
| 1191 | 42 echo '- - testing: =( ${array[@]} ) - -' |
| 1192 | 43 times |
| 1193 | 44 declare -a bigTwo=( ${bigOne[@]} ) |
| 1194 | 45 # Note parens: ^ ^ |
| 1195 | 46 times |
| 1196 | 47 |
| 1197 | 48 |
| 1198 | 49 echo |
| 1199 | 50 echo '- - testing: =${array[@]} - -' |
| 1200 | 51 times |
| 1201 | 52 declare -a bigThree=${bigOne[@]} |
| 1202 | 53 # No parentheses this time. |
| 1203 | 54 times |
| 1204 | 55 |
| 1205 | 56 # Comparing the numbers shows that the second form, pointed out |
| 1206 | 57 #+ by Stephane Chazelas, is faster. |
| 1207 | 58 # |
| 1208 | 59 # As William Park explains: |
| 1209 | 60 #+ The bigTwo array assigned element by element (because of parentheses), |
| 1210 | 61 #+ whereas bigThree assigned as a single string. |
| 1211 | 62 # So, in essence, you have: |
| 1212 | 63 # bigTwo=( [0]="..." [1]="..." [2]="..." ... ) |
| 1213 | 64 # bigThree=( [0]="... ... ..." ) |
| 1214 | 65 # |
| 1215 | 66 # Verify this by: echo ${bigTwo[0]} |
| 1216 | 67 # echo ${bigThree[0]} |
| 1217 | 68 |
| 1218 | 69 |
| 1219 | 70 # I will continue to use the first form in my example descriptions |
| 1220 | 71 #+ because I think it is a better illustration of what is happening. |
| 1221 | 72 |
| 1222 | 73 # The reusable portions of my examples will actual contain |
| 1223 | 74 #+ the second form where appropriate because of the speedup. |
| 1224 | 75 |
| 1225 | 76 # MSZ: Sorry about that earlier oversight folks. |
| 1226 | 77 |
| 1227 | 78 |
| 1228 | 79 # Note: |
| 1229 | 80 # ---- |
| 1230 | 81 # The "declare -a" statements in lines 32 and 44 |
| 1231 | 82 #+ are not strictly necessary, since it is implicit |
| 1232 | 83 #+ in the Array=( ... ) assignment form. |
| 1233 | 84 # However, eliminating these declarations slows down |
| 1234 | 85 #+ the execution of the following sections of the script. |
| 1235 | 86 # Try it, and see. |
| 1236 | 87 |
| 1237 | 88 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 #! /bin/bash |
| 1294 | 2 # CopyArray.sh |
| 1295 | 3 # |
| 1296 | 4 # This script written by Michael Zick. |
| 1297 | 5 # Used here with permission. |
| 1298 | 6 |
| 1299 | 7 # How-To "Pass by Name & Return by Name" |
| 1300 | 8 #+ or "Building your own assignment statement". |
| 1301 | 9 |
| 1302 | 10 |
| 1303 | 11 CpArray_Mac() { |
| 1304 | 12 |
| 1305 | 13 # Assignment Command Statement Builder |
| 1306 | 14 |
| 1307 | 15 echo -n 'eval ' |
| 1308 | 16 echo -n "$2" # Destination name |
| 1309 | 17 echo -n '=( ${' |
| 1310 | 18 echo -n "$1" # Source name |
| 1311 | 19 echo -n '[@]} )' |
| 1312 | 20 |
| 1313 | 21 # That could all be a single command. |
| 1314 | 22 # Matter of style only. |
| 1315 | 23 } |
| 1316 | 24 |
| 1317 | 25 declare -f CopyArray # Function "Pointer" |
| 1318 | 26 CopyArray=CpArray_Mac # Statement Builder |
| 1319 | 27 |
| 1320 | 28 Hype() |
| 1321 | 29 { |
| 1322 | 30 |
| 1323 | 31 # Hype the array named $1. |
| 1324 | 32 # (Splice it together with array containing "Really Rocks".) |
| 1325 | 33 # Return in array named $2. |
| 1326 | 34 |
| 1327 | 35 local -a TMP |
| 1328 | 36 local -a hype=( Really Rocks ) |
| 1329 | 37 |
| 1330 | 38 $($CopyArray $1 TMP) |
| 1331 | 39 TMP=( ${TMP[@]} ${hype[@]} ) |
| 1332 | 40 $($CopyArray TMP $2) |
| 1333 | 41 } |
| 1334 | 42 |
| 1335 | 43 declare -a before=( Advanced Bash Scripting ) |
| 1336 | 44 declare -a after |
| 1337 | 45 |
| 1338 | 46 echo "Array Before = ${before[@]}" |
| 1339 | 47 |
| 1340 | 48 Hype before after |
| 1341 | 49 |
| 1342 | 50 echo "Array After = ${after[@]}" |
| 1343 | 51 |
| 1344 | 52 # Too much hype? |
| 1345 | 53 |
| 1346 | 54 echo "What ${after[@]:3:2}?" |
| 1347 | 55 |
| 1348 | 56 declare -a modest=( ${after[@]:2:1} ${after[@]:3:2} ) |
| 1349 | 57 # ---- substring extraction ---- |
| 1350 | 58 |
| 1351 | 59 echo "Array Modest = ${modest[@]}" |
| 1352 | 60 |
| 1353 | 61 # What happened to 'before' ? |
| 1354 | 62 |
| 1355 | 63 echo "Array Before = ${before[@]}" |
| 1356 | 64 |
| 1357 | 65 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 #! /bin/bash |
| 1380 | 2 # array-append.bash |
| 1381 | 3 |
| 1382 | 4 # Copyright (c) Michael S. Zick, 2003, All rights reserved. |
| 1383 | 5 # License: Unrestricted reuse in any form, for any purpose. |
| 1384 | 6 # Version: $ID$ |
| 1385 | 7 # |
| 1386 | 8 # Slightly modified in formatting by M.C. |
| 1387 | 9 |
| 1388 | 10 |
| 1389 | 11 # Array operations are Bash-specific. |
| 1390 | 12 # Legacy UNIX /bin/sh lacks equivalents. |
| 1391 | 13 |
| 1392 | 14 |
| 1393 | 15 # Pipe the output of this script to 'more' |
| 1394 | 16 #+ so it doesn't scroll off the terminal. |
| 1395 | 17 # Or, redirect output to a file. |
| 1396 | 18 |
| 1397 | 19 |
| 1398 | 20 declare -a array1=( zero1 one1 two1 ) |
| 1399 | 21 # Subscript packed. |
| 1400 | 22 declare -a array2=( [0]=zero2 [2]=two2 [3]=three2 ) |
| 1401 | 23 # Subscript sparse -- [1] is not defined. |
| 1402 | 24 |
| 1403 | 25 echo |
| 1404 | 26 echo '- Confirm that the array is really subscript sparse. -' |
| 1405 | 27 echo "Number of elements: 4" # Hard-coded for illustration. |
| 1406 | 28 for (( i = 0 ; i < 4 ; i++ )) |
| 1407 | 29 do |
| 1408 | 30 echo "Element [$i]: ${array2[$i]}" |
| 1409 | 31 done |
| 1410 | 32 # See also the more general code example in basics-reviewed.bash. |
| 1411 | 33 |
| 1412 | 34 |
| 1413 | 35 declare -a dest |
| 1414 | 36 |
| 1415 | 37 # Combine (append) two arrays into a third array. |
| 1416 | 38 echo |
| 1417 | 39 echo 'Conditions: Unquoted, default IFS, All-Elements-Of operator' |
| 1418 | 40 echo '- Undefined elements not present, subscripts not maintained. -' |
| 1419 | 41 # # The undefined elements do not exist; they are not being dropped. |
| 1420 | 42 |
| 1421 | 43 dest=( ${array1[@]} ${array2[@]} ) |
| 1422 | 44 # dest=${array1[@]}${array2[@]} # Strange results, possibly a bug. |
| 1423 | 45 |
| 1424 | 46 # Now, list the result. |
| 1425 | 47 echo |
| 1426 | 48 echo '- - Testing Array Append - -' |
| 1427 | 49 cnt=${#dest[@]} |
| 1428 | 50 |
| 1429 | 51 echo "Number of elements: $cnt" |
| 1430 | 52 for (( i = 0 ; i < cnt ; i++ )) |
| 1431 | 53 do |
| 1432 | 54 echo "Element [$i]: ${dest[$i]}" |
| 1433 | 55 done |
| 1434 | 56 |
| 1435 | 57 # Assign an array to a single array element (twice). |
| 1436 | 58 dest[0]=${array1[@]} |
| 1437 | 59 dest[1]=${array2[@]} |
| 1438 | 60 |
| 1439 | 61 # List the result. |
| 1440 | 62 echo |
| 1441 | 63 echo '- - Testing modified array - -' |
| 1442 | 64 cnt=${#dest[@]} |
| 1443 | 65 |
| 1444 | 66 echo "Number of elements: $cnt" |
| 1445 | 67 for (( i = 0 ; i < cnt ; i++ )) |
| 1446 | 68 do |
| 1447 | 69 echo "Element [$i]: ${dest[$i]}" |
| 1448 | 70 done |
| 1449 | 71 |
| 1450 | 72 # Examine the modified second element. |
| 1451 | 73 echo |
| 1452 | 74 echo '- - Reassign and list second element - -' |
| 1453 | 75 |
| 1454 | 76 declare -a subArray=${dest[1]} |
| 1455 | 77 cnt=${#subArray[@]} |
| 1456 | 78 |
| 1457 | 79 echo "Number of elements: $cnt" |
| 1458 | 80 for (( i = 0 ; i < cnt ; i++ )) |
| 1459 | 81 do |
| 1460 | 82 echo "Element [$i]: ${subArray[$i]}" |
| 1461 | 83 done |
| 1462 | 84 |
| 1463 | 85 # The assignment of an entire array to a single element |
| 1464 | 86 #+ of another array using the '=${ ... }' array assignment |
| 1465 | 87 #+ has converted the array being assigned into a string, |
| 1466 | 88 #+ with the elements separated by a space (the first character of IFS). |
| 1467 | 89 |
| 1468 | 90 # If the original elements didn't contain whitespace . . . |
| 1469 | 91 # If the original array isn't subscript sparse . . . |
| 1470 | 92 # Then we could get the original array structure back again. |
| 1471 | 93 |
| 1472 | 94 # Restore from the modified second element. |
| 1473 | 95 echo |
| 1474 | 96 echo '- - Listing restored element - -' |
| 1475 | 97 |
| 1476 | 98 declare -a subArray=( ${dest[1]} ) |
| 1477 | 99 cnt=${#subArray[@]} |
| 1478 | 100 |
| 1479 | 101 echo "Number of elements: $cnt" |
| 1480 | 102 for (( i = 0 ; i < cnt ; i++ )) |
| 1481 | 103 do |
| 1482 | 104 echo "Element [$i]: ${subArray[$i]}" |
| 1483 | 105 done |
| 1484 | 106 echo '- - Do not depend on this behavior. - -' |
| 1485 | 107 echo '- - This behavior is subject to change - -' |
| 1486 | 108 echo '- - in versions of Bash newer than version 2.05b - -' |
| 1487 | 109 |
| 1488 | 110 # MSZ: Sorry about any earlier confusion folks. |
| 1489 | 111 |
| 1490 | 112 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 #!/bin/bash |
| 1524 | 2 # bubble.sh: Bubble sort, of sorts. |
| 1525 | 3 |
| 1526 | 4 # Recall the algorithm for a bubble sort. In this particular version... |
| 1527 | 5 |
| 1528 | 6 # With each successive pass through the array to be sorted, |
| 1529 | 7 #+ compare two adjacent elements, and swap them if out of order. |
| 1530 | 8 # At the end of the first pass, the "heaviest" element has sunk to bottom. |
| 1531 | 9 # At the end of the second pass, the next "heaviest" one has sunk next to bottom. |
| 1532 | 10 # And so forth. |
| 1533 | 11 # This means that each successive pass needs to traverse less of the array. |
| 1534 | 12 # You will therefore notice a speeding up in the printing of the later passes. |
| 1535 | 13 |
| 1536 | 14 |
| 1537 | 15 exchange() |
| 1538 | 16 { |
| 1539 | 17 # Swaps two members of the array. |
| 1540 | 18 local temp=${Countries[$1]} # Temporary storage |
| 1541 | 19 #+ for element getting swapped out. |
| 1542 | 20 Countries[$1]=${Countries[$2]} |
| 1543 | 21 Countries[$2]=$temp |
| 1544 | 22 |
| 1545 | 23 return |
| 1546 | 24 } |
| 1547 | 25 |
| 1548 | 26 declare -a Countries # Declare array, |
| 1549 | 27 #+ optional here since it's initialized below. |
| 1550 | 28 |
| 1551 | 29 # Is it permissable to split an array variable over multiple lines |
| 1552 | 30 #+ using an escape (\)? |
| 1553 | 31 # Yes. |
| 1554 | 32 |
| 1555 | 33 Countries=(Netherlands Ukraine Zaire Turkey Russia Yemen Syria \ |
| 1556 | 34 Brazil Argentina Nicaragua Japan Mexico Venezuela Greece England \ |
| 1557 | 35 Israel Peru Canada Oman Denmark Wales France Kenya \ |
| 1558 | 36 Xanadu Qatar Liechtenstein Hungary) |
| 1559 | 37 |
| 1560 | 38 # "Xanadu" is the mythical place where, according to Coleridge, |
| 1561 | 39 #+ Kubla Khan did a pleasure dome decree. |
| 1562 | 40 |
| 1563 | 41 |
| 1564 | 42 clear # Clear the screen to start with. |
| 1565 | 43 |
| 1566 | 44 echo "0: ${Countries[*]}" # List entire array at pass 0. |
| 1567 | 45 |
| 1568 | 46 number_of_elements=${#Countries[@]} |
| 1569 | 47 let "comparisons = $number_of_elements - 1" |
| 1570 | 48 |
| 1571 | 49 count=1 # Pass number. |
| 1572 | 50 |
| 1573 | 51 while [ "$comparisons" -gt 0 ] # Beginning of outer loop |
| 1574 | 52 do |
| 1575 | 53 |
| 1576 | 54 index=0 # Reset index to start of array after each pass. |
| 1577 | 55 |
| 1578 | 56 while [ "$index" -lt "$comparisons" ] # Beginning of inner loop |
| 1579 | 57 do |
| 1580 | 58 if [ ${Countries[$index]} \> ${Countries[`expr $index + 1`]} ] |
| 1581 | 59 # If out of order... |
| 1582 | 60 # Recalling that \> is ASCII comparison operator |
| 1583 | 61 #+ within single brackets. |
| 1584 | 62 |
| 1585 | 63 # if [[ ${Countries[$index]} > ${Countries[`expr $index + 1`]} ]] |
| 1586 | 64 #+ also works. |
| 1587 | 65 then |
| 1588 | 66 exchange $index `expr $index + 1` # Swap. |
| 1589 | 67 fi |
| 1590 | 68 let "index += 1" # Or, index+=1 on Bash, ver. 3.1 or newer. |
| 1591 | 69 done # End of inner loop |
| 1592 | 70 |
| 1593 | 71 # ---------------------------------------------------------------------- |
| 1594 | 72 # Paulo Marcel Coelho Aragao suggests for-loops as a simpler altenative. |
| 1595 | 73 # |
| 1596 | 74 # for (( last = $number_of_elements - 1 ; last > 0 ; last-- )) |
| 1597 | 75 ## Fix by C.Y. Hunt ^ (Thanks!) |
| 1598 | 76 # do |
| 1599 | 77 # for (( i = 0 ; i < last ; i++ )) |
| 1600 | 78 # do |
| 1601 | 79 # [[ "${Countries[$i]}" > "${Countries[$((i+1))]}" ]] \ |
| 1602 | 80 # && exchange $i $((i+1)) |
| 1603 | 81 # done |
| 1604 | 82 # done |
| 1605 | 83 # ---------------------------------------------------------------------- |
| 1606 | 84 |
| 1607 | 85 |
| 1608 | 86 let "comparisons -= 1" # Since "heaviest" element bubbles to bottom, |
| 1609 | 87 #+ we need do one less comparison each pass. |
| 1610 | 88 |
| 1611 | 89 echo |
| 1612 | 90 echo "$count: ${Countries[@]}" # Print resultant array at end of each pass. |
| 1613 | 91 echo |
| 1614 | 92 let "count += 1" # Increment pass count. |
| 1615 | 93 |
| 1616 | 94 done # End of outer loop |
| 1617 | 95 # All done. |
| 1618 | 96 |
| 1619 | 97 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 #!/bin/bash |
| 1643 | 2 # "Nested" array. |
| 1644 | 3 |
| 1645 | 4 # Michael Zick provided this example, |
| 1646 | 5 #+ with corrections and clarifications by William Park. |
| 1647 | 6 |
| 1648 | 7 AnArray=( $(ls --inode --ignore-backups --almost-all \ |
| 1649 | 8 --directory --full-time --color=none --time=status \ |
| 1650 | 9 --sort=time -l ${PWD} ) ) # Commands and options. |
| 1651 | 10 |
| 1652 | 11 # Spaces are significant . . . and don't quote anything in the above. |
| 1653 | 12 |
| 1654 | 13 SubArray=( ${AnArray[@]:11:1} ${AnArray[@]:6:5} ) |
| 1655 | 14 # This array has six elements: |
| 1656 | 15 #+ SubArray=( [0]=${AnArray[11]} [1]=${AnArray[6]} [2]=${AnArray[7]} |
| 1657 | 16 # [3]=${AnArray[8]} [4]=${AnArray[9]} [5]=${AnArray[10]} ) |
| 1658 | 17 # |
| 1659 | 18 # Arrays in Bash are (circularly) linked lists |
| 1660 | 19 #+ of type string (char *). |
| 1661 | 20 # So, this isn't actually a nested array, |
| 1662 | 21 #+ but it's functionally similar. |
| 1663 | 22 |
| 1664 | 23 echo "Current directory and date of last status change:" |
| 1665 | 24 echo "${SubArray[@]}" |
| 1666 | 25 |
| 1667 | 26 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 #!/bin/bash |
| 1703 | 2 # embedded-arrays.sh |
| 1704 | 3 # Embedded arrays and indirect references. |
| 1705 | 4 |
| 1706 | 5 # This script by Dennis Leeuw. |
| 1707 | 6 # Used with permission. |
| 1708 | 7 # Modified by document author. |
| 1709 | 8 |
| 1710 | 9 |
| 1711 | 10 ARRAY1=( |
| 1712 | 11 VAR1_1=value11 |
| 1713 | 12 VAR1_2=value12 |
| 1714 | 13 VAR1_3=value13 |
| 1715 | 14 ) |
| 1716 | 15 |
| 1717 | 16 ARRAY2=( |
| 1718 | 17 VARIABLE="test" |
| 1719 | 18 STRING="VAR1=value1 VAR2=value2 VAR3=value3" |
| 1720 | 19 ARRAY21=${ARRAY1[*]} |
| 1721 | 20 ) # Embed ARRAY1 within this second array. |
| 1722 | 21 |
| 1723 | 22 function print () { |
| 1724 | 23 OLD_IFS="$IFS" |
| 1725 | 24 IFS=$'\n' # To print each array element |
| 1726 | 25 #+ on a separate line. |
| 1727 | 26 TEST1="ARRAY2[*]" |
| 1728 | 27 local ${!TEST1} # See what happens if you delete this line. |
| 1729 | 28 # Indirect reference. |
| 1730 | 29 # This makes the components of $TEST1 |
| 1731 | 30 #+ accessible to this function. |
| 1732 | 31 |
| 1733 | 32 |
| 1734 | 33 # Let's see what we've got so far. |
| 1735 | 34 echo |
| 1736 | 35 echo "\$TEST1 = $TEST1" # Just the name of the variable. |
| 1737 | 36 echo; echo |
| 1738 | 37 echo "{\$TEST1} = ${!TEST1}" # Contents of the variable. |
| 1739 | 38 # That's what an indirect |
| 1740 | 39 #+ reference does. |
| 1741 | 40 echo |
| 1742 | 41 echo "-------------------------------------------"; echo |
| 1743 | 42 echo |
| 1744 | 43 |
| 1745 | 44 |
| 1746 | 45 # Print variable |
| 1747 | 46 echo "Variable VARIABLE: $VARIABLE" |
| 1748 | 47 |
| 1749 | 48 # Print a string element |
| 1750 | 49 IFS="$OLD_IFS" |
| 1751 | 50 TEST2="STRING[*]" |
| 1752 | 51 local ${!TEST2} # Indirect reference (as above). |
| 1753 | 52 echo "String element VAR2: $VAR2 from STRING" |
| 1754 | 53 |
| 1755 | 54 # Print an array element |
| 1756 | 55 TEST2="ARRAY21[*]" |
| 1757 | 56 local ${!TEST2} # Indirect reference (as above). |
| 1758 | 57 echo "Array element VAR1_1: $VAR1_1 from ARRAY21" |
| 1759 | 58 } |
| 1760 | 59 |
| 1761 | 60 print |
| 1762 | 61 echo |
| 1763 | 62 |
| 1764 | 63 exit 0 |
| 1765 | 64 |
| 1766 | 65 # As the author of the script notes, |
| 1767 | 66 #+ "you can easily expand it to create named-hashes in bash." |
| 1768 | 67 # (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 #!/bin/bash |
| 1807 | 2 # sieve.sh (ex68.sh) |
| 1808 | 3 |
| 1809 | 4 # Sieve of Eratosthenes |
| 1810 | 5 # Ancient algorithm for finding prime numbers. |
| 1811 | 6 |
| 1812 | 7 # This runs a couple of orders of magnitude slower |
| 1813 | 8 #+ than the equivalent program written in C. |
| 1814 | 9 |
| 1815 | 10 LOWER_LIMIT=1 # Starting with 1. |
| 1816 | 11 UPPER_LIMIT=1000 # Up to 1000. |
| 1817 | 12 # (You may set this higher . . . if you have time on your hands.) |
| 1818 | 13 |
| 1819 | 14 PRIME=1 |
| 1820 | 15 NON_PRIME=0 |
| 1821 | 16 |
| 1822 | 17 let SPLIT=UPPER_LIMIT/2 |
| 1823 | 18 # Optimization: |
| 1824 | 19 # Need to test numbers only halfway to upper limit. Why? |
| 1825 | 20 |
| 1826 | 21 |
| 1827 | 22 declare -a Primes |
| 1828 | 23 # Primes[] is an array. |
| 1829 | 24 |
| 1830 | 25 |
| 1831 | 26 initialize () |
| 1832 | 27 { |
| 1833 | 28 # Initialize the array. |
| 1834 | 29 |
| 1835 | 30 i=$LOWER_LIMIT |
| 1836 | 31 until [ "$i" -gt "$UPPER_LIMIT" ] |
| 1837 | 32 do |
| 1838 | 33 Primes[i]=$PRIME |
| 1839 | 34 let "i += 1" |
| 1840 | 35 done |
| 1841 | 36 # Assume all array members guilty (prime) |
| 1842 | 37 #+ until proven innocent. |
| 1843 | 38 } |
| 1844 | 39 |
| 1845 | 40 print_primes () |
| 1846 | 41 { |
| 1847 | 42 # Print out the members of the Primes[] array tagged as prime. |
| 1848 | 43 |
| 1849 | 44 i=$LOWER_LIMIT |
| 1850 | 45 |
| 1851 | 46 until [ "$i" -gt "$UPPER_LIMIT" ] |
| 1852 | 47 do |
| 1853 | 48 |
| 1854 | 49 if [ "${Primes[i]}" -eq "$PRIME" ] |
| 1855 | 50 then |
| 1856 | 51 printf "%8d" $i |
| 1857 | 52 # 8 spaces per number gives nice, even columns. |
| 1858 | 53 fi |
| 1859 | 54 |
| 1860 | 55 let "i += 1" |
| 1861 | 56 |
| 1862 | 57 done |
| 1863 | 58 |
| 1864 | 59 } |
| 1865 | 60 |
| 1866 | 61 sift () # Sift out the non-primes. |
| 1867 | 62 { |
| 1868 | 63 |
| 1869 | 64 let i=$LOWER_LIMIT+1 |
| 1870 | 65 # Let's start with 2. |
| 1871 | 66 |
| 1872 | 67 until [ "$i" -gt "$UPPER_LIMIT" ] |
| 1873 | 68 do |
| 1874 | 69 |
| 1875 | 70 if [ "${Primes[i]}" -eq "$PRIME" ] |
| 1876 | 71 # Don't bother sieving numbers already sieved (tagged as non-prime). |
| 1877 | 72 then |
| 1878 | 73 |
| 1879 | 74 t=$i |
| 1880 | 75 |
| 1881 | 76 while [ "$t" -le "$UPPER_LIMIT" ] |
| 1882 | 77 do |
| 1883 | 78 let "t += $i " |
| 1884 | 79 Primes[t]=$NON_PRIME |
| 1885 | 80 # Tag as non-prime all multiples. |
| 1886 | 81 done |
| 1887 | 82 |
| 1888 | 83 fi |
| 1889 | 84 |
| 1890 | 85 let "i += 1" |
| 1891 | 86 done |
| 1892 | 87 |
| 1893 | 88 |
| 1894 | 89 } |
| 1895 | 90 |
| 1896 | 91 |
| 1897 | 92 # ============================================== |
| 1898 | 93 # main () |
| 1899 | 94 # Invoke the functions sequentially. |
| 1900 | 95 initialize |
| 1901 | 96 sift |
| 1902 | 97 print_primes |
| 1903 | 98 # This is what they call structured programming. |
| 1904 | 99 # ============================================== |
| 1905 | 100 |
| 1906 | 101 echo |
| 1907 | 102 |
| 1908 | 103 exit 0 |
| 1909 | 104 |
| 1910 | 105 |
| 1911 | 106 |
| 1912 | 107 # -------------------------------------------------------- # |
| 1913 | 108 # Code below line will not execute, because of 'exit.' |
| 1914 | 109 |
| 1915 | 110 # This improved version of the Sieve, by Stephane Chazelas, |
| 1916 | 111 #+ executes somewhat faster. |
| 1917 | 112 |
| 1918 | 113 # Must invoke with command-line argument (limit of primes). |
| 1919 | 114 |
| 1920 | 115 UPPER_LIMIT=$1 # From command-line. |
| 1921 | 116 let SPLIT=UPPER_LIMIT/2 # Halfway to max number. |
| 1922 | 117 |
| 1923 | 118 Primes=( '' $(seq $UPPER_LIMIT) ) |
| 1924 | 119 |
| 1925 | 120 i=1 |
| 1926 | 121 until (( ( i += 1 ) > SPLIT )) # Need check only halfway. |
| 1927 | 122 do |
| 1928 | 123 if [[ -n ${Primes[i]} ]] |
| 1929 | 124 then |
| 1930 | 125 t=$i |
| 1931 | 126 until (( ( t += i ) > UPPER_LIMIT )) |
| 1932 | 127 do |
| 1933 | 128 Primes[t]= |
| 1934 | 129 done |
| 1935 | 130 fi |
| 1936 | 131 done |
| 1937 | 132 echo ${Primes[*]} |
| 1938 | 133 |
| 1939 | 134 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 #!/bin/bash |
| 1962 | 2 # Optimized Sieve of Eratosthenes |
| 1963 | 3 # Script by Jared Martin, with very minor changes by ABS Guide author. |
| 1964 | 4 # Used in ABS Guide with permission (thanks!). |
| 1965 | 5 |
| 1966 | 6 # Based on script in Advanced Bash Scripting Guide. |
| 1967 | 7 # http://tldp.org/LDP/abs/html/arrays.html#PRIMES0 (ex68.sh). |
| 1968 | 8 |
| 1969 | 9 # http://www.cs.hmc.edu/~oneill/papers/Sieve-JFP.pdf (reference) |
| 1970 | 10 # Check results against http://primes.utm.edu/lists/small/1000.txt |
| 1971 | 11 |
| 1972 | 12 # Necessary but not sufficient would be, e.g., |
| 1973 | 13 # (($(sieve 7919 | wc -w) == 1000)) && echo "7919 is the 1000th prime" |
| 1974 | 14 |
| 1975 | 15 UPPER_LIMIT=${1:?"Need an upper limit of primes to search."} |
| 1976 | 16 |
| 1977 | 17 Primes=( '' $(seq ${UPPER_LIMIT}) ) |
| 1978 | 18 |
| 1979 | 19 typeset -i i t |
| 1980 | 20 Primes[i=1]='' # 1 is not a prime. |
| 1981 | 21 until (( ( i += 1 ) > (${UPPER_LIMIT}/i) )) # Need check only ith-way. |
| 1982 | 22 do # Why? |
| 1983 | 23 if ((${Primes[t=i*(i-1), i]})) |
| 1984 | 24 # Obscure, but instructive, use of arithmetic expansion in subscript. |
| 1985 | 25 then |
| 1986 | 26 until (( ( t += i ) > ${UPPER_LIMIT} )) |
| 1987 | 27 do Primes[t]=; done |
| 1988 | 28 fi |
| 1989 | 29 done |
| 1990 | 30 |
| 1991 | 31 # echo ${Primes[*]} |
| 1992 | 32 echo # Change to original script for pretty-printing (80-col. display). |
| 1993 | 33 printf "%8d" ${Primes[*]} |
| 1994 | 34 echo; echo |
| 1995 | 35 |
| 1996 | 36 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 #!/bin/bash |
| 2039 | 2 # stack.sh: push-down stack simulation |
| 2040 | 3 |
| 2041 | 4 # Similar to the CPU stack, a push-down stack stores data items |
| 2042 | 5 #+ sequentially, but releases them in reverse order, last-in first-out. |
| 2043 | 6 |
| 2044 | 7 |
| 2045 | 8 BP=100 # Base Pointer of stack array. |
| 2046 | 9 # Begin at element 100. |
| 2047 | 10 |
| 2048 | 11 SP=$BP # Stack Pointer. |
| 2049 | 12 # Initialize it to "base" (bottom) of stack. |
| 2050 | 13 |
| 2051 | 14 Data= # Contents of stack location. |
| 2052 | 15 # Must use global variable, |
| 2053 | 16 #+ because of limitation on function return range. |
| 2054 | 17 |
| 2055 | 18 |
| 2056 | 19 # 100 Base pointer <-- Base Pointer |
| 2057 | 20 # 99 First data item |
| 2058 | 21 # 98 Second data item |
| 2059 | 22 # ... More data |
| 2060 | 23 # Last data item <-- Stack pointer |
| 2061 | 24 |
| 2062 | 25 |
| 2063 | 26 declare -a stack |
| 2064 | 27 |
| 2065 | 28 |
| 2066 | 29 push() # Push item on stack. |
| 2067 | 30 { |
| 2068 | 31 if [ -z "$1" ] # Nothing to push? |
| 2069 | 32 then |
| 2070 | 33 return |
| 2071 | 34 fi |
| 2072 | 35 |
| 2073 | 36 let "SP -= 1" # Bump stack pointer. |
| 2074 | 37 stack[$SP]=$1 |
| 2075 | 38 |
| 2076 | 39 return |
| 2077 | 40 } |
| 2078 | 41 |
| 2079 | 42 pop() # Pop item off stack. |
| 2080 | 43 { |
| 2081 | 44 Data= # Empty out data item. |
| 2082 | 45 |
| 2083 | 46 if [ "$SP" -eq "$BP" ] # Stack empty? |
| 2084 | 47 then |
| 2085 | 48 return |
| 2086 | 49 fi # This also keeps SP from getting past 100, |
| 2087 | 50 #+ i.e., prevents a runaway stack. |
| 2088 | 51 |
| 2089 | 52 Data=${stack[$SP]} |
| 2090 | 53 let "SP += 1" # Bump stack pointer. |
| 2091 | 54 return |
| 2092 | 55 } |
| 2093 | 56 |
| 2094 | 57 status_report() # Find out what's happening. |
| 2095 | 58 { |
| 2096 | 59 echo "-------------------------------------" |
| 2097 | 60 echo "REPORT" |
| 2098 | 61 echo "Stack Pointer = $SP" |
| 2099 | 62 echo "Just popped \""$Data"\" off the stack." |
| 2100 | 63 echo "-------------------------------------" |
| 2101 | 64 echo |
| 2102 | 65 } |
| 2103 | 66 |
| 2104 | 67 |
| 2105 | 68 # ======================================================= |
| 2106 | 69 # Now, for some fun. |
| 2107 | 70 |
| 2108 | 71 echo |
| 2109 | 72 |
| 2110 | 73 # See if you can pop anything off empty stack. |
| 2111 | 74 pop |
| 2112 | 75 status_report |
| 2113 | 76 |
| 2114 | 77 echo |
| 2115 | 78 |
| 2116 | 79 push garbage |
| 2117 | 80 pop |
| 2118 | 81 status_report # Garbage in, garbage out. |
| 2119 | 82 |
| 2120 | 83 value1=23; push $value1 |
| 2121 | 84 value2=skidoo; push $value2 |
| 2122 | 85 value3=LAST; push $value3 |
| 2123 | 86 |
| 2124 | 87 pop # LAST |
| 2125 | 88 status_report |
| 2126 | 89 pop # skidoo |
| 2127 | 90 status_report |
| 2128 | 91 pop # 23 |
| 2129 | 92 status_report # Last-in, first-out! |
| 2130 | 93 |
| 2131 | 94 # Notice how the stack pointer decrements with each push, |
| 2132 | 95 #+ and increments with each pop. |
| 2133 | 96 |
| 2134 | 97 echo |
| 2135 | 98 |
| 2136 | 99 exit 0 |
| 2137 | 100 |
| 2138 | 101 # ======================================================= |
| 2139 | 102 |
| 2140 | 103 |
| 2141 | 104 # Exercises: |
| 2142 | 105 # --------- |
| 2143 | 106 |
| 2144 | 107 # 1) Modify the "push()" function to permit pushing |
| 2145 | 108 # + multiple element on the stack with a single function call. |
| 2146 | 109 |
| 2147 | 110 # 2) Modify the "pop()" function to permit popping |
| 2148 | 111 # + multiple element from the stack with a single function call. |
| 2149 | 112 |
| 2150 | 113 # 3) Add error checking to the critical functions. |
| 2151 | 114 # That is, return an error code, depending on |
| 2152 | 115 # + successful or unsuccessful completion of the operation, |
| 2153 | 116 # + and take appropriate action. |
| 2154 | 117 |
| 2155 | 118 # 4) Using this script as a starting point, |
| 2156 | 119 # + 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 #!/bin/bash |
| 2195 | 2 |
| 2196 | 3 # Douglas Hofstadter's notorious "Q-series": |
| 2197 | 4 |
| 2198 | 5 # Q(1) = Q(2) = 1 |
| 2199 | 6 # Q(n) = Q(n - Q(n-1)) + Q(n - Q(n-2)), for n>2 |
| 2200 | 7 |
| 2201 | 8 # This is a "chaotic" integer series with strange |
| 2202 | 9 #+ and unpredictable behavior. |
| 2203 | 10 # The first 20 terms of the series are: |
| 2204 | 11 # 1 1 2 3 3 4 5 5 6 6 6 8 8 8 10 9 10 11 11 12 |
| 2205 | 12 |
| 2206 | 13 # See Hofstadter's book, _Goedel, Escher, Bach: An Eternal Golden Braid_, |
| 2207 | 14 #+ p. 137, ff. |
| 2208 | 15 |
| 2209 | 16 |
| 2210 | 17 LIMIT=100 # Number of terms to calculate. |
| 2211 | 18 LINEWIDTH=20 # Number of terms printed per line. |
| 2212 | 19 |
| 2213 | 20 Q[1]=1 # First two terms of series are 1. |
| 2214 | 21 Q[2]=1 |
| 2215 | 22 |
| 2216 | 23 echo |
| 2217 | 24 echo "Q-series [$LIMIT terms]:" |
| 2218 | 25 echo -n "${Q[1]} " # Output first two terms. |
| 2219 | 26 echo -n "${Q[2]} " |
| 2220 | 27 |
| 2221 | 28 for ((n=3; n <= $LIMIT; n++)) # C-like loop expression. |
| 2222 | 29 do # Q[n] = Q[n - Q[n-1]] + Q[n - Q[n-2]] for n>2 |
| 2223 | 30 # Need to break the expression into intermediate terms, |
| 2224 | 31 #+ since Bash doesn't handle complex array arithmetic very well. |
| 2225 | 32 |
| 2226 | 33 let "n1 = $n - 1" # n-1 |
| 2227 | 34 let "n2 = $n - 2" # n-2 |
| 2228 | 35 |
| 2229 | 36 t0=`expr $n - ${Q[n1]}` # n - Q[n-1] |
| 2230 | 37 t1=`expr $n - ${Q[n2]}` # n - Q[n-2] |
| 2231 | 38 |
| 2232 | 39 T0=${Q[t0]} # Q[n - Q[n-1]] |
| 2233 | 40 T1=${Q[t1]} # Q[n - Q[n-2]] |
| 2234 | 41 |
| 2235 | 42 Q[n]=`expr $T0 + $T1` # Q[n - Q[n-1]] + Q[n - Q[n-2]] |
| 2236 | 43 echo -n "${Q[n]} " |
| 2237 | 44 |
| 2238 | 45 if [ `expr $n % $LINEWIDTH` -eq 0 ] # Format output. |
| 2239 | 46 then # ^ modulo |
| 2240 | 47 echo # Break lines into neat chunks. |
| 2241 | 48 fi |
| 2242 | 49 |
| 2243 | 50 done |
| 2244 | 51 |
| 2245 | 52 echo |
| 2246 | 53 |
| 2247 | 54 exit 0 |
| 2248 | 55 |
| 2249 | 56 # This is an iterative implementation of the Q-series. |
| 2250 | 57 # The more intuitive recursive implementation is left as an exercise. |
| 2251 | 58 # Warning: calculating this series recursively takes a VERY long time |
| 2252 | 59 #+ 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 #!/bin/bash |
| 2285 | 2 # twodim.sh: Simulating a two-dimensional array. |
| 2286 | 3 |
| 2287 | 4 # A one-dimensional array consists of a single row. |
| 2288 | 5 # A two-dimensional array stores rows sequentially. |
| 2289 | 6 |
| 2290 | 7 Rows=5 |
| 2291 | 8 Columns=5 |
| 2292 | 9 # 5 X 5 Array. |
| 2293 | 10 |
| 2294 | 11 declare -a alpha # char alpha [Rows] [Columns]; |
| 2295 | 12 # Unnecessary declaration. Why? |
| 2296 | 13 |
| 2297 | 14 load_alpha () |
| 2298 | 15 { |
| 2299 | 16 local rc=0 |
| 2300 | 17 local index |
| 2301 | 18 |
| 2302 | 19 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 do # Use different symbols if you like. |
| 2304 | 21 local row=`expr $rc / $Columns` |
| 2305 | 22 local column=`expr $rc % $Rows` |
| 2306 | 23 let "index = $row * $Rows + $column" |
| 2307 | 24 alpha[$index]=$i |
| 2308 | 25 # alpha[$row][$column] |
| 2309 | 26 let "rc += 1" |
| 2310 | 27 done |
| 2311 | 28 |
| 2312 | 29 # Simpler would be |
| 2313 | 30 #+ 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 #+ but this somehow lacks the "flavor" of a two-dimensional array. |
| 2315 | 32 } |
| 2316 | 33 |
| 2317 | 34 print_alpha () |
| 2318 | 35 { |
| 2319 | 36 local row=0 |
| 2320 | 37 local index |
| 2321 | 38 |
| 2322 | 39 echo |
| 2323 | 40 |
| 2324 | 41 while [ "$row" -lt "$Rows" ] # Print out in "row major" order: |
| 2325 | 42 do #+ columns vary, |
| 2326 | 43 #+ while row (outer loop) remains the same. |
| 2327 | 44 local column=0 |
| 2328 | 45 |
| 2329 | 46 echo -n " " # Lines up "square" array with rotated one. |
| 2330 | 47 |
| 2331 | 48 while [ "$column" -lt "$Columns" ] |
| 2332 | 49 do |
| 2333 | 50 let "index = $row * $Rows + $column" |
| 2334 | 51 echo -n "${alpha[index]} " # alpha[$row][$column] |
| 2335 | 52 let "column += 1" |
| 2336 | 53 done |
| 2337 | 54 |
| 2338 | 55 let "row += 1" |
| 2339 | 56 echo |
| 2340 | 57 |
| 2341 | 58 done |
| 2342 | 59 |
| 2343 | 60 # The simpler equivalent is |
| 2344 | 61 # echo ${alpha[*]} | xargs -n $Columns |
| 2345 | 62 |
| 2346 | 63 echo |
| 2347 | 64 } |
| 2348 | 65 |
| 2349 | 66 filter () # Filter out negative array indices. |
| 2350 | 67 { |
| 2351 | 68 |
| 2352 | 69 echo -n " " # Provides the tilt. |
| 2353 | 70 # Explain how. |
| 2354 | 71 |
| 2355 | 72 if [[ "$1" -ge 0 && "$1" -lt "$Rows" && "$2" -ge 0 && "$2" -lt "$Columns" ]] |
| 2356 | 73 then |
| 2357 | 74 let "index = $1 * $Rows + $2" |
| 2358 | 75 # Now, print it rotated. |
| 2359 | 76 echo -n " ${alpha[index]}" |
| 2360 | 77 # alpha[$row][$column] |
| 2361 | 78 fi |
| 2362 | 79 |
| 2363 | 80 } |
| 2364 | 81 |
| 2365 | 82 |
| 2366 | 83 |
| 2367 | 84 |
| 2368 | 85 rotate () # Rotate the array 45 degrees -- |
| 2369 | 86 { #+ "balance" it on its lower lefthand corner. |
| 2370 | 87 local row |
| 2371 | 88 local column |
| 2372 | 89 |
| 2373 | 90 for (( row = Rows; row > -Rows; row-- )) |
| 2374 | 91 do # Step through the array backwards. Why? |
| 2375 | 92 |
| 2376 | 93 for (( column = 0; column < Columns; column++ )) |
| 2377 | 94 do |
| 2378 | 95 |
| 2379 | 96 if [ "$row" -ge 0 ] |
| 2380 | 97 then |
| 2381 | 98 let "t1 = $column - $row" |
| 2382 | 99 let "t2 = $column" |
| 2383 | 100 else |
| 2384 | 101 let "t1 = $column" |
| 2385 | 102 let "t2 = $column + $row" |
| 2386 | 103 fi |
| 2387 | 104 |
| 2388 | 105 filter $t1 $t2 # Filter out negative array indices. |
| 2389 | 106 # What happens if you don't do this? |
| 2390 | 107 done |
| 2391 | 108 |
| 2392 | 109 echo; echo |
| 2393 | 110 |
| 2394 | 111 done |
| 2395 | 112 |
| 2396 | 113 # Array rotation inspired by examples (pp. 143-146) in |
| 2397 | 114 #+ "Advanced C Programming on the IBM PC," by Herbert Mayer |
| 2398 | 115 #+ (see bibliography). |
| 2399 | 116 # This just goes to show that much of what can be done in C |
| 2400 | 117 #+ can also be done in shell scripting. |
| 2401 | 118 |
| 2402 | 119 } |
| 2403 | 120 |
| 2404 | 121 |
| 2405 | 122 #--------------- Now, let the show begin. ------------# |
| 2406 | 123 load_alpha # Load the array. |
| 2407 | 124 print_alpha # Print it out. |
| 2408 | 125 rotate # Rotate it 45 degrees counterclockwise. |
| 2409 | 126 #-----------------------------------------------------# |
| 2410 | 127 |
| 2411 | 128 exit 0 |
| 2412 | 129 |
| 2413 | 130 # This is a rather contrived, not to mention inelegant simulation. |
| 2414 | 131 |
| 2415 | 132 # Exercises: |
| 2416 | 133 # --------- |
| 2417 | 134 # 1) Rewrite the array loading and printing functions |
| 2418 | 135 # in a more intuitive and less kludgy fashion. |
| 2419 | 136 # |
| 2420 | 137 # 2) Figure out how the array rotation functions work. |
| 2421 | 138 # Hint: think about the implications of backwards-indexing an array. |
| 2422 | 139 # |
| 2423 | 140 # 3) Rewrite this script to handle a non-square array, |
| 2424 | 141 # such as a 6 X 4 one. |
| 2425 | 142 # 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 | > |