File: contributed-scripts.html

package info (click to toggle)
abs-guide 10-3
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 6,960 kB
  • sloc: sh: 14,129; makefile: 81
file content (14410 lines) | stat: -rw-r--r-- 512,510 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML
><HEAD
><TITLE
>Contributed Scripts</TITLE
><META
NAME="GENERATOR"
CONTENT="Modular DocBook HTML Stylesheet Version 1.76b+
"><LINK
REL="HOME"
TITLE="Advanced Bash-Scripting Guide"
HREF="index.html"><LINK
REL="PREVIOUS"
TITLE="Bibliography"
HREF="biblio.html"><LINK
REL="NEXT"
TITLE="Reference Cards"
HREF="refcards.html"><META
HTTP-EQUIV="Content-Style-Type"
CONTENT="text/css"><LINK
REL="stylesheet"
HREF="common/kde-common.css"
TYPE="text/css"><META
HTTP-EQUIV="Content-Type"
CONTENT="text/html; charset=iso-8859-1"><META
HTTP-EQUIV="Content-Language"
CONTENT="en"><LINK
REL="stylesheet"
HREF="common/kde-localised.css"
TYPE="text/css"
TITLE="KDE-English"><LINK
REL="stylesheet"
HREF="common/kde-default.css"
TYPE="text/css"
TITLE="KDE-Default"></HEAD
><BODY
CLASS="APPENDIX"
BGCOLOR="#FFFFFF"
TEXT="#000000"
LINK="#AA0000"
VLINK="#AA0055"
ALINK="#AA0000"
STYLE="font-family: sans-serif;"
><DIV
CLASS="NAVHEADER"
><TABLE
SUMMARY="Header navigation table"
WIDTH="100%"
BORDER="0"
CELLPADDING="0"
CELLSPACING="0"
><TR
><TH
COLSPAN="3"
ALIGN="center"
>Advanced Bash-Scripting Guide: An in-depth exploration of the art of shell scripting</TH
></TR
><TR
><TD
WIDTH="10%"
ALIGN="left"
VALIGN="bottom"
><A
HREF="biblio.html"
ACCESSKEY="P"
>Prev</A
></TD
><TD
WIDTH="80%"
ALIGN="center"
VALIGN="bottom"
></TD
><TD
WIDTH="10%"
ALIGN="right"
VALIGN="bottom"
><A
HREF="refcards.html"
ACCESSKEY="N"
>Next</A
></TD
></TR
></TABLE
><HR
ALIGN="LEFT"
WIDTH="100%"></DIV
><DIV
CLASS="APPENDIX"
><H1
><A
NAME="CONTRIBUTED-SCRIPTS"
></A
>Appendix A. Contributed Scripts</H1
><P
>These scripts, while not fitting into the text of this document, do
    illustrate some interesting shell programming techniques. Some are useful,
    too. Have fun analyzing and running them.</P
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="MAILFORMAT"
></A
><P
><B
>Example A-1. <I
CLASS="FIRSTTERM"
>mailformat</I
>: Formatting an e-mail
      message</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#!/bin/bash
   2&nbsp;# mail-format.sh (ver. 1.1): Format e-mail messages.
   3&nbsp;
   4&nbsp;# Gets rid of carets, tabs, and also folds excessively long lines.
   5&nbsp;
   6&nbsp;# =================================================================
   7&nbsp;#                 Standard Check for Script Argument(s)
   8&nbsp;ARGS=1
   9&nbsp;E_BADARGS=85
  10&nbsp;E_NOFILE=86
  11&nbsp;
  12&nbsp;if [ $# -ne $ARGS ]  # Correct number of arguments passed to script?
  13&nbsp;then
  14&nbsp;  echo "Usage: `basename $0` filename"
  15&nbsp;  exit $E_BADARGS
  16&nbsp;fi
  17&nbsp;
  18&nbsp;if [ -f "$1" ]       # Check if file exists.
  19&nbsp;then
  20&nbsp;    file_name=$1
  21&nbsp;else
  22&nbsp;    echo "File \"$1\" does not exist."
  23&nbsp;    exit $E_NOFILE
  24&nbsp;fi
  25&nbsp;# -----------------------------------------------------------------
  26&nbsp;
  27&nbsp;MAXWIDTH=70          # Width to fold excessively long lines to.
  28&nbsp;
  29&nbsp;# =================================
  30&nbsp;# A variable can hold a sed script.
  31&nbsp;# It's a useful technique.
  32&nbsp;sedscript='s/^&#62;//
  33&nbsp;s/^  *&#62;//
  34&nbsp;s/^  *//
  35&nbsp;s/		*//'
  36&nbsp;# =================================
  37&nbsp;
  38&nbsp;#  Delete carets and tabs at beginning of lines,
  39&nbsp;#+ then fold lines to $MAXWIDTH characters.
  40&nbsp;sed "$sedscript" $1 | fold -s --width=$MAXWIDTH
  41&nbsp;                        #  -s option to "fold"
  42&nbsp;                        #+ breaks lines at whitespace, if possible.
  43&nbsp;
  44&nbsp;
  45&nbsp;#  This script was inspired by an article in a well-known trade journal
  46&nbsp;#+ extolling a 164K MS Windows utility with similar functionality.
  47&nbsp;#
  48&nbsp;#  An nice set of text processing utilities and an efficient
  49&nbsp;#+ scripting language provide an alternative to the bloated executables
  50&nbsp;#+ of a clunky operating system.
  51&nbsp;
  52&nbsp;exit $?</PRE
></TD
></TR
></TABLE
><HR></DIV
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="RN"
></A
><P
><B
>Example A-2. <I
CLASS="FIRSTTERM"
>rn</I
>: A simple-minded file renaming
      utility</B
></P
><P
>This script is a modification of <A
HREF="textproc.html#LOWERCASE"
>Example 16-22</A
>.</P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#! /bin/bash
   2&nbsp;# rn.sh
   3&nbsp;
   4&nbsp;# Very simpleminded filename "rename" utility (based on "lowercase.sh").
   5&nbsp;#
   6&nbsp;#  The "ren" utility, by Vladimir Lanin (lanin@csd2.nyu.edu),
   7&nbsp;#+ does a much better job of this.
   8&nbsp;
   9&nbsp;
  10&nbsp;ARGS=2
  11&nbsp;E_BADARGS=85
  12&nbsp;ONE=1                     # For getting singular/plural right (see below).
  13&nbsp;
  14&nbsp;if [ $# -ne "$ARGS" ]
  15&nbsp;then
  16&nbsp;  echo "Usage: `basename $0` old-pattern new-pattern"
  17&nbsp;  # As in "rn gif jpg", which renames all gif files in working directory to jpg.
  18&nbsp;  exit $E_BADARGS
  19&nbsp;fi
  20&nbsp;
  21&nbsp;number=0                  # Keeps track of how many files actually renamed.
  22&nbsp;
  23&nbsp;
  24&nbsp;for filename in *$1*      #Traverse all matching files in directory.
  25&nbsp;do
  26&nbsp;   if [ -f "$filename" ]  # If finds match...
  27&nbsp;   then
  28&nbsp;     fname=`basename $filename`            # Strip off path.
  29&nbsp;     n=`echo $fname | sed -e "s/$1/$2/"`   # Substitute new for old in filename.
  30&nbsp;     mv $fname $n                          # Rename.
  31&nbsp;     let "number += 1"
  32&nbsp;   fi
  33&nbsp;done   
  34&nbsp;
  35&nbsp;if [ "$number" -eq "$ONE" ]                # For correct grammar.
  36&nbsp;then
  37&nbsp; echo "$number file renamed."
  38&nbsp;else 
  39&nbsp; echo "$number files renamed."
  40&nbsp;fi 
  41&nbsp;
  42&nbsp;exit $?
  43&nbsp;
  44&nbsp;
  45&nbsp;# Exercises:
  46&nbsp;# ---------
  47&nbsp;# What types of files will this not work on?
  48&nbsp;# How can this be fixed?</PRE
></TD
></TR
></TABLE
><HR></DIV
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="BLANKRENAME"
></A
><P
><B
>Example A-3. <I
CLASS="FIRSTTERM"
>blank-rename</I
>: Renames filenames containing
        blanks</B
></P
><P
>This is an even simpler-minded version of previous script.</P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#! /bin/bash
   2&nbsp;# blank-rename.sh
   3&nbsp;#
   4&nbsp;# Substitutes underscores for blanks in all the filenames in a directory.
   5&nbsp;
   6&nbsp;ONE=1                     # For getting singular/plural right (see below).
   7&nbsp;number=0                  # Keeps track of how many files actually renamed.
   8&nbsp;FOUND=0                   # Successful return value.
   9&nbsp;
  10&nbsp;for filename in *         #Traverse all files in directory.
  11&nbsp;do
  12&nbsp;     echo "$filename" | grep -q " "         #  Check whether filename
  13&nbsp;     if [ $? -eq $FOUND ]                   #+ contains space(s).
  14&nbsp;     then
  15&nbsp;       fname=$filename                      # Yes, this filename needs work.
  16&nbsp;       n=`echo $fname | sed -e "s/ /_/g"`   # Substitute underscore for blank.
  17&nbsp;       mv "$fname" "$n"                     # Do the actual renaming.
  18&nbsp;       let "number += 1"
  19&nbsp;     fi
  20&nbsp;done   
  21&nbsp;
  22&nbsp;if [ "$number" -eq "$ONE" ]                 # For correct grammar.
  23&nbsp;then
  24&nbsp; echo "$number file renamed."
  25&nbsp;else 
  26&nbsp; echo "$number files renamed."
  27&nbsp;fi 
  28&nbsp;
  29&nbsp;exit 0</PRE
></TD
></TR
></TABLE
><HR></DIV
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="ENCRYPTEDPW"
></A
><P
><B
>Example A-4. <I
CLASS="FIRSTTERM"
>encryptedpw</I
>: Uploading to an ftp site,
      using a locally encrypted password</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#!/bin/bash
   2&nbsp;
   3&nbsp;# Example "ex72.sh" modified to use encrypted password.
   4&nbsp;
   5&nbsp;#  Note that this is still rather insecure,
   6&nbsp;#+ since the decrypted password is sent in the clear.
   7&nbsp;#  Use something like "ssh" if this is a concern.
   8&nbsp;
   9&nbsp;E_BADARGS=85
  10&nbsp;
  11&nbsp;if [ -z "$1" ]
  12&nbsp;then
  13&nbsp;  echo "Usage: `basename $0` filename"
  14&nbsp;  exit $E_BADARGS
  15&nbsp;fi  
  16&nbsp;
  17&nbsp;Username=bozo           # Change to suit.
  18&nbsp;pword=/home/bozo/secret/password_encrypted.file
  19&nbsp;# File containing encrypted password.
  20&nbsp;
  21&nbsp;Filename=`basename $1`  # Strips pathname out of file name.
  22&nbsp;
  23&nbsp;Server="XXX"
  24&nbsp;Directory="YYY"         # Change above to actual server name &#38; directory.
  25&nbsp;
  26&nbsp;
  27&nbsp;Password=`cruft &#60;$pword`          # Decrypt password.
  28&nbsp;#  Uses the author's own "cruft" file encryption package,
  29&nbsp;#+ based on the classic "onetime pad" algorithm,
  30&nbsp;#+ and obtainable from:
  31&nbsp;#+ Primary-site:   ftp://ibiblio.org/pub/Linux/utils/file
  32&nbsp;#+                 cruft-0.2.tar.gz [16k]
  33&nbsp;
  34&nbsp;
  35&nbsp;ftp -n $Server &#60;&#60;End-Of-Session
  36&nbsp;user $Username $Password
  37&nbsp;binary
  38&nbsp;bell
  39&nbsp;cd $Directory
  40&nbsp;put $Filename
  41&nbsp;bye
  42&nbsp;End-Of-Session
  43&nbsp;# -n option to "ftp" disables auto-logon.
  44&nbsp;# Note that "bell" rings 'bell' after each file transfer.
  45&nbsp;
  46&nbsp;exit 0</PRE
></TD
></TR
></TABLE
><HR></DIV
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="COPYCD"
></A
><P
><B
>Example A-5. <I
CLASS="FIRSTTERM"
>copy-cd</I
>: Copying a data CD</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#!/bin/bash
   2&nbsp;# copy-cd.sh: copying a data CD
   3&nbsp;
   4&nbsp;CDROM=/dev/cdrom                           # CD ROM device
   5&nbsp;OF=/home/bozo/projects/cdimage.iso         # output file
   6&nbsp;#       /xxxx/xxxxxxxx/                      Change to suit your system.
   7&nbsp;BLOCKSIZE=2048
   8&nbsp;# SPEED=10                                 # If unspecified, uses max spd.
   9&nbsp;# DEVICE=/dev/cdrom                          older version.
  10&nbsp;DEVICE="1,0,0"
  11&nbsp;
  12&nbsp;echo; echo "Insert source CD, but do *not* mount it."
  13&nbsp;echo "Press ENTER when ready. "
  14&nbsp;read ready                                 # Wait for input, $ready not used.
  15&nbsp;
  16&nbsp;echo; echo "Copying the source CD to $OF."
  17&nbsp;echo "This may take a while. Please be patient."
  18&nbsp;
  19&nbsp;dd if=$CDROM of=$OF bs=$BLOCKSIZE          # Raw device copy.
  20&nbsp;
  21&nbsp;
  22&nbsp;echo; echo "Remove data CD."
  23&nbsp;echo "Insert blank CDR."
  24&nbsp;echo "Press ENTER when ready. "
  25&nbsp;read ready                                 # Wait for input, $ready not used.
  26&nbsp;
  27&nbsp;echo "Copying $OF to CDR."
  28&nbsp;
  29&nbsp;# cdrecord -v -isosize speed=$SPEED dev=$DEVICE $OF   # Old version.
  30&nbsp;wodim -v -isosize dev=$DEVICE $OF
  31&nbsp;# Uses Joerg Schilling's "cdrecord" package (see its docs).
  32&nbsp;# http://www.fokus.gmd.de/nthp/employees/schilling/cdrecord.html
  33&nbsp;# Newer Linux distros may use "wodim" rather than "cdrecord" ...
  34&nbsp;
  35&nbsp;
  36&nbsp;echo; echo "Done copying $OF to CDR on device $CDROM."
  37&nbsp;
  38&nbsp;echo "Do you want to erase the image file (y/n)? "  # Probably a huge file.
  39&nbsp;read answer
  40&nbsp;
  41&nbsp;case "$answer" in
  42&nbsp;[yY]) rm -f $OF
  43&nbsp;      echo "$OF erased."
  44&nbsp;      ;;
  45&nbsp;*)    echo "$OF not erased.";;
  46&nbsp;esac
  47&nbsp;
  48&nbsp;echo
  49&nbsp;
  50&nbsp;# Exercise:
  51&nbsp;# Change the above "case" statement to also accept "yes" and "Yes" as input.
  52&nbsp;
  53&nbsp;exit 0</PRE
></TD
></TR
></TABLE
><HR></DIV
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="COLLATZ"
></A
><P
><B
>Example A-6. Collatz series</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#!/bin/bash
   2&nbsp;# collatz.sh
   3&nbsp;
   4&nbsp;#  The notorious "hailstone" or Collatz series.
   5&nbsp;#  -------------------------------------------
   6&nbsp;#  1) Get the integer "seed" from the command-line.
   7&nbsp;#  2) NUMBER &#60;-- seed
   8&nbsp;#  3) Print NUMBER.
   9&nbsp;#  4)  If NUMBER is even, divide by 2, or
  10&nbsp;#  5)+ if odd, multiply by 3 and add 1.
  11&nbsp;#  6) NUMBER &#60;-- result 
  12&nbsp;#  7) Loop back to step 3 (for specified number of iterations).
  13&nbsp;#
  14&nbsp;#  The theory is that every such sequence,
  15&nbsp;#+ no matter how large the initial value,
  16&nbsp;#+ eventually settles down to repeating "4,2,1..." cycles,
  17&nbsp;#+ even after fluctuating through a wide range of values.
  18&nbsp;#
  19&nbsp;#  This is an instance of an "iterate,"
  20&nbsp;#+ an operation that feeds its output back into its input.
  21&nbsp;#  Sometimes the result is a "chaotic" series.
  22&nbsp;
  23&nbsp;
  24&nbsp;MAX_ITERATIONS=200
  25&nbsp;# For large seed numbers (&#62;32000), try increasing MAX_ITERATIONS.
  26&nbsp;
  27&nbsp;h=${1:-$$}                      #  Seed.
  28&nbsp;                                #  Use $PID as seed,
  29&nbsp;                                #+ if not specified as command-line arg.
  30&nbsp;
  31&nbsp;echo
  32&nbsp;echo "C($h) -*- $MAX_ITERATIONS Iterations"
  33&nbsp;echo
  34&nbsp;
  35&nbsp;for ((i=1; i&#60;=MAX_ITERATIONS; i++))
  36&nbsp;do
  37&nbsp;
  38&nbsp;# echo -n "$h	"
  39&nbsp;#            ^^^ 
  40&nbsp;#            tab
  41&nbsp;# printf does it better ...
  42&nbsp;COLWIDTH=%7d
  43&nbsp;printf $COLWIDTH $h
  44&nbsp;
  45&nbsp;  let "remainder = h % 2"
  46&nbsp;  if [ "$remainder" -eq 0 ]   # Even?
  47&nbsp;  then
  48&nbsp;    let "h /= 2"              # Divide by 2.
  49&nbsp;  else
  50&nbsp;    let "h = h*3 + 1"         # Multiply by 3 and add 1.
  51&nbsp;  fi
  52&nbsp;
  53&nbsp;
  54&nbsp;COLUMNS=10                    # Output 10 values per line.
  55&nbsp;let "line_break = i % $COLUMNS"
  56&nbsp;if [ "$line_break" -eq 0 ]
  57&nbsp;then
  58&nbsp;  echo
  59&nbsp;fi  
  60&nbsp;
  61&nbsp;done
  62&nbsp;
  63&nbsp;echo
  64&nbsp;
  65&nbsp;#  For more information on this strange mathematical function,
  66&nbsp;#+ see _Computers, Pattern, Chaos, and Beauty_, by Pickover, p. 185 ff.,
  67&nbsp;#+ as listed in the bibliography.
  68&nbsp;
  69&nbsp;exit 0</PRE
></TD
></TR
></TABLE
><HR></DIV
><P
><A
NAME="DAYSBETWEEN0"
></A
></P
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="DAYSBETWEEN"
></A
><P
><B
>Example A-7. <I
CLASS="FIRSTTERM"
>days-between</I
>: Days between two
        dates</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#!/bin/bash
   2&nbsp;# days-between.sh:    Number of days between two dates.
   3&nbsp;# Usage: ./days-between.sh [M]M/[D]D/YYYY [M]M/[D]D/YYYY
   4&nbsp;#
   5&nbsp;# Note: Script modified to account for changes in Bash, v. 2.05b +,
   6&nbsp;#+      that closed the loophole permitting large negative
   7&nbsp;#+      integer return values.
   8&nbsp;
   9&nbsp;ARGS=2                # Two command-line parameters expected.
  10&nbsp;E_PARAM_ERR=85        # Param error.
  11&nbsp;
  12&nbsp;REFYR=1600            # Reference year.
  13&nbsp;CENTURY=100
  14&nbsp;DIY=365
  15&nbsp;ADJ_DIY=367           # Adjusted for leap year + fraction.
  16&nbsp;MIY=12
  17&nbsp;DIM=31
  18&nbsp;LEAPCYCLE=4
  19&nbsp;
  20&nbsp;MAXRETVAL=255         #  Largest permissible
  21&nbsp;                      #+ positive return value from a function.
  22&nbsp;
  23&nbsp;diff=                 # Declare global variable for date difference.
  24&nbsp;value=                # Declare global variable for absolute value.
  25&nbsp;day=                  # Declare globals for day, month, year.
  26&nbsp;month=
  27&nbsp;year=
  28&nbsp;
  29&nbsp;
  30&nbsp;Param_Error ()        # Command-line parameters wrong.
  31&nbsp;{
  32&nbsp;  echo "Usage: `basename $0` [M]M/[D]D/YYYY [M]M/[D]D/YYYY"
  33&nbsp;  echo "       (date must be after 1/3/1600)"
  34&nbsp;  exit $E_PARAM_ERR
  35&nbsp;}  
  36&nbsp;
  37&nbsp;
  38&nbsp;Parse_Date ()                 # Parse date from command-line params.
  39&nbsp;{
  40&nbsp;  month=${1%%/**}
  41&nbsp;  dm=${1%/**}                 # Day and month.
  42&nbsp;  day=${dm#*/}
  43&nbsp;  let "year = `basename $1`"  # Not a filename, but works just the same.
  44&nbsp;}  
  45&nbsp;
  46&nbsp;
  47&nbsp;check_date ()                 # Checks for invalid date(s) passed.
  48&nbsp;{
  49&nbsp;  [ "$day" -gt "$DIM" ] || [ "$month" -gt "$MIY" ] ||
  50&nbsp;  [ "$year" -lt "$REFYR" ] &#38;&#38; Param_Error
  51&nbsp;  # Exit script on bad value(s).
  52&nbsp;  # Uses or-list / and-list.
  53&nbsp;  #
  54&nbsp;  # Exercise: Implement more rigorous date checking.
  55&nbsp;}
  56&nbsp;
  57&nbsp;
  58&nbsp;strip_leading_zero () #  Better to strip possible leading zero(s)
  59&nbsp;{                     #+ from day and/or month
  60&nbsp;  return ${1#0}       #+ since otherwise Bash will interpret them
  61&nbsp;}                     #+ as octal values (POSIX.2, sect 2.9.2.1).
  62&nbsp;
  63&nbsp;
  64&nbsp;day_index ()          # Gauss' Formula:
  65&nbsp;{                     # Days from March 1, 1600 to date passed as param.
  66&nbsp;                      #           ^^^^^^^^^^^^^
  67&nbsp;  day=$1
  68&nbsp;  month=$2
  69&nbsp;  year=$3
  70&nbsp;
  71&nbsp;  let "month = $month - 2"
  72&nbsp;  if [ "$month" -le 0 ]
  73&nbsp;  then
  74&nbsp;    let "month += 12"
  75&nbsp;    let "year -= 1"
  76&nbsp;  fi  
  77&nbsp;
  78&nbsp;  let "year -= $REFYR"
  79&nbsp;  let "indexyr = $year / $CENTURY"
  80&nbsp;
  81&nbsp;
  82&nbsp;  let "Days = $DIY*$year + $year/$LEAPCYCLE - $indexyr \
  83&nbsp;              + $indexyr/$LEAPCYCLE + $ADJ_DIY*$month/$MIY + $day - $DIM"
  84&nbsp;  #  For an in-depth explanation of this algorithm, see
  85&nbsp;  #+   http://weblogs.asp.net/pgreborio/archive/2005/01/06/347968.aspx
  86&nbsp;
  87&nbsp;
  88&nbsp;  echo $Days
  89&nbsp;
  90&nbsp;}  
  91&nbsp;
  92&nbsp;
  93&nbsp;calculate_difference ()            # Difference between two day indices.
  94&nbsp;{
  95&nbsp;  let "diff = $1 - $2"             # Global variable.
  96&nbsp;}  
  97&nbsp;
  98&nbsp;
  99&nbsp;abs ()                             #  Absolute value
 100&nbsp;{                                  #  Uses global "value" variable.
 101&nbsp;  if [ "$1" -lt 0 ]                #  If negative
 102&nbsp;  then                             #+ then
 103&nbsp;    let "value = 0 - $1"           #+ change sign,
 104&nbsp;  else                             #+ else
 105&nbsp;    let "value = $1"               #+ leave it alone.
 106&nbsp;  fi
 107&nbsp;}
 108&nbsp;
 109&nbsp;
 110&nbsp;
 111&nbsp;if [ $# -ne "$ARGS" ]              # Require two command-line params.
 112&nbsp;then
 113&nbsp;  Param_Error
 114&nbsp;fi  
 115&nbsp;
 116&nbsp;Parse_Date $1
 117&nbsp;check_date $day $month $year       #  See if valid date.
 118&nbsp;
 119&nbsp;strip_leading_zero $day            #  Remove any leading zeroes
 120&nbsp;day=$?                             #+ on day and/or month.
 121&nbsp;strip_leading_zero $month
 122&nbsp;month=$?
 123&nbsp;
 124&nbsp;let "date1 = `day_index $day $month $year`"
 125&nbsp;
 126&nbsp;
 127&nbsp;Parse_Date $2
 128&nbsp;check_date $day $month $year
 129&nbsp;
 130&nbsp;strip_leading_zero $day
 131&nbsp;day=$?
 132&nbsp;strip_leading_zero $month
 133&nbsp;month=$?
 134&nbsp;
 135&nbsp;date2=$(day_index $day $month $year) # Command substitution.
 136&nbsp;
 137&nbsp;
 138&nbsp;calculate_difference $date1 $date2
 139&nbsp;
 140&nbsp;abs $diff                            # Make sure it's positive.
 141&nbsp;diff=$value
 142&nbsp;
 143&nbsp;echo $diff
 144&nbsp;
 145&nbsp;exit 0
 146&nbsp;
 147&nbsp;#  Exercise:
 148&nbsp;#  --------
 149&nbsp;#  If given only one command-line parameter, have the script
 150&nbsp;#+ use today's date as the second.
 151&nbsp;
 152&nbsp;
 153&nbsp;#  Compare this script with
 154&nbsp;#+ the implementation of Gauss' Formula in a C program at
 155&nbsp;#+    http://buschencrew.hypermart.net/software/datedif</PRE
></TD
></TR
></TABLE
><HR></DIV
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="MAKEDICT"
></A
><P
><B
>Example A-8. Making a <I
CLASS="FIRSTTERM"
>dictionary</I
></B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#!/bin/bash
   2&nbsp;# makedict.sh  [make dictionary]
   3&nbsp;
   4&nbsp;# Modification of /usr/sbin/mkdict (/usr/sbin/cracklib-forman) script.
   5&nbsp;# Original script copyright 1993, by Alec Muffett.
   6&nbsp;#
   7&nbsp;#  This modified script included in this document in a manner
   8&nbsp;#+ consistent with the "LICENSE" document of the "Crack" package
   9&nbsp;#+ that the original script is a part of.
  10&nbsp;
  11&nbsp;#  This script processes text files to produce a sorted list
  12&nbsp;#+ of words found in the files.
  13&nbsp;#  This may be useful for compiling dictionaries
  14&nbsp;#+ and for other lexicographic purposes.
  15&nbsp;
  16&nbsp;
  17&nbsp;E_BADARGS=85
  18&nbsp;
  19&nbsp;if [ ! -r "$1" ]                    #  Need at least one
  20&nbsp;then                                #+ valid file argument.
  21&nbsp;  echo "Usage: $0 files-to-process"
  22&nbsp;  exit $E_BADARGS
  23&nbsp;fi  
  24&nbsp;
  25&nbsp;
  26&nbsp;# SORT="sort"                       #  No longer necessary to define
  27&nbsp;                                    #+ options to sort. Changed from
  28&nbsp;                                    #+ original script.
  29&nbsp;
  30&nbsp;cat $* |                            #  Dump specified files to stdout.
  31&nbsp;        tr A-Z a-z |                #  Convert to lowercase.
  32&nbsp;        tr ' ' '\012' |             #  New: change spaces to newlines.
  33&nbsp;#       tr -cd '\012[a-z][0-9]' |   #  Get rid of everything
  34&nbsp;                                    #+ non-alphanumeric (in orig. script).
  35&nbsp;        tr -c '\012a-z'  '\012' |   #  Rather than deleting non-alpha
  36&nbsp;                                    #+ chars, change them to newlines.
  37&nbsp;        sort |                      #  $SORT options unnecessary now.
  38&nbsp;        uniq |                      #  Remove duplicates.
  39&nbsp;        grep -v '^#' |              #  Delete lines starting with #.
  40&nbsp;        grep -v '^$'                #  Delete blank lines.
  41&nbsp;
  42&nbsp;exit $?</PRE
></TD
></TR
></TABLE
><HR></DIV
><P
><A
NAME="SOUNDEX0"
></A
></P
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="SOUNDEX"
></A
><P
><B
>Example A-9. Soundex conversion</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#!/bin/bash
   2&nbsp;# soundex.sh: Calculate "soundex" code for names
   3&nbsp;
   4&nbsp;# =======================================================
   5&nbsp;#        Soundex script
   6&nbsp;#              by
   7&nbsp;#         Mendel Cooper
   8&nbsp;#     thegrendel.abs@gmail.com
   9&nbsp;#     reldate: 23 January, 2002
  10&nbsp;#
  11&nbsp;#   Placed in the Public Domain.
  12&nbsp;#
  13&nbsp;# A slightly different version of this script appeared in
  14&nbsp;#+ Ed Schaefer's July, 2002 "Shell Corner" column
  15&nbsp;#+ in "Unix Review" on-line,
  16&nbsp;#+ http://www.unixreview.com/documents/uni1026336632258/
  17&nbsp;# =======================================================
  18&nbsp;
  19&nbsp;
  20&nbsp;ARGCOUNT=1                     # Need name as argument.
  21&nbsp;E_WRONGARGS=90
  22&nbsp;
  23&nbsp;if [ $# -ne "$ARGCOUNT" ]
  24&nbsp;then
  25&nbsp;  echo "Usage: `basename $0` name"
  26&nbsp;  exit $E_WRONGARGS
  27&nbsp;fi  
  28&nbsp;
  29&nbsp;
  30&nbsp;assign_value ()                #  Assigns numerical value
  31&nbsp;{                              #+ to letters of name.
  32&nbsp;
  33&nbsp;  val1=bfpv                    # 'b,f,p,v' = 1
  34&nbsp;  val2=cgjkqsxz                # 'c,g,j,k,q,s,x,z' = 2
  35&nbsp;  val3=dt                      #  etc.
  36&nbsp;  val4=l
  37&nbsp;  val5=mn
  38&nbsp;  val6=r
  39&nbsp;
  40&nbsp;# Exceptionally clever use of 'tr' follows.
  41&nbsp;# Try to figure out what is going on here.
  42&nbsp;
  43&nbsp;value=$( echo "$1" \
  44&nbsp;| tr -d wh \
  45&nbsp;| tr $val1 1 | tr $val2 2 | tr $val3 3 \
  46&nbsp;| tr $val4 4 | tr $val5 5 | tr $val6 6 \
  47&nbsp;| tr -s 123456 \
  48&nbsp;| tr -d aeiouy )
  49&nbsp;
  50&nbsp;# Assign letter values.
  51&nbsp;# Remove duplicate numbers, except when separated by vowels.
  52&nbsp;# Ignore vowels, except as separators, so delete them last.
  53&nbsp;# Ignore 'w' and 'h', even as separators, so delete them first.
  54&nbsp;#
  55&nbsp;# The above command substitution lays more pipe than a plumber &#60;g&#62;.
  56&nbsp;
  57&nbsp;}  
  58&nbsp;
  59&nbsp;
  60&nbsp;input_name="$1"
  61&nbsp;echo
  62&nbsp;echo "Name = $input_name"
  63&nbsp;
  64&nbsp;
  65&nbsp;# Change all characters of name input to lowercase.
  66&nbsp;# ------------------------------------------------
  67&nbsp;name=$( echo $input_name | tr A-Z a-z )
  68&nbsp;# ------------------------------------------------
  69&nbsp;# Just in case argument to script is mixed case.
  70&nbsp;
  71&nbsp;
  72&nbsp;# Prefix of soundex code: first letter of name.
  73&nbsp;# --------------------------------------------
  74&nbsp;
  75&nbsp;
  76&nbsp;char_pos=0                     # Initialize character position. 
  77&nbsp;prefix0=${name:$char_pos:1}
  78&nbsp;prefix=`echo $prefix0 | tr a-z A-Z`
  79&nbsp;                               # Uppercase 1st letter of soundex.
  80&nbsp;
  81&nbsp;let "char_pos += 1"            # Bump character position to 2nd letter of name.
  82&nbsp;name1=${name:$char_pos}
  83&nbsp;
  84&nbsp;
  85&nbsp;# ++++++++++++++++++++++++++ Exception Patch ++++++++++++++++++++++++++++++
  86&nbsp;#  Now, we run both the input name and the name shifted one char
  87&nbsp;#+ to the right through the value-assigning function.
  88&nbsp;#  If we get the same value out, that means that the first two characters
  89&nbsp;#+ of the name have the same value assigned, and that one should cancel.
  90&nbsp;#  However, we also need to test whether the first letter of the name
  91&nbsp;#+ is a vowel or 'w' or 'h', because otherwise this would bollix things up.
  92&nbsp;
  93&nbsp;char1=`echo $prefix | tr A-Z a-z`    # First letter of name, lowercased.
  94&nbsp;
  95&nbsp;assign_value $name
  96&nbsp;s1=$value
  97&nbsp;assign_value $name1
  98&nbsp;s2=$value
  99&nbsp;assign_value $char1
 100&nbsp;s3=$value
 101&nbsp;s3=9$s3                              #  If first letter of name is a vowel
 102&nbsp;                                     #+ or 'w' or 'h',
 103&nbsp;                                     #+ then its "value" will be null (unset).
 104&nbsp;				     #+ Therefore, set it to 9, an otherwise
 105&nbsp;				     #+ unused value, which can be tested for.
 106&nbsp;
 107&nbsp;
 108&nbsp;if [[ "$s1" -ne "$s2" || "$s3" -eq 9 ]]
 109&nbsp;then
 110&nbsp;  suffix=$s2
 111&nbsp;else  
 112&nbsp;  suffix=${s2:$char_pos}
 113&nbsp;fi  
 114&nbsp;# ++++++++++++++++++++++ end Exception Patch ++++++++++++++++++++++++++++++
 115&nbsp;
 116&nbsp;
 117&nbsp;padding=000                    # Use at most 3 zeroes to pad.
 118&nbsp;
 119&nbsp;
 120&nbsp;soun=$prefix$suffix$padding    # Pad with zeroes.
 121&nbsp;
 122&nbsp;MAXLEN=4                       # Truncate to maximum of 4 chars.
 123&nbsp;soundex=${soun:0:$MAXLEN}
 124&nbsp;
 125&nbsp;echo "Soundex = $soundex"
 126&nbsp;
 127&nbsp;echo
 128&nbsp;
 129&nbsp;#  The soundex code is a method of indexing and classifying names
 130&nbsp;#+ by grouping together the ones that sound alike.
 131&nbsp;#  The soundex code for a given name is the first letter of the name,
 132&nbsp;#+ followed by a calculated three-number code.
 133&nbsp;#  Similar sounding names should have almost the same soundex codes.
 134&nbsp;
 135&nbsp;#   Examples:
 136&nbsp;#   Smith and Smythe both have a "S-530" soundex.
 137&nbsp;#   Harrison = H-625
 138&nbsp;#   Hargison = H-622
 139&nbsp;#   Harriman = H-655
 140&nbsp;
 141&nbsp;#  This works out fairly well in practice, but there are numerous anomalies.
 142&nbsp;#
 143&nbsp;#
 144&nbsp;#  The U.S. Census and certain other governmental agencies use soundex,
 145&nbsp;#  as do genealogical researchers.
 146&nbsp;#
 147&nbsp;#  For more information,
 148&nbsp;#+ see the "National Archives and Records Administration home page",
 149&nbsp;#+ http://www.nara.gov/genealogy/soundex/soundex.html
 150&nbsp;
 151&nbsp;
 152&nbsp;
 153&nbsp;# Exercise:
 154&nbsp;# --------
 155&nbsp;# Simplify the "Exception Patch" section of this script.
 156&nbsp;
 157&nbsp;exit 0</PRE
></TD
></TR
></TABLE
><HR></DIV
><P
><A
NAME="LIFEREF"
></A
></P
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="LIFESLOW"
></A
><P
><B
>Example A-10. <I
CLASS="FIRSTTERM"
>Game of Life</I
></B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#!/bin/bash
   2&nbsp;# life.sh: "Life in the Slow Lane"
   3&nbsp;# Author: Mendel Cooper
   4&nbsp;# License: GPL3
   5&nbsp;
   6&nbsp;# Version 0.2:   Patched by Daniel Albers
   7&nbsp;#+               to allow non-square grids as input.
   8&nbsp;# Version 0.2.1: Added 2-second delay between generations.
   9&nbsp;
  10&nbsp;# ##################################################################### #
  11&nbsp;# This is the Bash script version of John Conway's "Game of Life".      #
  12&nbsp;# "Life" is a simple implementation of cellular automata.               #
  13&nbsp;# --------------------------------------------------------------------- #
  14&nbsp;# On a rectangular grid, let each "cell" be either "living" or "dead."  #
  15&nbsp;# Designate a living cell with a dot, and a dead one with a blank space.#
  16&nbsp;#      Begin with an arbitrarily drawn dot-and-blank grid,              #
  17&nbsp;#+     and let this be the starting generation: generation 0.           #
  18&nbsp;# Determine each successive generation by the following rules:          #
  19&nbsp;#   1) Each cell has 8 neighbors, the adjoining cells                   #
  20&nbsp;#+     left, right, top, bottom, and the 4 diagonals.                   #
  21&nbsp;#                                                                       #
  22&nbsp;#                       123                                             #
  23&nbsp;#                       4*5     The * is the cell under consideration.  #
  24&nbsp;#                       678                                             #
  25&nbsp;#                                                                       #
  26&nbsp;# 2) A living cell with either 2 or 3 living neighbors remains alive.   #
  27&nbsp;SURVIVE=2                                                               #
  28&nbsp;# 3) A dead cell with 3 living neighbors comes alive, a "birth."        #
  29&nbsp;BIRTH=3                                                                 #
  30&nbsp;# 4) All other cases result in a dead cell for the next generation.     #
  31&nbsp;# ##################################################################### #
  32&nbsp;
  33&nbsp;
  34&nbsp;startfile=gen0   # Read the starting generation from the file "gen0" ...
  35&nbsp;                 # Default, if no other file specified when invoking script.
  36&nbsp;                 #
  37&nbsp;if [ -n "$1" ]   # Specify another "generation 0" file.
  38&nbsp;then
  39&nbsp;    startfile="$1"
  40&nbsp;fi  
  41&nbsp;
  42&nbsp;############################################
  43&nbsp;#  Abort script if "startfile" not specified
  44&nbsp;#+ and
  45&nbsp;#+ default file "gen0" not present.
  46&nbsp;
  47&nbsp;E_NOSTARTFILE=86
  48&nbsp;
  49&nbsp;if [ ! -e "$startfile" ]
  50&nbsp;then
  51&nbsp;  echo "Startfile \""$startfile"\" missing!"
  52&nbsp;  exit $E_NOSTARTFILE
  53&nbsp;fi
  54&nbsp;############################################
  55&nbsp;
  56&nbsp;
  57&nbsp;ALIVE1=.
  58&nbsp;DEAD1=_
  59&nbsp;                 # Represent living and dead cells in the start-up file.
  60&nbsp;
  61&nbsp;#  -----------------------------------------------------#
  62&nbsp;#  This script uses a 10 x 10 grid (may be increased,
  63&nbsp;#+ but a large grid will slow down execution).
  64&nbsp;ROWS=10
  65&nbsp;COLS=10
  66&nbsp;#  Change above two variables to match desired grid size.
  67&nbsp;#  -----------------------------------------------------#
  68&nbsp;
  69&nbsp;GENERATIONS=10          #  How many generations to cycle through.
  70&nbsp;                        #  Adjust this upwards
  71&nbsp;                        #+ if you have time on your hands.
  72&nbsp;
  73&nbsp;NONE_ALIVE=85           #  Exit status on premature bailout,
  74&nbsp;                        #+ if no cells left alive.
  75&nbsp;DELAY=2                 #  Pause between generations.
  76&nbsp;TRUE=0
  77&nbsp;FALSE=1
  78&nbsp;ALIVE=0
  79&nbsp;DEAD=1
  80&nbsp;
  81&nbsp;avar=                   # Global; holds current generation.
  82&nbsp;generation=0            # Initialize generation count.
  83&nbsp;
  84&nbsp;# =================================================================
  85&nbsp;
  86&nbsp;let "cells = $ROWS * $COLS"   # How many cells.
  87&nbsp;
  88&nbsp;# Arrays containing "cells."
  89&nbsp;declare -a initial
  90&nbsp;declare -a current
  91&nbsp;
  92&nbsp;display ()
  93&nbsp;{
  94&nbsp;
  95&nbsp;alive=0                 # How many cells alive at any given time.
  96&nbsp;                        # Initially zero.
  97&nbsp;
  98&nbsp;declare -a arr
  99&nbsp;arr=( `echo "$1"` )     # Convert passed arg to array.
 100&nbsp;
 101&nbsp;element_count=${#arr[*]}
 102&nbsp;
 103&nbsp;local i
 104&nbsp;local rowcheck
 105&nbsp;
 106&nbsp;for ((i=0; i&#60;$element_count; i++))
 107&nbsp;do
 108&nbsp;
 109&nbsp;  # Insert newline at end of each row.
 110&nbsp;  let "rowcheck = $i % COLS"
 111&nbsp;  if [ "$rowcheck" -eq 0 ]
 112&nbsp;  then
 113&nbsp;    echo                # Newline.
 114&nbsp;    echo -n "      "    # Indent.
 115&nbsp;  fi  
 116&nbsp;
 117&nbsp;  cell=${arr[i]}
 118&nbsp;
 119&nbsp;  if [ "$cell" = . ]
 120&nbsp;  then
 121&nbsp;    let "alive += 1"
 122&nbsp;  fi  
 123&nbsp;
 124&nbsp;  echo -n "$cell" | sed -e 's/_/ /g'
 125&nbsp;  # Print out array, changing underscores to spaces.
 126&nbsp;done  
 127&nbsp;
 128&nbsp;return
 129&nbsp;
 130&nbsp;}
 131&nbsp;
 132&nbsp;IsValid ()                            # Test if cell coordinate valid.
 133&nbsp;{
 134&nbsp;
 135&nbsp;  if [ -z "$1"  -o -z "$2" ]          # Mandatory arguments missing?
 136&nbsp;  then
 137&nbsp;    return $FALSE
 138&nbsp;  fi
 139&nbsp;
 140&nbsp;local row
 141&nbsp;local lower_limit=0                   # Disallow negative coordinate.
 142&nbsp;local upper_limit
 143&nbsp;local left
 144&nbsp;local right
 145&nbsp;
 146&nbsp;let "upper_limit = $ROWS * $COLS - 1" # Total number of cells.
 147&nbsp;
 148&nbsp;
 149&nbsp;if [ "$1" -lt "$lower_limit" -o "$1" -gt "$upper_limit" ]
 150&nbsp;then
 151&nbsp;  return $FALSE                       # Out of array bounds.
 152&nbsp;fi  
 153&nbsp;
 154&nbsp;row=$2
 155&nbsp;let "left = $row * $COLS"             # Left limit.
 156&nbsp;let "right = $left + $COLS - 1"       # Right limit.
 157&nbsp;
 158&nbsp;if [ "$1" -lt "$left" -o "$1" -gt "$right" ]
 159&nbsp;then
 160&nbsp;  return $FALSE                       # Beyond row boundary.
 161&nbsp;fi  
 162&nbsp;
 163&nbsp;return $TRUE                          # Valid coordinate.
 164&nbsp;
 165&nbsp;}  
 166&nbsp;
 167&nbsp;
 168&nbsp;IsAlive ()              #  Test whether cell is alive.
 169&nbsp;                        #  Takes array, cell number, and
 170&nbsp;{                       #+ state of cell as arguments.
 171&nbsp;  GetCount "$1" $2      #  Get alive cell count in neighborhood.
 172&nbsp;  local nhbd=$?
 173&nbsp;
 174&nbsp;  if [ "$nhbd" -eq "$BIRTH" ]  # Alive in any case.
 175&nbsp;  then
 176&nbsp;    return $ALIVE
 177&nbsp;  fi
 178&nbsp;
 179&nbsp;  if [ "$3" = "." -a "$nhbd" -eq "$SURVIVE" ]
 180&nbsp;  then                  # Alive only if previously alive.
 181&nbsp;    return $ALIVE
 182&nbsp;  fi  
 183&nbsp;
 184&nbsp;  return $DEAD          # Defaults to dead.
 185&nbsp;
 186&nbsp;}  
 187&nbsp;
 188&nbsp;
 189&nbsp;GetCount ()             # Count live cells in passed cell's neighborhood.
 190&nbsp;                        # Two arguments needed:
 191&nbsp;			# $1) variable holding array
 192&nbsp;			# $2) cell number
 193&nbsp;{
 194&nbsp;  local cell_number=$2
 195&nbsp;  local array
 196&nbsp;  local top
 197&nbsp;  local center
 198&nbsp;  local bottom
 199&nbsp;  local r
 200&nbsp;  local row
 201&nbsp;  local i
 202&nbsp;  local t_top
 203&nbsp;  local t_cen
 204&nbsp;  local t_bot
 205&nbsp;  local count=0
 206&nbsp;  local ROW_NHBD=3
 207&nbsp;
 208&nbsp;  array=( `echo "$1"` )
 209&nbsp;
 210&nbsp;  let "top = $cell_number - $COLS - 1"    # Set up cell neighborhood.
 211&nbsp;  let "center = $cell_number - 1"
 212&nbsp;  let "bottom = $cell_number + $COLS - 1"
 213&nbsp;  let "r = $cell_number / $COLS"
 214&nbsp;
 215&nbsp;  for ((i=0; i&#60;$ROW_NHBD; i++))           # Traverse from left to right. 
 216&nbsp;  do
 217&nbsp;    let "t_top = $top + $i"
 218&nbsp;    let "t_cen = $center + $i"
 219&nbsp;    let "t_bot = $bottom + $i"
 220&nbsp;
 221&nbsp;
 222&nbsp;    let "row = $r"                        # Count center row.
 223&nbsp;    IsValid $t_cen $row                   # Valid cell position?
 224&nbsp;    if [ $? -eq "$TRUE" ]
 225&nbsp;    then
 226&nbsp;      if [ ${array[$t_cen]} = "$ALIVE1" ] # Is it alive?
 227&nbsp;      then                                # If yes, then ...
 228&nbsp;        let "count += 1"                  # Increment count.
 229&nbsp;      fi	
 230&nbsp;    fi  
 231&nbsp;
 232&nbsp;    let "row = $r - 1"                    # Count top row.          
 233&nbsp;    IsValid $t_top $row
 234&nbsp;    if [ $? -eq "$TRUE" ]
 235&nbsp;    then
 236&nbsp;      if [ ${array[$t_top]} = "$ALIVE1" ] # Redundancy here.
 237&nbsp;      then                                # Can it be optimized?
 238&nbsp;        let "count += 1"
 239&nbsp;      fi	
 240&nbsp;    fi  
 241&nbsp;
 242&nbsp;    let "row = $r + 1"                    # Count bottom row.
 243&nbsp;    IsValid $t_bot $row
 244&nbsp;    if [ $? -eq "$TRUE" ]
 245&nbsp;    then
 246&nbsp;      if [ ${array[$t_bot]} = "$ALIVE1" ] 
 247&nbsp;      then
 248&nbsp;        let "count += 1"
 249&nbsp;      fi	
 250&nbsp;    fi  
 251&nbsp;
 252&nbsp;  done  
 253&nbsp;
 254&nbsp;
 255&nbsp;  if [ ${array[$cell_number]} = "$ALIVE1" ]
 256&nbsp;  then
 257&nbsp;    let "count -= 1"        #  Make sure value of tested cell itself
 258&nbsp;  fi                        #+ is not counted.
 259&nbsp;
 260&nbsp;
 261&nbsp;  return $count
 262&nbsp;  
 263&nbsp;}
 264&nbsp;
 265&nbsp;next_gen ()               # Update generation array.
 266&nbsp;{
 267&nbsp;
 268&nbsp;local array
 269&nbsp;local i=0
 270&nbsp;
 271&nbsp;array=( `echo "$1"` )     # Convert passed arg to array.
 272&nbsp;
 273&nbsp;while [ "$i" -lt "$cells" ]
 274&nbsp;do
 275&nbsp;  IsAlive "$1" $i ${array[$i]}   # Is the cell alive?
 276&nbsp;  if [ $? -eq "$ALIVE" ]
 277&nbsp;  then                           #  If alive, then
 278&nbsp;    array[$i]=.                  #+ represent the cell as a period.
 279&nbsp;  else  
 280&nbsp;    array[$i]="_"                #  Otherwise underscore
 281&nbsp;   fi                            #+ (will later be converted to space).
 282&nbsp;  let "i += 1" 
 283&nbsp;done   
 284&nbsp;
 285&nbsp;
 286&nbsp;#    let "generation += 1"       # Increment generation count.
 287&nbsp;###  Why was the above line commented out?
 288&nbsp;
 289&nbsp;
 290&nbsp;# Set variable to pass as parameter to "display" function.
 291&nbsp;avar=`echo ${array[@]}`   # Convert array back to string variable.
 292&nbsp;display "$avar"           # Display it.
 293&nbsp;echo; echo
 294&nbsp;echo "Generation $generation  -  $alive alive"
 295&nbsp;
 296&nbsp;if [ "$alive" -eq 0 ]
 297&nbsp;then
 298&nbsp;  echo
 299&nbsp;  echo "Premature exit: no more cells alive!"
 300&nbsp;  exit $NONE_ALIVE        #  No point in continuing
 301&nbsp;fi                        #+ if no live cells.
 302&nbsp;
 303&nbsp;}
 304&nbsp;
 305&nbsp;
 306&nbsp;# =========================================================
 307&nbsp;
 308&nbsp;# main ()
 309&nbsp;# {
 310&nbsp;
 311&nbsp;# Load initial array with contents of startup file.
 312&nbsp;initial=( `cat "$startfile" | sed -e '/#/d' | tr -d '\n' |\
 313&nbsp;# Delete lines containing '#' comment character.
 314&nbsp;           sed -e 's/\./\. /g' -e 's/_/_ /g'` )
 315&nbsp;# Remove linefeeds and insert space between elements.
 316&nbsp;
 317&nbsp;clear          # Clear screen.
 318&nbsp;
 319&nbsp;echo #         Title
 320&nbsp;setterm -reverse on
 321&nbsp;echo "======================="
 322&nbsp;setterm -reverse off
 323&nbsp;echo "    $GENERATIONS generations"
 324&nbsp;echo "           of"
 325&nbsp;echo "\"Life in the Slow Lane\""
 326&nbsp;setterm -reverse on
 327&nbsp;echo "======================="
 328&nbsp;setterm -reverse off
 329&nbsp;
 330&nbsp;sleep $DELAY   # Display "splash screen" for 2 seconds.
 331&nbsp;
 332&nbsp;
 333&nbsp;# -------- Display first generation. --------
 334&nbsp;Gen0=`echo ${initial[@]}`
 335&nbsp;display "$Gen0"           # Display only.
 336&nbsp;echo; echo
 337&nbsp;echo "Generation $generation  -  $alive alive"
 338&nbsp;sleep $DELAY
 339&nbsp;# -------------------------------------------
 340&nbsp;
 341&nbsp;
 342&nbsp;let "generation += 1"     # Bump generation count.
 343&nbsp;echo
 344&nbsp;
 345&nbsp;# ------- Display second generation. -------
 346&nbsp;Cur=`echo ${initial[@]}`
 347&nbsp;next_gen "$Cur"          # Update &#38; display.
 348&nbsp;sleep $DELAY
 349&nbsp;# ------------------------------------------
 350&nbsp;
 351&nbsp;let "generation += 1"     # Increment generation count.
 352&nbsp;
 353&nbsp;# ------ Main loop for displaying subsequent generations ------
 354&nbsp;while [ "$generation" -le "$GENERATIONS" ]
 355&nbsp;do
 356&nbsp;  Cur="$avar"
 357&nbsp;  next_gen "$Cur"
 358&nbsp;  let "generation += 1"
 359&nbsp;  sleep $DELAY
 360&nbsp;done
 361&nbsp;# ==============================================================
 362&nbsp;
 363&nbsp;echo
 364&nbsp;# }
 365&nbsp;
 366&nbsp;exit 0   # CEOF:EOF
 367&nbsp;
 368&nbsp;
 369&nbsp;
 370&nbsp;# The grid in this script has a "boundary problem."
 371&nbsp;# The the top, bottom, and sides border on a void of dead cells.
 372&nbsp;# Exercise: Change the script to have the grid wrap around,
 373&nbsp;# +         so that the left and right sides will "touch,"      
 374&nbsp;# +         as will the top and bottom.
 375&nbsp;#
 376&nbsp;# Exercise: Create a new "gen0" file to seed this script.
 377&nbsp;#           Use a 12 x 16 grid, instead of the original 10 x 10 one.
 378&nbsp;#           Make the necessary changes to the script,
 379&nbsp;#+          so it will run with the altered file.
 380&nbsp;#
 381&nbsp;# Exercise: Modify this script so that it can determine the grid size
 382&nbsp;#+          from the "gen0" file, and set any variables necessary
 383&nbsp;#+          for the script to run.
 384&nbsp;#           This would make unnecessary any changes to variables
 385&nbsp;#+          in the script for an altered grid size.
 386&nbsp;#
 387&nbsp;# Exercise: Optimize this script.
 388&nbsp;#           It has redundant code.</PRE
></TD
></TR
></TABLE
><HR></DIV
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="GEN0DATA"
></A
><P
><B
>Example A-11. Data file for <I
CLASS="FIRSTTERM"
>Game of Life</I
></B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;# gen0
   2&nbsp;#
   3&nbsp;# This is an example "generation 0" start-up file for "life.sh".
   4&nbsp;# --------------------------------------------------------------
   5&nbsp;#  The "gen0" file is a 10 x 10 grid using a period (.) for live cells,
   6&nbsp;#+ and an underscore (_) for dead ones. We cannot simply use spaces
   7&nbsp;#+ for dead cells in this file because of a peculiarity in Bash arrays.
   8&nbsp;#  [Exercise for the reader: explain this.]
   9&nbsp;#
  10&nbsp;# Lines beginning with a '#' are comments, and the script ignores them.
  11&nbsp;__.__..___
  12&nbsp;__.._.____
  13&nbsp;____.___..
  14&nbsp;_._______.
  15&nbsp;____._____
  16&nbsp;..__...___
  17&nbsp;____._____
  18&nbsp;___...____
  19&nbsp;__.._..___
  20&nbsp;_..___..__</PRE
></TD
></TR
></TABLE
><HR></DIV
><P
>+++</P
><P
>The following script is by Mark Moraes of the University
    of Toronto. See the file <TT
CLASS="FILENAME"
>Moraes-COPYRIGHT</TT
>
    for permissions and restrictions. This file is included in the
    combined <A
HREF="mirrorsites.html#WHERE_TARBALL"
>HTML/source tarball</A
>
    of the <SPAN
CLASS="emphasis"
><I
CLASS="EMPHASIS"
>ABS Guide</I
></SPAN
>.</P
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="BEHEAD"
></A
><P
><B
>Example A-12. <I
CLASS="FIRSTTERM"
>behead</I
>: Removing mail and news
      message headers</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#! /bin/sh
   2&nbsp;#  Strips off the header from a mail/News message i.e. till the first
   3&nbsp;#+ empty line.
   4&nbsp;#  Author: Mark Moraes, University of Toronto
   5&nbsp;
   6&nbsp;# ==&#62; These comments added by author of this document.
   7&nbsp;
   8&nbsp;if [ $# -eq 0 ]; then
   9&nbsp;# ==&#62; If no command-line args present, then works on file redirected to stdin.
  10&nbsp;	sed -e '1,/^$/d' -e '/^[ 	]*$/d'
  11&nbsp;	# --&#62; Delete empty lines and all lines until 
  12&nbsp;	# --&#62; first one beginning with white space.
  13&nbsp;else
  14&nbsp;# ==&#62; If command-line args present, then work on files named.
  15&nbsp;	for i do
  16&nbsp;		sed -e '1,/^$/d' -e '/^[ 	]*$/d' $i
  17&nbsp;		# --&#62; Ditto, as above.
  18&nbsp;	done
  19&nbsp;fi
  20&nbsp;
  21&nbsp;exit
  22&nbsp;
  23&nbsp;# ==&#62; Exercise: Add error checking and other options.
  24&nbsp;# ==&#62;
  25&nbsp;# ==&#62; Note that the small sed script repeats, except for the arg passed.
  26&nbsp;# ==&#62; Does it make sense to embed it in a function? Why or why not?
  27&nbsp;
  28&nbsp;
  29&nbsp;/*
  30&nbsp; * Copyright University of Toronto 1988, 1989.
  31&nbsp; * Written by Mark Moraes
  32&nbsp; *
  33&nbsp; * Permission is granted to anyone to use this software for any purpose on
  34&nbsp; * any computer system, and to alter it and redistribute it freely, subject
  35&nbsp; * to the following restrictions:
  36&nbsp; *
  37&nbsp; * 1. The author and the University of Toronto are not responsible 
  38&nbsp; *    for the consequences of use of this software, no matter how awful, 
  39&nbsp; *    even if they arise from flaws in it.
  40&nbsp; *
  41&nbsp; * 2. The origin of this software must not be misrepresented, either by
  42&nbsp; *    explicit claim or by omission.  Since few users ever read sources,
  43&nbsp; *    credits must appear in the documentation.
  44&nbsp; *
  45&nbsp; * 3. Altered versions must be plainly marked as such, and must not be
  46&nbsp; *    misrepresented as being the original software.  Since few users
  47&nbsp; *    ever read sources, credits must appear in the documentation.
  48&nbsp; *
  49&nbsp; * 4. This notice may not be removed or altered.
  50&nbsp; */</PRE
></TD
></TR
></TABLE
><HR></DIV
><P
>+</P
><P
>Antek Sawicki contributed the following script, which makes very
      clever use of the parameter substitution operators discussed in
      <A
HREF="parameter-substitution.html"
>Section 10.2</A
>.</P
><P
><A
NAME="PW0"
></A
></P
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="PW"
></A
><P
><B
>Example A-13. <I
CLASS="FIRSTTERM"
>password</I
>: Generating random
      8-character passwords</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#!/bin/bash
   2&nbsp;#
   3&nbsp;#
   4&nbsp;#  Random password generator for Bash 2.x +
   5&nbsp;#+ by Antek Sawicki &#60;tenox@tenox.tc&#62;,
   6&nbsp;#+ who generously gave usage permission to the ABS Guide author.
   7&nbsp;#
   8&nbsp;# ==&#62; Comments added by document author ==&#62;
   9&nbsp;
  10&nbsp;
  11&nbsp;MATRIX="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
  12&nbsp;# ==&#62; Password will consist of alphanumeric characters.
  13&nbsp;LENGTH="8"
  14&nbsp;# ==&#62; May change 'LENGTH' for longer password.
  15&nbsp;
  16&nbsp;
  17&nbsp;while [ "${n:=1}" -le "$LENGTH" ]
  18&nbsp;# ==&#62; Recall that := is "default substitution" operator.
  19&nbsp;# ==&#62; So, if 'n' has not been initialized, set it to 1.
  20&nbsp;do
  21&nbsp;	PASS="$PASS${MATRIX:$(($RANDOM%${#MATRIX})):1}"
  22&nbsp;	# ==&#62; Very clever, but tricky.
  23&nbsp;
  24&nbsp;	# ==&#62; Starting from the innermost nesting...
  25&nbsp;	# ==&#62; ${#MATRIX} returns length of array MATRIX.
  26&nbsp;
  27&nbsp;	# ==&#62; $RANDOM%${#MATRIX} returns random number between 1
  28&nbsp;	# ==&#62; and [length of MATRIX] - 1.
  29&nbsp;
  30&nbsp;	# ==&#62; ${MATRIX:$(($RANDOM%${#MATRIX})):1}
  31&nbsp;	# ==&#62; returns expansion of MATRIX at random position, by length 1. 
  32&nbsp;	# ==&#62; See {var:pos:len} parameter substitution in Chapter 9.
  33&nbsp;	# ==&#62; and the associated examples.
  34&nbsp;
  35&nbsp;	# ==&#62; PASS=... simply pastes this result onto previous PASS (concatenation).
  36&nbsp;
  37&nbsp;	# ==&#62; To visualize this more clearly, uncomment the following line
  38&nbsp;	#                 echo "$PASS"
  39&nbsp;	# ==&#62; to see PASS being built up,
  40&nbsp;	# ==&#62; one character at a time, each iteration of the loop.
  41&nbsp;
  42&nbsp;	let n+=1
  43&nbsp;	# ==&#62; Increment 'n' for next pass.
  44&nbsp;done
  45&nbsp;
  46&nbsp;echo "$PASS"      # ==&#62; Or, redirect to a file, as desired.
  47&nbsp;
  48&nbsp;exit 0</PRE
></TD
></TR
></TABLE
><HR></DIV
><P
>+</P
><P
><A
NAME="ZFIFO"
></A
>James R. Van Zandt contributed this script
      which uses named pipes and, in his words, <SPAN
CLASS="QUOTE"
>"really exercises
      quoting and escaping."</SPAN
></P
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="FIFO"
></A
><P
><B
>Example A-14. <I
CLASS="FIRSTTERM"
>fifo</I
>: Making daily backups, using
      named pipes</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#!/bin/bash
   2&nbsp;# ==&#62; Script by James R. Van Zandt, and used here with his permission.
   3&nbsp;
   4&nbsp;# ==&#62; Comments added by author of this document.
   5&nbsp;
   6&nbsp;  
   7&nbsp;  HERE=`uname -n`    # ==&#62; hostname
   8&nbsp;  THERE=bilbo
   9&nbsp;  echo "starting remote backup to $THERE at `date +%r`"
  10&nbsp;  # ==&#62; `date +%r` returns time in 12-hour format, i.e. "08:08:34 PM".
  11&nbsp;  
  12&nbsp;  # make sure /pipe really is a pipe and not a plain file
  13&nbsp;  rm -rf /pipe
  14&nbsp;  mkfifo /pipe       # ==&#62; Create a "named pipe", named "/pipe" ...
  15&nbsp;  
  16&nbsp;  # ==&#62; 'su xyz' runs commands as user "xyz".
  17&nbsp;  # ==&#62; 'ssh' invokes secure shell (remote login client).
  18&nbsp;  su xyz -c "ssh $THERE \"cat &#62; /home/xyz/backup/${HERE}-daily.tar.gz\" &#60; /pipe"&#38;
  19&nbsp;  cd /
  20&nbsp;  tar -czf - bin boot dev etc home info lib man root sbin share usr var &#62; /pipe
  21&nbsp;  # ==&#62; Uses named pipe, /pipe, to communicate between processes:
  22&nbsp;  # ==&#62; 'tar/gzip' writes to /pipe and 'ssh' reads from /pipe.
  23&nbsp;
  24&nbsp;  # ==&#62; The end result is this backs up the main directories, from / on down.
  25&nbsp;
  26&nbsp;  # ==&#62;  What are the advantages of a "named pipe" in this situation,
  27&nbsp;  # ==&#62;+ as opposed to an "anonymous pipe", with |?
  28&nbsp;  # ==&#62;  Will an anonymous pipe even work here?
  29&nbsp;
  30&nbsp;  # ==&#62;  Is it necessary to delete the pipe before exiting the script?
  31&nbsp;  # ==&#62;  How could that be done?
  32&nbsp;
  33&nbsp;
  34&nbsp;  exit 0</PRE
></TD
></TR
></TABLE
><HR></DIV
><P
>+</P
><P
><A
NAME="PRIMES1"
></A
></P
><P
>Stphane Chazelas used the following script to
      demonstrate generating prime numbers without arrays.</P
><P
><A
NAME="PRIMES00"
></A
></P
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="PRIMES"
></A
><P
><B
>Example A-15. Generating prime numbers using the modulo operator</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#!/bin/bash
   2&nbsp;# primes.sh: Generate prime numbers, without using arrays.
   3&nbsp;# Script contributed by Stephane Chazelas.
   4&nbsp;
   5&nbsp;#  This does *not* use the classic "Sieve of Eratosthenes" algorithm,
   6&nbsp;#+ but instead the more intuitive method of testing each candidate number
   7&nbsp;#+ for factors (divisors), using the "%" modulo operator.
   8&nbsp;
   9&nbsp;
  10&nbsp;LIMIT=1000                    # Primes, 2 ... 1000.
  11&nbsp;
  12&nbsp;Primes()
  13&nbsp;{
  14&nbsp; (( n = $1 + 1 ))             # Bump to next integer.
  15&nbsp; shift                        # Next parameter in list.
  16&nbsp;#  echo "_n=$n i=$i_"
  17&nbsp; 
  18&nbsp; if (( n == LIMIT ))
  19&nbsp; then echo $*
  20&nbsp; return
  21&nbsp; fi
  22&nbsp;
  23&nbsp; for i; do                    # "i" set to "@", previous values of $n.
  24&nbsp;#   echo "-n=$n i=$i-"
  25&nbsp;   (( i * i &#62; n )) &#38;&#38; break   # Optimization.
  26&nbsp;   (( n % i )) &#38;&#38; continue    # Sift out non-primes using modulo operator.
  27&nbsp;   Primes $n $@               # Recursion inside loop.
  28&nbsp;   return
  29&nbsp;   done
  30&nbsp;
  31&nbsp;   Primes $n $@ $n            #  Recursion outside loop.
  32&nbsp;                              #  Successively accumulate
  33&nbsp;			      #+ positional parameters.
  34&nbsp;                              #  "$@" is the accumulating list of primes.
  35&nbsp;}
  36&nbsp;
  37&nbsp;Primes 1
  38&nbsp;
  39&nbsp;exit $?
  40&nbsp;
  41&nbsp;# Pipe output of the script to 'fmt' for prettier printing.
  42&nbsp;
  43&nbsp;#  Uncomment lines 16 and 24 to help figure out what is going on.
  44&nbsp;
  45&nbsp;#  Compare the speed of this algorithm for generating primes
  46&nbsp;#+ with the Sieve of Eratosthenes (ex68.sh).
  47&nbsp;
  48&nbsp;
  49&nbsp;#  Exercise: Rewrite this script without recursion.</PRE
></TD
></TR
></TABLE
><HR></DIV
><P
>+</P
><P
>Rick Boivie's revision of Jordi Sanfeliu's
      <SPAN
CLASS="emphasis"
><I
CLASS="EMPHASIS"
>tree</I
></SPAN
> script.</P
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="TREE"
></A
><P
><B
>Example A-16. <I
CLASS="FIRSTTERM"
>tree</I
>: Displaying a directory tree</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#!/bin/bash
   2&nbsp;# tree.sh
   3&nbsp;
   4&nbsp;#  Written by Rick Boivie.
   5&nbsp;#  Used with permission.
   6&nbsp;#  This is a revised and simplified version of a script
   7&nbsp;#+ by Jordi Sanfeliu (the original author), and patched by Ian Kjos.
   8&nbsp;#  This script replaces the earlier version used in
   9&nbsp;#+ previous releases of the Advanced Bash Scripting Guide.
  10&nbsp;#  Copyright (c) 2002, by Jordi Sanfeliu, Rick Boivie, and Ian Kjos.
  11&nbsp;
  12&nbsp;# ==&#62; Comments added by the author of this document.
  13&nbsp;
  14&nbsp;
  15&nbsp;search () {
  16&nbsp;for dir in `echo *`
  17&nbsp;#  ==&#62; `echo *` lists all the files in current working directory,
  18&nbsp;#+ ==&#62; without line breaks.
  19&nbsp;#  ==&#62; Similar effect to for dir in *
  20&nbsp;#  ==&#62; but "dir in `echo *`" will not handle filenames with blanks.
  21&nbsp;do
  22&nbsp;  if [ -d "$dir" ] ; then # ==&#62; If it is a directory (-d)...
  23&nbsp;  zz=0                    # ==&#62; Temp variable, keeping track of
  24&nbsp;                          #     directory level.
  25&nbsp;  while [ $zz != $1 ]     # Keep track of inner nested loop.
  26&nbsp;    do
  27&nbsp;      echo -n "| "        # ==&#62; Display vertical connector symbol,
  28&nbsp;                          # ==&#62; with 2 spaces &#38; no line feed
  29&nbsp;                          #     in order to indent.
  30&nbsp;      zz=`expr $zz + 1`   # ==&#62; Increment zz.
  31&nbsp;    done
  32&nbsp;
  33&nbsp;    if [ -L "$dir" ] ; then # ==&#62; If directory is a symbolic link...
  34&nbsp;      echo "+---$dir" `ls -l $dir | sed 's/^.*'$dir' //'`
  35&nbsp;      # ==&#62; Display horiz. connector and list directory name, but...
  36&nbsp;      # ==&#62; delete date/time part of long listing.
  37&nbsp;    else
  38&nbsp;      echo "+---$dir"       # ==&#62; Display horizontal connector symbol...
  39&nbsp;      # ==&#62; and print directory name.
  40&nbsp;      numdirs=`expr $numdirs + 1` # ==&#62; Increment directory count.
  41&nbsp;      if cd "$dir" ; then         # ==&#62; If can move to subdirectory...
  42&nbsp;        search `expr $1 + 1`      # with recursion ;-)
  43&nbsp;        # ==&#62; Function calls itself.
  44&nbsp;        cd ..
  45&nbsp;      fi
  46&nbsp;    fi
  47&nbsp;  fi
  48&nbsp;done
  49&nbsp;}
  50&nbsp;
  51&nbsp;if [ $# != 0 ] ; then
  52&nbsp;  cd $1   # Move to indicated directory.
  53&nbsp;  #else   # stay in current directory
  54&nbsp;fi
  55&nbsp;
  56&nbsp;echo "Initial directory = `pwd`"
  57&nbsp;numdirs=0
  58&nbsp;
  59&nbsp;search 0
  60&nbsp;echo "Total directories = $numdirs"
  61&nbsp;
  62&nbsp;exit 0</PRE
></TD
></TR
></TABLE
><HR></DIV
><P
>Patsie's version of a directory <I
CLASS="FIRSTTERM"
>tree</I
>
      script.</P
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="TREE2"
></A
><P
><B
>Example A-17. <I
CLASS="FIRSTTERM"
>tree2</I
>: Alternate directory tree script</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#!/bin/bash
   2&nbsp;# tree2.sh
   3&nbsp;
   4&nbsp;# Lightly modified/reformatted by ABS Guide author.
   5&nbsp;# Included in ABS Guide with permission of script author (thanks!).
   6&nbsp;
   7&nbsp;## Recursive file/dirsize checking script, by Patsie
   8&nbsp;##
   9&nbsp;## This script builds a list of files/directories and their size (du -akx)
  10&nbsp;## and processes this list to a human readable tree shape
  11&nbsp;## The 'du -akx' is only as good as the permissions the owner has.
  12&nbsp;## So preferably run as root* to get the best results, or use only on
  13&nbsp;## directories for which you have read permissions. Anything you can't
  14&nbsp;## read is not in the list.
  15&nbsp;
  16&nbsp;#* ABS Guide author advises caution when running scripts as root!
  17&nbsp;
  18&nbsp;
  19&nbsp;##########  THIS IS CONFIGURABLE  ##########
  20&nbsp;
  21&nbsp;TOP=5                   # Top 5 biggest (sub)directories.
  22&nbsp;MAXRECURS=5             # Max 5 subdirectories/recursions deep.
  23&nbsp;E_BL=80                 # Blank line already returned.
  24&nbsp;E_DIR=81                # Directory not specified.
  25&nbsp;
  26&nbsp;
  27&nbsp;##########  DON'T CHANGE ANYTHING BELOW THIS LINE  ##########
  28&nbsp;
  29&nbsp;PID=$$                            # Our own process ID.
  30&nbsp;SELF=`basename $0`                # Our own program name.
  31&nbsp;TMP="/tmp/${SELF}.${PID}.tmp"     # Temporary 'du' result.
  32&nbsp;
  33&nbsp;# Convert number to dotted thousand.
  34&nbsp;function dot { echo "            $*" |
  35&nbsp;               sed -e :a -e 's/\(.*[0-9]\)\([0-9]\{3\}\)/\1,\2/;ta' |
  36&nbsp;               tail -c 12; }
  37&nbsp;
  38&nbsp;# Usage: tree &#60;recursion&#62; &#60;indent prefix&#62; &#60;min size&#62; &#60;directory&#62;
  39&nbsp;function tree {
  40&nbsp;  recurs="$1"           # How deep nested are we?
  41&nbsp;  prefix="$2"           # What do we display before file/dirname?
  42&nbsp;  minsize="$3"          # What is the minumum file/dirsize?
  43&nbsp;  dirname="$4"          # Which directory are we checking?
  44&nbsp;
  45&nbsp;# Get ($TOP) biggest subdirs/subfiles from TMP file.
  46&nbsp;  LIST=`egrep "[[:space:]]${dirname}/[^/]*$" "$TMP" |
  47&nbsp;        awk '{if($1&#62;'$minsize') print;}' | sort -nr | head -$TOP`
  48&nbsp;  [ -z "$LIST" ] &#38;&#38; return        # Empty list, then go back.
  49&nbsp;
  50&nbsp;  cnt=0
  51&nbsp;  num=`echo "$LIST" | wc -l`      # How many entries in the list.
  52&nbsp;
  53&nbsp;  ## Main loop
  54&nbsp;  echo "$LIST" | while read size name; do
  55&nbsp;    ((cnt+=1))		          # Count entry number.
  56&nbsp;    bname=`basename "$name"`      # We only need a basename of the entry.
  57&nbsp;    [ -d "$name" ] &#38;&#38; bname="$bname/"
  58&nbsp;                                  # If it's a directory, append a slash.
  59&nbsp;    echo "`dot $size`$prefix +-$bname"
  60&nbsp;                                  # Display the result.
  61&nbsp;    #  Call ourself recursively if it's a directory
  62&nbsp;    #+ and we're not nested too deep ($MAXRECURS).
  63&nbsp;    #  The recursion goes up: $((recurs+1))
  64&nbsp;    #  The prefix gets a space if it's the last entry,
  65&nbsp;    #+ or a pipe if there are more entries.
  66&nbsp;    #  The minimum file/dirsize becomes
  67&nbsp;    #+ a tenth of his parent: $((size/10)).
  68&nbsp;    # Last argument is the full directory name to check.
  69&nbsp;    if [ -d "$name" -a $recurs -lt $MAXRECURS ]; then
  70&nbsp;      [ $cnt -lt $num ] \
  71&nbsp;        || (tree $((recurs+1)) "$prefix  " $((size/10)) "$name") \
  72&nbsp;        &#38;&#38; (tree $((recurs+1)) "$prefix |" $((size/10)) "$name")
  73&nbsp;    fi
  74&nbsp;  done
  75&nbsp;
  76&nbsp;  [ $? -eq 0 ] &#38;&#38; echo "           $prefix"
  77&nbsp;  # Every time we jump back add a 'blank' line.
  78&nbsp;  return $E_BL
  79&nbsp;  # We return 80 to tell we added a blank line already.
  80&nbsp;}
  81&nbsp;
  82&nbsp;###                ###
  83&nbsp;###  main program  ###
  84&nbsp;###                ###
  85&nbsp;
  86&nbsp;rootdir="$@"
  87&nbsp;[ -d "$rootdir" ] ||
  88&nbsp;  { echo "$SELF: Usage: $SELF &#60;directory&#62;" &#62;&#38;2; exit $E_DIR; }
  89&nbsp;  # We should be called with a directory name.
  90&nbsp;
  91&nbsp;echo "Building inventory list, please wait ..."
  92&nbsp;     # Show "please wait" message.
  93&nbsp;du -akx "$rootdir" 1&#62;"$TMP" 2&#62;/dev/null
  94&nbsp;     # Build a temporary list of all files/dirs and their size.
  95&nbsp;size=`tail -1 "$TMP" | awk '{print $1}'`
  96&nbsp;     # What is our rootdirectory's size?
  97&nbsp;echo "`dot $size` $rootdir"
  98&nbsp;     # Display rootdirectory's entry.
  99&nbsp;tree 0 "" 0 "$rootdir"
 100&nbsp;     # Display the tree below our rootdirectory.
 101&nbsp;
 102&nbsp;rm "$TMP" 2&#62;/dev/null
 103&nbsp;     # Clean up TMP file.
 104&nbsp;
 105&nbsp;exit $?</PRE
></TD
></TR
></TABLE
><HR></DIV
><P
>Noah Friedman permitted use of his <SPAN
CLASS="emphasis"
><I
CLASS="EMPHASIS"
>string
      function</I
></SPAN
> script. It essentially reproduces some
      of the <I
CLASS="FIRSTTERM"
>C</I
>-library string manipulation
      functions.</P
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="STRING"
></A
><P
><B
>Example A-18. <I
CLASS="FIRSTTERM"
>string functions</I
>: C-style string
      functions</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#!/bin/bash
   2&nbsp;
   3&nbsp;# string.bash --- bash emulation of string(3) library routines
   4&nbsp;# Author: Noah Friedman &#60;friedman@prep.ai.mit.edu&#62;
   5&nbsp;# ==&#62;     Used with his kind permission in this document.
   6&nbsp;# Created: 1992-07-01
   7&nbsp;# Last modified: 1993-09-29
   8&nbsp;# Public domain
   9&nbsp;
  10&nbsp;# Conversion to bash v2 syntax done by Chet Ramey
  11&nbsp;
  12&nbsp;# Commentary:
  13&nbsp;# Code:
  14&nbsp;
  15&nbsp;#:docstring strcat:
  16&nbsp;# Usage: strcat s1 s2
  17&nbsp;#
  18&nbsp;# Strcat appends the value of variable s2 to variable s1. 
  19&nbsp;#
  20&nbsp;# Example:
  21&nbsp;#    a="foo"
  22&nbsp;#    b="bar"
  23&nbsp;#    strcat a b
  24&nbsp;#    echo $a
  25&nbsp;#    =&#62; foobar
  26&nbsp;#
  27&nbsp;#:end docstring:
  28&nbsp;
  29&nbsp;###;;;autoload   ==&#62; Autoloading of function commented out.
  30&nbsp;function strcat ()
  31&nbsp;{
  32&nbsp;    local s1_val s2_val
  33&nbsp;
  34&nbsp;    s1_val=${!1}                        # indirect variable expansion
  35&nbsp;    s2_val=${!2}
  36&nbsp;    eval "$1"=\'"${s1_val}${s2_val}"\'
  37&nbsp;    # ==&#62; eval $1='${s1_val}${s2_val}' avoids problems,
  38&nbsp;    # ==&#62; if one of the variables contains a single quote.
  39&nbsp;}
  40&nbsp;
  41&nbsp;#:docstring strncat:
  42&nbsp;# Usage: strncat s1 s2 $n
  43&nbsp;# 
  44&nbsp;# Line strcat, but strncat appends a maximum of n characters from the value
  45&nbsp;# of variable s2.  It copies fewer if the value of variabl s2 is shorter
  46&nbsp;# than n characters.  Echoes result on stdout.
  47&nbsp;#
  48&nbsp;# Example:
  49&nbsp;#    a=foo
  50&nbsp;#    b=barbaz
  51&nbsp;#    strncat a b 3
  52&nbsp;#    echo $a
  53&nbsp;#    =&#62; foobar
  54&nbsp;#
  55&nbsp;#:end docstring:
  56&nbsp;
  57&nbsp;###;;;autoload
  58&nbsp;function strncat ()
  59&nbsp;{
  60&nbsp;    local s1="$1"
  61&nbsp;    local s2="$2"
  62&nbsp;    local -i n="$3"
  63&nbsp;    local s1_val s2_val
  64&nbsp;
  65&nbsp;    s1_val=${!s1}                       # ==&#62; indirect variable expansion
  66&nbsp;    s2_val=${!s2}
  67&nbsp;
  68&nbsp;    if [ ${#s2_val} -gt ${n} ]; then
  69&nbsp;       s2_val=${s2_val:0:$n}            # ==&#62; substring extraction
  70&nbsp;    fi
  71&nbsp;
  72&nbsp;    eval "$s1"=\'"${s1_val}${s2_val}"\'
  73&nbsp;    # ==&#62; eval $1='${s1_val}${s2_val}' avoids problems,
  74&nbsp;    # ==&#62; if one of the variables contains a single quote.
  75&nbsp;}
  76&nbsp;
  77&nbsp;#:docstring strcmp:
  78&nbsp;# Usage: strcmp $s1 $s2
  79&nbsp;#
  80&nbsp;# Strcmp compares its arguments and returns an integer less than, equal to,
  81&nbsp;# or greater than zero, depending on whether string s1 is lexicographically
  82&nbsp;# less than, equal to, or greater than string s2.
  83&nbsp;#:end docstring:
  84&nbsp;
  85&nbsp;###;;;autoload
  86&nbsp;function strcmp ()
  87&nbsp;{
  88&nbsp;    [ "$1" = "$2" ] &#38;&#38; return 0
  89&nbsp;
  90&nbsp;    [ "${1}" '&#60;' "${2}" ] &#62; /dev/null &#38;&#38; return -1
  91&nbsp;
  92&nbsp;    return 1
  93&nbsp;}
  94&nbsp;
  95&nbsp;#:docstring strncmp:
  96&nbsp;# Usage: strncmp $s1 $s2 $n
  97&nbsp;# 
  98&nbsp;# Like strcmp, but makes the comparison by examining a maximum of n
  99&nbsp;# characters (n less than or equal to zero yields equality).
 100&nbsp;#:end docstring:
 101&nbsp;
 102&nbsp;###;;;autoload
 103&nbsp;function strncmp ()
 104&nbsp;{
 105&nbsp;    if [ -z "${3}" -o "${3}" -le "0" ]; then
 106&nbsp;       return 0
 107&nbsp;    fi
 108&nbsp;   
 109&nbsp;    if [ ${3} -ge ${#1} -a ${3} -ge ${#2} ]; then
 110&nbsp;       strcmp "$1" "$2"
 111&nbsp;       return $?
 112&nbsp;    else
 113&nbsp;       s1=${1:0:$3}
 114&nbsp;       s2=${2:0:$3}
 115&nbsp;       strcmp $s1 $s2
 116&nbsp;       return $?
 117&nbsp;    fi
 118&nbsp;}
 119&nbsp;
 120&nbsp;#:docstring strlen:
 121&nbsp;# Usage: strlen s
 122&nbsp;#
 123&nbsp;# Strlen returns the number of characters in string literal s.
 124&nbsp;#:end docstring:
 125&nbsp;
 126&nbsp;###;;;autoload
 127&nbsp;function strlen ()
 128&nbsp;{
 129&nbsp;    eval echo "\${#${1}}"
 130&nbsp;    # ==&#62; Returns the length of the value of the variable
 131&nbsp;    # ==&#62; whose name is passed as an argument.
 132&nbsp;}
 133&nbsp;
 134&nbsp;#:docstring strspn:
 135&nbsp;# Usage: strspn $s1 $s2
 136&nbsp;# 
 137&nbsp;# Strspn returns the length of the maximum initial segment of string s1,
 138&nbsp;# which consists entirely of characters from string s2.
 139&nbsp;#:end docstring:
 140&nbsp;
 141&nbsp;###;;;autoload
 142&nbsp;function strspn ()
 143&nbsp;{
 144&nbsp;    # Unsetting IFS allows whitespace to be handled as normal chars. 
 145&nbsp;    local IFS=
 146&nbsp;    local result="${1%%[!${2}]*}"
 147&nbsp; 
 148&nbsp;    echo ${#result}
 149&nbsp;}
 150&nbsp;
 151&nbsp;#:docstring strcspn:
 152&nbsp;# Usage: strcspn $s1 $s2
 153&nbsp;#
 154&nbsp;# Strcspn returns the length of the maximum initial segment of string s1,
 155&nbsp;# which consists entirely of characters not from string s2.
 156&nbsp;#:end docstring:
 157&nbsp;
 158&nbsp;###;;;autoload
 159&nbsp;function strcspn ()
 160&nbsp;{
 161&nbsp;    # Unsetting IFS allows whitspace to be handled as normal chars. 
 162&nbsp;    local IFS=
 163&nbsp;    local result="${1%%[${2}]*}"
 164&nbsp; 
 165&nbsp;    echo ${#result}
 166&nbsp;}
 167&nbsp;
 168&nbsp;#:docstring strstr:
 169&nbsp;# Usage: strstr s1 s2
 170&nbsp;# 
 171&nbsp;# Strstr echoes a substring starting at the first occurrence of string s2 in
 172&nbsp;# string s1, or nothing if s2 does not occur in the string.  If s2 points to
 173&nbsp;# a string of zero length, strstr echoes s1.
 174&nbsp;#:end docstring:
 175&nbsp;
 176&nbsp;###;;;autoload
 177&nbsp;function strstr ()
 178&nbsp;{
 179&nbsp;    # if s2 points to a string of zero length, strstr echoes s1
 180&nbsp;    [ ${#2} -eq 0 ] &#38;&#38; { echo "$1" ; return 0; }
 181&nbsp;
 182&nbsp;    # strstr echoes nothing if s2 does not occur in s1
 183&nbsp;    case "$1" in
 184&nbsp;    *$2*) ;;
 185&nbsp;    *) return 1;;
 186&nbsp;    esac
 187&nbsp;
 188&nbsp;    # use the pattern matching code to strip off the match and everything
 189&nbsp;    # following it
 190&nbsp;    first=${1/$2*/}
 191&nbsp;
 192&nbsp;    # then strip off the first unmatched portion of the string
 193&nbsp;    echo "${1##$first}"
 194&nbsp;}
 195&nbsp;
 196&nbsp;#:docstring strtok:
 197&nbsp;# Usage: strtok s1 s2
 198&nbsp;#
 199&nbsp;# Strtok considers the string s1 to consist of a sequence of zero or more
 200&nbsp;# text tokens separated by spans of one or more characters from the
 201&nbsp;# separator string s2.  The first call (with a non-empty string s1
 202&nbsp;# specified) echoes a string consisting of the first token on stdout. The
 203&nbsp;# function keeps track of its position in the string s1 between separate
 204&nbsp;# calls, so that subsequent calls made with the first argument an empty
 205&nbsp;# string will work through the string immediately following that token.  In
 206&nbsp;# this way subsequent calls will work through the string s1 until no tokens
 207&nbsp;# remain.  The separator string s2 may be different from call to call.
 208&nbsp;# When no token remains in s1, an empty value is echoed on stdout.
 209&nbsp;#:end docstring:
 210&nbsp;
 211&nbsp;###;;;autoload
 212&nbsp;function strtok ()
 213&nbsp;{
 214&nbsp; :
 215&nbsp;}
 216&nbsp;
 217&nbsp;#:docstring strtrunc:
 218&nbsp;# Usage: strtrunc $n $s1 {$s2} {$...}
 219&nbsp;#
 220&nbsp;# Used by many functions like strncmp to truncate arguments for comparison.
 221&nbsp;# Echoes the first n characters of each string s1 s2 ... on stdout. 
 222&nbsp;#:end docstring:
 223&nbsp;
 224&nbsp;###;;;autoload
 225&nbsp;function strtrunc ()
 226&nbsp;{
 227&nbsp;    n=$1 ; shift
 228&nbsp;    for z; do
 229&nbsp;        echo "${z:0:$n}"
 230&nbsp;    done
 231&nbsp;}
 232&nbsp;
 233&nbsp;# provide string
 234&nbsp;
 235&nbsp;# string.bash ends here
 236&nbsp;
 237&nbsp;
 238&nbsp;# ========================================================================== #
 239&nbsp;# ==&#62; Everything below here added by the document author.
 240&nbsp;
 241&nbsp;# ==&#62; Suggested use of this script is to delete everything below here,
 242&nbsp;# ==&#62; and "source" this file into your own scripts.
 243&nbsp;
 244&nbsp;# strcat
 245&nbsp;string0=one
 246&nbsp;string1=two
 247&nbsp;echo
 248&nbsp;echo "Testing \"strcat\" function:"
 249&nbsp;echo "Original \"string0\" = $string0"
 250&nbsp;echo "\"string1\" = $string1"
 251&nbsp;strcat string0 string1
 252&nbsp;echo "New \"string0\" = $string0"
 253&nbsp;echo
 254&nbsp;
 255&nbsp;# strlen
 256&nbsp;echo
 257&nbsp;echo "Testing \"strlen\" function:"
 258&nbsp;str=123456789
 259&nbsp;echo "\"str\" = $str"
 260&nbsp;echo -n "Length of \"str\" = "
 261&nbsp;strlen str
 262&nbsp;echo
 263&nbsp;
 264&nbsp;
 265&nbsp;
 266&nbsp;# Exercise:
 267&nbsp;# --------
 268&nbsp;# Add code to test all the other string functions above.
 269&nbsp;
 270&nbsp;
 271&nbsp;exit 0</PRE
></TD
></TR
></TABLE
><HR></DIV
><P
>Michael Zick's complex array example uses the <A
HREF="filearchiv.html#MD5SUMREF"
>md5sum</A
> check sum command to encode directory
      information.</P
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="DIRECTORYINFO"
></A
><P
><B
>Example A-19. Directory information</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#! /bin/bash
   2&nbsp;# directory-info.sh
   3&nbsp;# Parses and lists directory information.
   4&nbsp;
   5&nbsp;# NOTE: Change lines 273 and 353 per "README" file.
   6&nbsp;
   7&nbsp;# Michael Zick is the author of this script.
   8&nbsp;# Used here with his permission.
   9&nbsp;
  10&nbsp;# Controls
  11&nbsp;# If overridden by command arguments, they must be in the order:
  12&nbsp;#   Arg1: "Descriptor Directory"
  13&nbsp;#   Arg2: "Exclude Paths"
  14&nbsp;#   Arg3: "Exclude Directories"
  15&nbsp;#
  16&nbsp;# Environment Settings override Defaults.
  17&nbsp;# Command arguments override Environment Settings.
  18&nbsp;
  19&nbsp;# Default location for content addressed file descriptors.
  20&nbsp;MD5UCFS=${1:-${MD5UCFS:-'/tmpfs/ucfs'}}
  21&nbsp;
  22&nbsp;# Directory paths never to list or enter
  23&nbsp;declare -a \
  24&nbsp;  EXCLUDE_PATHS=${2:-${EXCLUDE_PATHS:-'(/proc /dev /devfs /tmpfs)'}}
  25&nbsp;
  26&nbsp;# Directories never to list or enter
  27&nbsp;declare -a \
  28&nbsp;  EXCLUDE_DIRS=${3:-${EXCLUDE_DIRS:-'(ucfs lost+found tmp wtmp)'}}
  29&nbsp;
  30&nbsp;# Files never to list or enter
  31&nbsp;declare -a \
  32&nbsp;  EXCLUDE_FILES=${3:-${EXCLUDE_FILES:-'(core "Name with Spaces")'}}
  33&nbsp;
  34&nbsp;
  35&nbsp;# Here document used as a comment block.
  36&nbsp;: &#60;&#60;LSfieldsDoc
  37&nbsp;# # # # # List Filesystem Directory Information # # # # #
  38&nbsp;#
  39&nbsp;#	ListDirectory "FileGlob" "Field-Array-Name"
  40&nbsp;# or
  41&nbsp;#	ListDirectory -of "FileGlob" "Field-Array-Filename"
  42&nbsp;#	'-of' meaning 'output to filename'
  43&nbsp;# # # # #
  44&nbsp;
  45&nbsp;String format description based on: ls (GNU fileutils) version 4.0.36
  46&nbsp;
  47&nbsp;Produces a line (or more) formatted:
  48&nbsp;inode permissions hard-links owner group ...
  49&nbsp;32736 -rw-------    1 mszick   mszick
  50&nbsp;
  51&nbsp;size    day month date hh:mm:ss year path
  52&nbsp;2756608 Sun Apr 20 08:53:06 2003 /home/mszick/core
  53&nbsp;
  54&nbsp;Unless it is formatted:
  55&nbsp;inode permissions hard-links owner group ...
  56&nbsp;266705 crw-rw----    1    root  uucp
  57&nbsp;
  58&nbsp;major minor day month date hh:mm:ss year path
  59&nbsp;4,  68 Sun Apr 20 09:27:33 2003 /dev/ttyS4
  60&nbsp;NOTE: that pesky comma after the major number
  61&nbsp;
  62&nbsp;NOTE: the 'path' may be multiple fields:
  63&nbsp;/home/mszick/core
  64&nbsp;/proc/982/fd/0 -&#62; /dev/null
  65&nbsp;/proc/982/fd/1 -&#62; /home/mszick/.xsession-errors
  66&nbsp;/proc/982/fd/13 -&#62; /tmp/tmpfZVVOCs (deleted)
  67&nbsp;/proc/982/fd/7 -&#62; /tmp/kde-mszick/ksycoca
  68&nbsp;/proc/982/fd/8 -&#62; socket:[11586]
  69&nbsp;/proc/982/fd/9 -&#62; pipe:[11588]
  70&nbsp;
  71&nbsp;If that isn't enough to keep your parser guessing,
  72&nbsp;either or both of the path components may be relative:
  73&nbsp;../Built-Shared -&#62; Built-Static
  74&nbsp;../linux-2.4.20.tar.bz2 -&#62; ../../../SRCS/linux-2.4.20.tar.bz2
  75&nbsp;
  76&nbsp;The first character of the 11 (10?) character permissions field:
  77&nbsp;'s' Socket
  78&nbsp;'d' Directory
  79&nbsp;'b' Block device
  80&nbsp;'c' Character device
  81&nbsp;'l' Symbolic link
  82&nbsp;NOTE: Hard links not marked - test for identical inode numbers
  83&nbsp;on identical filesystems.
  84&nbsp;All information about hard linked files are shared, except
  85&nbsp;for the names and the name's location in the directory system.
  86&nbsp;NOTE: A "Hard link" is known as a "File Alias" on some systems.
  87&nbsp;'-' An undistingushed file
  88&nbsp;
  89&nbsp;Followed by three groups of letters for: User, Group, Others
  90&nbsp;Character 1: '-' Not readable; 'r' Readable
  91&nbsp;Character 2: '-' Not writable; 'w' Writable
  92&nbsp;Character 3, User and Group: Combined execute and special
  93&nbsp;'-' Not Executable, Not Special
  94&nbsp;'x' Executable, Not Special
  95&nbsp;'s' Executable, Special
  96&nbsp;'S' Not Executable, Special
  97&nbsp;Character 3, Others: Combined execute and sticky (tacky?)
  98&nbsp;'-' Not Executable, Not Tacky
  99&nbsp;'x' Executable, Not Tacky
 100&nbsp;'t' Executable, Tacky
 101&nbsp;'T' Not Executable, Tacky
 102&nbsp;
 103&nbsp;Followed by an access indicator
 104&nbsp;Haven't tested this one, it may be the eleventh character
 105&nbsp;or it may generate another field
 106&nbsp;' ' No alternate access
 107&nbsp;'+' Alternate access
 108&nbsp;LSfieldsDoc
 109&nbsp;
 110&nbsp;
 111&nbsp;ListDirectory()
 112&nbsp;{
 113&nbsp;	local -a T
 114&nbsp;	local -i of=0		# Default return in variable
 115&nbsp;#	OLD_IFS=$IFS		# Using BASH default ' \t\n'
 116&nbsp;
 117&nbsp;	case "$#" in
 118&nbsp;	3)	case "$1" in
 119&nbsp;		-of)	of=1 ; shift ;;
 120&nbsp;		 * )	return 1 ;;
 121&nbsp;		esac ;;
 122&nbsp;	2)	: ;;		# Poor man's "continue"
 123&nbsp;	*)	return 1 ;;
 124&nbsp;	esac
 125&nbsp;
 126&nbsp;	# NOTE: the (ls) command is NOT quoted (")
 127&nbsp;	T=( $(ls --inode --ignore-backups --almost-all --directory \
 128&nbsp;	--full-time --color=none --time=status --sort=none \
 129&nbsp;	--format=long $1) )
 130&nbsp;
 131&nbsp;	case $of in
 132&nbsp;	# Assign T back to the array whose name was passed as $2
 133&nbsp;		0) eval $2=\( \"\$\{T\[@\]\}\" \) ;;
 134&nbsp;	# Write T into filename passed as $2
 135&nbsp;		1) echo "${T[@]}" &#62; "$2" ;;
 136&nbsp;	esac
 137&nbsp;	return 0
 138&nbsp;   }
 139&nbsp;
 140&nbsp;# # # # # Is that string a legal number? # # # # #
 141&nbsp;#
 142&nbsp;#	IsNumber "Var"
 143&nbsp;# # # # # There has to be a better way, sigh...
 144&nbsp;
 145&nbsp;IsNumber()
 146&nbsp;{
 147&nbsp;	local -i int
 148&nbsp;	if [ $# -eq 0 ]
 149&nbsp;	then
 150&nbsp;		return 1
 151&nbsp;	else
 152&nbsp;		(let int=$1)  2&#62;/dev/null
 153&nbsp;		return $?	# Exit status of the let thread
 154&nbsp;	fi
 155&nbsp;}
 156&nbsp;
 157&nbsp;# # # # # Index Filesystem Directory Information # # # # #
 158&nbsp;#
 159&nbsp;#	IndexList "Field-Array-Name" "Index-Array-Name"
 160&nbsp;# or
 161&nbsp;#	IndexList -if Field-Array-Filename Index-Array-Name
 162&nbsp;#	IndexList -of Field-Array-Name Index-Array-Filename
 163&nbsp;#	IndexList -if -of Field-Array-Filename Index-Array-Filename
 164&nbsp;# # # # #
 165&nbsp;
 166&nbsp;: &#60;&#60;IndexListDoc
 167&nbsp;Walk an array of directory fields produced by ListDirectory
 168&nbsp;
 169&nbsp;Having suppressed the line breaks in an otherwise line oriented
 170&nbsp;report, build an index to the array element which starts each line.
 171&nbsp;
 172&nbsp;Each line gets two index entries, the first element of each line
 173&nbsp;(inode) and the element that holds the pathname of the file.
 174&nbsp;
 175&nbsp;The first index entry pair (Line-Number==0) are informational:
 176&nbsp;Index-Array-Name[0] : Number of "Lines" indexed
 177&nbsp;Index-Array-Name[1] : "Current Line" pointer into Index-Array-Name
 178&nbsp;
 179&nbsp;The following index pairs (if any) hold element indexes into
 180&nbsp;the Field-Array-Name per:
 181&nbsp;Index-Array-Name[Line-Number * 2] : The "inode" field element.
 182&nbsp;NOTE: This distance may be either +11 or +12 elements.
 183&nbsp;Index-Array-Name[(Line-Number * 2) + 1] : The "pathname" element.
 184&nbsp;NOTE: This distance may be a variable number of elements.
 185&nbsp;Next line index pair for Line-Number+1.
 186&nbsp;IndexListDoc
 187&nbsp;
 188&nbsp;
 189&nbsp;
 190&nbsp;IndexList()
 191&nbsp;{
 192&nbsp;	local -a LIST			# Local of listname passed
 193&nbsp;	local -a -i INDEX=( 0 0 )	# Local of index to return
 194&nbsp;	local -i Lidx Lcnt
 195&nbsp;	local -i if=0 of=0		# Default to variable names
 196&nbsp;
 197&nbsp;	case "$#" in			# Simplistic option testing
 198&nbsp;		0) return 1 ;;
 199&nbsp;		1) return 1 ;;
 200&nbsp;		2) : ;;			# Poor man's continue
 201&nbsp;		3) case "$1" in
 202&nbsp;			-if) if=1 ;;
 203&nbsp;			-of) of=1 ;;
 204&nbsp;			 * ) return 1 ;;
 205&nbsp;		   esac ; shift ;;
 206&nbsp;		4) if=1 ; of=1 ; shift ; shift ;;
 207&nbsp;		*) return 1
 208&nbsp;	esac
 209&nbsp;
 210&nbsp;	# Make local copy of list
 211&nbsp;	case "$if" in
 212&nbsp;		0) eval LIST=\( \"\$\{$1\[@\]\}\" \) ;;
 213&nbsp;		1) LIST=( $(cat $1) ) ;;
 214&nbsp;	esac
 215&nbsp;
 216&nbsp;	# Grok (grope?) the array
 217&nbsp;	Lcnt=${#LIST[@]}
 218&nbsp;	Lidx=0
 219&nbsp;	until (( Lidx &#62;= Lcnt ))
 220&nbsp;	do
 221&nbsp;	if IsNumber ${LIST[$Lidx]}
 222&nbsp;	then
 223&nbsp;		local -i inode name
 224&nbsp;		local ft
 225&nbsp;		inode=Lidx
 226&nbsp;		local m=${LIST[$Lidx+2]}	# Hard Links field
 227&nbsp;		ft=${LIST[$Lidx+1]:0:1} 	# Fast-Stat
 228&nbsp;		case $ft in
 229&nbsp;		b)	((Lidx+=12)) ;;		# Block device
 230&nbsp;		c)	((Lidx+=12)) ;;		# Character device
 231&nbsp;		*)	((Lidx+=11)) ;;		# Anything else
 232&nbsp;		esac
 233&nbsp;		name=Lidx
 234&nbsp;		case $ft in
 235&nbsp;		-)	((Lidx+=1)) ;;		# The easy one
 236&nbsp;		b)	((Lidx+=1)) ;;		# Block device
 237&nbsp;		c)	((Lidx+=1)) ;;		# Character device
 238&nbsp;		d)	((Lidx+=1)) ;;		# The other easy one
 239&nbsp;		l)	((Lidx+=3)) ;;		# At LEAST two more fields
 240&nbsp;#  A little more elegance here would handle pipes,
 241&nbsp;#+ sockets, deleted files - later.
 242&nbsp;		*)	until IsNumber ${LIST[$Lidx]} || ((Lidx &#62;= Lcnt))
 243&nbsp;			do
 244&nbsp;				((Lidx+=1))
 245&nbsp;			done
 246&nbsp;			;;			# Not required
 247&nbsp;		esac
 248&nbsp;		INDEX[${#INDEX[*]}]=$inode
 249&nbsp;		INDEX[${#INDEX[*]}]=$name
 250&nbsp;		INDEX[0]=${INDEX[0]}+1		# One more "line" found
 251&nbsp;# echo "Line: ${INDEX[0]} Type: $ft Links: $m Inode: \
 252&nbsp;# ${LIST[$inode]} Name: ${LIST[$name]}"
 253&nbsp;
 254&nbsp;	else
 255&nbsp;		((Lidx+=1))
 256&nbsp;	fi
 257&nbsp;	done
 258&nbsp;	case "$of" in
 259&nbsp;		0) eval $2=\( \"\$\{INDEX\[@\]\}\" \) ;;
 260&nbsp;		1) echo "${INDEX[@]}" &#62; "$2" ;;
 261&nbsp;	esac
 262&nbsp;	return 0				# What could go wrong?
 263&nbsp;}
 264&nbsp;
 265&nbsp;# # # # # Content Identify File # # # # #
 266&nbsp;#
 267&nbsp;#	DigestFile Input-Array-Name Digest-Array-Name
 268&nbsp;# or
 269&nbsp;#	DigestFile -if Input-FileName Digest-Array-Name
 270&nbsp;# # # # #
 271&nbsp;
 272&nbsp;# Here document used as a comment block.
 273&nbsp;: &#60;&#60;DigestFilesDoc
 274&nbsp;
 275&nbsp;The key (no pun intended) to a Unified Content File System (UCFS)
 276&nbsp;is to distinguish the files in the system based on their content.
 277&nbsp;Distinguishing files by their name is just so 20th Century.
 278&nbsp;
 279&nbsp;The content is distinguished by computing a checksum of that content.
 280&nbsp;This version uses the md5sum program to generate a 128 bit checksum
 281&nbsp;representative of the file's contents.
 282&nbsp;There is a chance that two files having different content might
 283&nbsp;generate the same checksum using md5sum (or any checksum).  Should
 284&nbsp;that become a problem, then the use of md5sum can be replace by a
 285&nbsp;cyrptographic signature.  But until then...
 286&nbsp;
 287&nbsp;The md5sum program is documented as outputting three fields (and it
 288&nbsp;does), but when read it appears as two fields (array elements).  This
 289&nbsp;is caused by the lack of whitespace between the second and third field.
 290&nbsp;So this function gropes the md5sum output and returns:
 291&nbsp;	[0]	32 character checksum in hexidecimal (UCFS filename)
 292&nbsp;	[1]	Single character: ' ' text file, '*' binary file
 293&nbsp;	[2]	Filesystem (20th Century Style) name
 294&nbsp;	Note: That name may be the character '-' indicating STDIN read.
 295&nbsp;
 296&nbsp;DigestFilesDoc
 297&nbsp;
 298&nbsp;
 299&nbsp;
 300&nbsp;DigestFile()
 301&nbsp;{
 302&nbsp;	local if=0		# Default, variable name
 303&nbsp;	local -a T1 T2
 304&nbsp;
 305&nbsp;	case "$#" in
 306&nbsp;	3)	case "$1" in
 307&nbsp;		-if)	if=1 ; shift ;;
 308&nbsp;		 * )	return 1 ;;
 309&nbsp;		esac ;;
 310&nbsp;	2)	: ;;		# Poor man's "continue"
 311&nbsp;	*)	return 1 ;;
 312&nbsp;	esac
 313&nbsp;
 314&nbsp;	case $if in
 315&nbsp;	0) eval T1=\( \"\$\{$1\[@\]\}\" \)
 316&nbsp;	   T2=( $(echo ${T1[@]} | md5sum -) )
 317&nbsp;	   ;;
 318&nbsp;	1) T2=( $(md5sum $1) )
 319&nbsp;	   ;;
 320&nbsp;	esac
 321&nbsp;
 322&nbsp;	case ${#T2[@]} in
 323&nbsp;	0) return 1 ;;
 324&nbsp;	1) return 1 ;;
 325&nbsp;	2) case ${T2[1]:0:1} in		# SanScrit-2.0.5
 326&nbsp;	   \*) T2[${#T2[@]}]=${T2[1]:1}
 327&nbsp;	       T2[1]=\*
 328&nbsp;	       ;;
 329&nbsp;	    *) T2[${#T2[@]}]=${T2[1]}
 330&nbsp;	       T2[1]=" "
 331&nbsp;	       ;;
 332&nbsp;	   esac
 333&nbsp;	   ;;
 334&nbsp;	3) : ;; # Assume it worked
 335&nbsp;	*) return 1 ;;
 336&nbsp;	esac
 337&nbsp;
 338&nbsp;	local -i len=${#T2[0]}
 339&nbsp;	if [ $len -ne 32 ] ; then return 1 ; fi
 340&nbsp;	eval $2=\( \"\$\{T2\[@\]\}\" \)
 341&nbsp;}
 342&nbsp;
 343&nbsp;# # # # # Locate File # # # # #
 344&nbsp;#
 345&nbsp;#	LocateFile [-l] FileName Location-Array-Name
 346&nbsp;# or
 347&nbsp;#	LocateFile [-l] -of FileName Location-Array-FileName
 348&nbsp;# # # # #
 349&nbsp;
 350&nbsp;# A file location is Filesystem-id and inode-number
 351&nbsp;
 352&nbsp;# Here document used as a comment block.
 353&nbsp;: &#60;&#60;StatFieldsDoc
 354&nbsp;	Based on stat, version 2.2
 355&nbsp;	stat -t and stat -lt fields
 356&nbsp;	[0]	name
 357&nbsp;	[1]	Total size
 358&nbsp;		File - number of bytes
 359&nbsp;		Symbolic link - string length of pathname
 360&nbsp;	[2]	Number of (512 byte) blocks allocated
 361&nbsp;	[3]	File type and Access rights (hex)
 362&nbsp;	[4]	User ID of owner
 363&nbsp;	[5]	Group ID of owner
 364&nbsp;	[6]	Device number
 365&nbsp;	[7]	Inode number
 366&nbsp;	[8]	Number of hard links
 367&nbsp;	[9]	Device type (if inode device) Major
 368&nbsp;	[10]	Device type (if inode device) Minor
 369&nbsp;	[11]	Time of last access
 370&nbsp;		May be disabled in 'mount' with noatime
 371&nbsp;		atime of files changed by exec, read, pipe, utime, mknod (mmap?)
 372&nbsp;		atime of directories changed by addition/deletion of files
 373&nbsp;	[12]	Time of last modification
 374&nbsp;		mtime of files changed by write, truncate, utime, mknod
 375&nbsp;		mtime of directories changed by addtition/deletion of files
 376&nbsp;	[13]	Time of last change
 377&nbsp;		ctime reflects time of changed inode information (owner, group
 378&nbsp;		permissions, link count
 379&nbsp;-*-*- Per:
 380&nbsp;	Return code: 0
 381&nbsp;	Size of array: 14
 382&nbsp;	Contents of array
 383&nbsp;	Element 0: /home/mszick
 384&nbsp;	Element 1: 4096
 385&nbsp;	Element 2: 8
 386&nbsp;	Element 3: 41e8
 387&nbsp;	Element 4: 500
 388&nbsp;	Element 5: 500
 389&nbsp;	Element 6: 303
 390&nbsp;	Element 7: 32385
 391&nbsp;	Element 8: 22
 392&nbsp;	Element 9: 0
 393&nbsp;	Element 10: 0
 394&nbsp;	Element 11: 1051221030
 395&nbsp;	Element 12: 1051214068
 396&nbsp;	Element 13: 1051214068
 397&nbsp;
 398&nbsp;	For a link in the form of linkname -&#62; realname
 399&nbsp;	stat -t  linkname returns the linkname (link) information
 400&nbsp;	stat -lt linkname returns the realname information
 401&nbsp;
 402&nbsp;	stat -tf and stat -ltf fields
 403&nbsp;	[0]	name
 404&nbsp;	[1]	ID-0?		# Maybe someday, but Linux stat structure
 405&nbsp;	[2]	ID-0?		# does not have either LABEL nor UUID
 406&nbsp;				# fields, currently information must come
 407&nbsp;				# from file-system specific utilities
 408&nbsp;	These will be munged into:
 409&nbsp;	[1]	UUID if possible
 410&nbsp;	[2]	Volume Label if possible
 411&nbsp;	Note: 'mount -l' does return the label and could return the UUID
 412&nbsp;
 413&nbsp;	[3]	Maximum length of filenames
 414&nbsp;	[4]	Filesystem type
 415&nbsp;	[5]	Total blocks in the filesystem
 416&nbsp;	[6]	Free blocks
 417&nbsp;	[7]	Free blocks for non-root user(s)
 418&nbsp;	[8]	Block size of the filesystem
 419&nbsp;	[9]	Total inodes
 420&nbsp;	[10]	Free inodes
 421&nbsp;
 422&nbsp;-*-*- Per:
 423&nbsp;	Return code: 0
 424&nbsp;	Size of array: 11
 425&nbsp;	Contents of array
 426&nbsp;	Element 0: /home/mszick
 427&nbsp;	Element 1: 0
 428&nbsp;	Element 2: 0
 429&nbsp;	Element 3: 255
 430&nbsp;	Element 4: ef53
 431&nbsp;	Element 5: 2581445
 432&nbsp;	Element 6: 2277180
 433&nbsp;	Element 7: 2146050
 434&nbsp;	Element 8: 4096
 435&nbsp;	Element 9: 1311552
 436&nbsp;	Element 10: 1276425
 437&nbsp;
 438&nbsp;StatFieldsDoc
 439&nbsp;
 440&nbsp;
 441&nbsp;#	LocateFile [-l] FileName Location-Array-Name
 442&nbsp;#	LocateFile [-l] -of FileName Location-Array-FileName
 443&nbsp;
 444&nbsp;LocateFile()
 445&nbsp;{
 446&nbsp;	local -a LOC LOC1 LOC2
 447&nbsp;	local lk="" of=0
 448&nbsp;
 449&nbsp;	case "$#" in
 450&nbsp;	0) return 1 ;;
 451&nbsp;	1) return 1 ;;
 452&nbsp;	2) : ;;
 453&nbsp;	*) while (( "$#" &#62; 2 ))
 454&nbsp;	   do
 455&nbsp;	      case "$1" in
 456&nbsp;	       -l) lk=-1 ;;
 457&nbsp;	      -of) of=1 ;;
 458&nbsp;	        *) return 1 ;;
 459&nbsp;	      esac
 460&nbsp;	   shift
 461&nbsp;           done ;;
 462&nbsp;	esac
 463&nbsp;
 464&nbsp;# More Sanscrit-2.0.5
 465&nbsp;      # LOC1=( $(stat -t $lk $1) )
 466&nbsp;      # LOC2=( $(stat -tf $lk $1) )
 467&nbsp;      # Uncomment above two lines if system has "stat" command installed.
 468&nbsp;	LOC=( ${LOC1[@]:0:1} ${LOC1[@]:3:11}
 469&nbsp;	      ${LOC2[@]:1:2} ${LOC2[@]:4:1} )
 470&nbsp;
 471&nbsp;	case "$of" in
 472&nbsp;		0) eval $2=\( \"\$\{LOC\[@\]\}\" \) ;;
 473&nbsp;		1) echo "${LOC[@]}" &#62; "$2" ;;
 474&nbsp;	esac
 475&nbsp;	return 0
 476&nbsp;# Which yields (if you are lucky, and have "stat" installed)
 477&nbsp;# -*-*- Location Discriptor -*-*-
 478&nbsp;#	Return code: 0
 479&nbsp;#	Size of array: 15
 480&nbsp;#	Contents of array
 481&nbsp;#	Element 0: /home/mszick		20th Century name
 482&nbsp;#	Element 1: 41e8			Type and Permissions
 483&nbsp;#	Element 2: 500			User
 484&nbsp;#	Element 3: 500			Group
 485&nbsp;#	Element 4: 303			Device
 486&nbsp;#	Element 5: 32385		inode
 487&nbsp;#	Element 6: 22			Link count
 488&nbsp;#	Element 7: 0			Device Major
 489&nbsp;#	Element 8: 0			Device Minor
 490&nbsp;#	Element 9: 1051224608		Last Access
 491&nbsp;#	Element 10: 1051214068		Last Modify
 492&nbsp;#	Element 11: 1051214068		Last Status
 493&nbsp;#	Element 12: 0			UUID (to be)
 494&nbsp;#	Element 13: 0			Volume Label (to be)
 495&nbsp;#	Element 14: ef53		Filesystem type
 496&nbsp;}
 497&nbsp;
 498&nbsp;
 499&nbsp;
 500&nbsp;# And then there was some test code
 501&nbsp;
 502&nbsp;ListArray() # ListArray Name
 503&nbsp;{
 504&nbsp;	local -a Ta
 505&nbsp;
 506&nbsp;	eval Ta=\( \"\$\{$1\[@\]\}\" \)
 507&nbsp;	echo
 508&nbsp;	echo "-*-*- List of Array -*-*-"
 509&nbsp;	echo "Size of array $1: ${#Ta[*]}"
 510&nbsp;	echo "Contents of array $1:"
 511&nbsp;	for (( i=0 ; i&#60;${#Ta[*]} ; i++ ))
 512&nbsp;	do
 513&nbsp;	    echo -e "\tElement $i: ${Ta[$i]}"
 514&nbsp;	done
 515&nbsp;	return 0
 516&nbsp;}
 517&nbsp;
 518&nbsp;declare -a CUR_DIR
 519&nbsp;# For small arrays
 520&nbsp;ListDirectory "${PWD}" CUR_DIR
 521&nbsp;ListArray CUR_DIR
 522&nbsp;
 523&nbsp;declare -a DIR_DIG
 524&nbsp;DigestFile CUR_DIR DIR_DIG
 525&nbsp;echo "The new \"name\" (checksum) for ${CUR_DIR[9]} is ${DIR_DIG[0]}"
 526&nbsp;
 527&nbsp;declare -a DIR_ENT
 528&nbsp;# BIG_DIR # For really big arrays - use a temporary file in ramdisk
 529&nbsp;# BIG-DIR # ListDirectory -of "${CUR_DIR[11]}/*" "/tmpfs/junk2"
 530&nbsp;ListDirectory "${CUR_DIR[11]}/*" DIR_ENT
 531&nbsp;
 532&nbsp;declare -a DIR_IDX
 533&nbsp;# BIG-DIR # IndexList -if "/tmpfs/junk2" DIR_IDX
 534&nbsp;IndexList DIR_ENT DIR_IDX
 535&nbsp;
 536&nbsp;declare -a IDX_DIG
 537&nbsp;# BIG-DIR # DIR_ENT=( $(cat /tmpfs/junk2) )
 538&nbsp;# BIG-DIR # DigestFile -if /tmpfs/junk2 IDX_DIG
 539&nbsp;DigestFile DIR_ENT IDX_DIG
 540&nbsp;# Small (should) be able to parallize IndexList &#38; DigestFile
 541&nbsp;# Large (should) be able to parallize IndexList &#38; DigestFile &#38; the assignment
 542&nbsp;echo "The \"name\" (checksum) for the contents of ${PWD} is ${IDX_DIG[0]}"
 543&nbsp;
 544&nbsp;declare -a FILE_LOC
 545&nbsp;LocateFile ${PWD} FILE_LOC
 546&nbsp;ListArray FILE_LOC
 547&nbsp;
 548&nbsp;exit 0</PRE
></TD
></TR
></TABLE
><HR></DIV
><P
>Stphane Chazelas demonstrates object-oriented programming in a
      Bash script.</P
><P
>Mariusz Gniazdowski contributed a <A
HREF="internal.html#HASHREF"
>hash</A
>
      library for use in scripts.</P
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="HASHLIB"
></A
><P
><B
>Example A-20. Library of hash functions</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;# Hash:
   2&nbsp;# Hash function library
   3&nbsp;# Author: Mariusz Gniazdowski &#60;mariusz.gn-at-gmail.com&#62;
   4&nbsp;# Date: 2005-04-07
   5&nbsp;
   6&nbsp;# Functions making emulating hashes in Bash a little less painful.
   7&nbsp;
   8&nbsp;
   9&nbsp;#    Limitations:
  10&nbsp;#  * Only global variables are supported.
  11&nbsp;#  * Each hash instance generates one global variable per value.
  12&nbsp;#  * Variable names collisions are possible
  13&nbsp;#+   if you define variable like __hash__hashname_key
  14&nbsp;#  * Keys must use chars that can be part of a Bash variable name
  15&nbsp;#+   (no dashes, periods, etc.).
  16&nbsp;#  * The hash is created as a variable:
  17&nbsp;#    ... hashname_keyname
  18&nbsp;#    So if somone will create hashes like:
  19&nbsp;#      myhash_ + mykey = myhash__mykey
  20&nbsp;#      myhash + _mykey = myhash__mykey
  21&nbsp;#    Then there will be a collision.
  22&nbsp;#    (This should not pose a major problem.)
  23&nbsp;
  24&nbsp;
  25&nbsp;Hash_config_varname_prefix=__hash__
  26&nbsp;
  27&nbsp;
  28&nbsp;# Emulates:  hash[key]=value
  29&nbsp;#
  30&nbsp;# Params:
  31&nbsp;# 1 - hash
  32&nbsp;# 2 - key
  33&nbsp;# 3 - value
  34&nbsp;function hash_set {
  35&nbsp;	eval "${Hash_config_varname_prefix}${1}_${2}=\"${3}\""
  36&nbsp;}
  37&nbsp;
  38&nbsp;
  39&nbsp;# Emulates:  value=hash[key]
  40&nbsp;#
  41&nbsp;# Params:
  42&nbsp;# 1 - hash
  43&nbsp;# 2 - key
  44&nbsp;# 3 - value (name of global variable to set)
  45&nbsp;function hash_get_into {
  46&nbsp;	eval "$3=\"\$${Hash_config_varname_prefix}${1}_${2}\""
  47&nbsp;}
  48&nbsp;
  49&nbsp;
  50&nbsp;# Emulates:  echo hash[key]
  51&nbsp;#
  52&nbsp;# Params:
  53&nbsp;# 1 - hash
  54&nbsp;# 2 - key
  55&nbsp;# 3 - echo params (like -n, for example)
  56&nbsp;function hash_echo {
  57&nbsp;	eval "echo $3 \"\$${Hash_config_varname_prefix}${1}_${2}\""
  58&nbsp;}
  59&nbsp;
  60&nbsp;
  61&nbsp;# Emulates:  hash1[key1]=hash2[key2]
  62&nbsp;#
  63&nbsp;# Params:
  64&nbsp;# 1 - hash1
  65&nbsp;# 2 - key1
  66&nbsp;# 3 - hash2
  67&nbsp;# 4 - key2
  68&nbsp;function hash_copy {
  69&nbsp;eval "${Hash_config_varname_prefix}${1}_${2}\
  70&nbsp;=\"\$${Hash_config_varname_prefix}${3}_${4}\""
  71&nbsp;}
  72&nbsp;
  73&nbsp;
  74&nbsp;# Emulates:  hash[keyN-1]=hash[key2]=...hash[key1]
  75&nbsp;#
  76&nbsp;# Copies first key to rest of keys.
  77&nbsp;#
  78&nbsp;# Params:
  79&nbsp;# 1 - hash1
  80&nbsp;# 2 - key1
  81&nbsp;# 3 - key2
  82&nbsp;# . . .
  83&nbsp;# N - keyN
  84&nbsp;function hash_dup {
  85&nbsp;  local hashName="$1" keyName="$2"
  86&nbsp;  shift 2
  87&nbsp;  until [ ${#} -le 0 ]; do
  88&nbsp;    eval "${Hash_config_varname_prefix}${hashName}_${1}\
  89&nbsp;=\"\$${Hash_config_varname_prefix}${hashName}_${keyName}\""
  90&nbsp;  shift;
  91&nbsp;  done;
  92&nbsp;}
  93&nbsp;
  94&nbsp;
  95&nbsp;# Emulates:  unset hash[key]
  96&nbsp;#
  97&nbsp;# Params:
  98&nbsp;# 1 - hash
  99&nbsp;# 2 - key
 100&nbsp;function hash_unset {
 101&nbsp;	eval "unset ${Hash_config_varname_prefix}${1}_${2}"
 102&nbsp;}
 103&nbsp;
 104&nbsp;
 105&nbsp;# Emulates something similar to:  ref=&#38;hash[key]
 106&nbsp;#
 107&nbsp;# The reference is name of the variable in which value is held.
 108&nbsp;#
 109&nbsp;# Params:
 110&nbsp;# 1 - hash
 111&nbsp;# 2 - key
 112&nbsp;# 3 - ref - Name of global variable to set.
 113&nbsp;function hash_get_ref_into {
 114&nbsp;	eval "$3=\"${Hash_config_varname_prefix}${1}_${2}\""
 115&nbsp;}
 116&nbsp;
 117&nbsp;
 118&nbsp;# Emulates something similar to:  echo &#38;hash[key]
 119&nbsp;#
 120&nbsp;# That reference is name of variable in which value is held.
 121&nbsp;#
 122&nbsp;# Params:
 123&nbsp;# 1 - hash
 124&nbsp;# 2 - key
 125&nbsp;# 3 - echo params (like -n for example)
 126&nbsp;function hash_echo_ref {
 127&nbsp;	eval "echo $3 \"${Hash_config_varname_prefix}${1}_${2}\""
 128&nbsp;}
 129&nbsp;
 130&nbsp;
 131&nbsp;
 132&nbsp;# Emulates something similar to:  $$hash[key](param1, param2, ...)
 133&nbsp;#
 134&nbsp;# Params:
 135&nbsp;# 1 - hash
 136&nbsp;# 2 - key
 137&nbsp;# 3,4, ... - Function parameters
 138&nbsp;function hash_call {
 139&nbsp;  local hash key
 140&nbsp;  hash=$1
 141&nbsp;  key=$2
 142&nbsp;  shift 2
 143&nbsp;  eval "eval \"\$${Hash_config_varname_prefix}${hash}_${key} \\\"\\\$@\\\"\""
 144&nbsp;}
 145&nbsp;
 146&nbsp;
 147&nbsp;# Emulates something similar to:  isset(hash[key]) or hash[key]==NULL
 148&nbsp;#
 149&nbsp;# Params:
 150&nbsp;# 1 - hash
 151&nbsp;# 2 - key
 152&nbsp;# Returns:
 153&nbsp;# 0 - there is such key
 154&nbsp;# 1 - there is no such key
 155&nbsp;function hash_is_set {
 156&nbsp;  eval "if [[ \"\${${Hash_config_varname_prefix}${1}_${2}-a}\" = \"a\" &#38;&#38; 
 157&nbsp;  \"\${${Hash_config_varname_prefix}${1}_${2}-b}\" = \"b\" ]]
 158&nbsp;    then return 1; else return 0; fi"
 159&nbsp;}
 160&nbsp;
 161&nbsp;
 162&nbsp;# Emulates something similar to:
 163&nbsp;#   foreach($hash as $key =&#62; $value) { fun($key,$value); }
 164&nbsp;#
 165&nbsp;# It is possible to write different variations of this function.
 166&nbsp;# Here we use a function call to make it as "generic" as possible.
 167&nbsp;#
 168&nbsp;# Params:
 169&nbsp;# 1 - hash
 170&nbsp;# 2 - function name
 171&nbsp;function hash_foreach {
 172&nbsp;  local keyname oldIFS="$IFS"
 173&nbsp;  IFS=' '
 174&nbsp;  for i in $(eval "echo \${!${Hash_config_varname_prefix}${1}_*}"); do
 175&nbsp;    keyname=$(eval "echo \${i##${Hash_config_varname_prefix}${1}_}")
 176&nbsp;    eval "$2 $keyname \"\$$i\""
 177&nbsp;  done
 178&nbsp;IFS="$oldIFS"
 179&nbsp;}
 180&nbsp;
 181&nbsp;#  NOTE: In lines 103 and 116, ampersand changed.
 182&nbsp;#  But, it doesn't matter, because these are comment lines anyhow.</PRE
></TD
></TR
></TABLE
><HR></DIV
><P
>Here is an example script using the foregoing hash library.</P
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="HASHEXAMPLE"
></A
><P
><B
>Example A-21. Colorizing text using hash functions</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#!/bin/bash
   2&nbsp;# hash-example.sh: Colorizing text.
   3&nbsp;# Author: Mariusz Gniazdowski &#60;mariusz.gn-at-gmail.com&#62;
   4&nbsp;
   5&nbsp;. Hash.lib      # Load the library of functions.
   6&nbsp;
   7&nbsp;hash_set colors red          "\033[0;31m"
   8&nbsp;hash_set colors blue         "\033[0;34m"
   9&nbsp;hash_set colors light_blue   "\033[1;34m"
  10&nbsp;hash_set colors light_red    "\033[1;31m"
  11&nbsp;hash_set colors cyan         "\033[0;36m"
  12&nbsp;hash_set colors light_green  "\033[1;32m"
  13&nbsp;hash_set colors light_gray   "\033[0;37m"
  14&nbsp;hash_set colors green        "\033[0;32m"
  15&nbsp;hash_set colors yellow       "\033[1;33m"
  16&nbsp;hash_set colors light_purple "\033[1;35m"
  17&nbsp;hash_set colors purple       "\033[0;35m"
  18&nbsp;hash_set colors reset_color  "\033[0;00m"
  19&nbsp;
  20&nbsp;
  21&nbsp;# $1 - keyname
  22&nbsp;# $2 - value
  23&nbsp;try_colors() {
  24&nbsp;	echo -en "$2"
  25&nbsp;	echo "This line is $1."
  26&nbsp;}
  27&nbsp;hash_foreach colors try_colors
  28&nbsp;hash_echo colors reset_color -en
  29&nbsp;
  30&nbsp;echo -e '\nLet us overwrite some colors with yellow.\n'
  31&nbsp;# It's hard to read yellow text on some terminals.
  32&nbsp;hash_dup colors yellow   red light_green blue green light_gray cyan
  33&nbsp;hash_foreach colors try_colors
  34&nbsp;hash_echo colors reset_color -en
  35&nbsp;
  36&nbsp;echo -e '\nLet us delete them and try colors once more . . .\n'
  37&nbsp;
  38&nbsp;for i in red light_green blue green light_gray cyan; do
  39&nbsp;	hash_unset colors $i
  40&nbsp;done
  41&nbsp;hash_foreach colors try_colors
  42&nbsp;hash_echo colors reset_color -en
  43&nbsp;
  44&nbsp;hash_set other txt "Other examples . . ."
  45&nbsp;hash_echo other txt
  46&nbsp;hash_get_into other txt text
  47&nbsp;echo $text
  48&nbsp;
  49&nbsp;hash_set other my_fun try_colors
  50&nbsp;hash_call other my_fun   purple "`hash_echo colors purple`"
  51&nbsp;hash_echo colors reset_color -en
  52&nbsp;
  53&nbsp;echo; echo "Back to normal?"; echo
  54&nbsp;
  55&nbsp;exit $?
  56&nbsp;
  57&nbsp;#  On some terminals, the "light" colors print in bold,
  58&nbsp;#  and end up looking darker than the normal ones.
  59&nbsp;#  Why is this?
  60&nbsp;</PRE
></TD
></TR
></TABLE
><HR></DIV
><P
><A
NAME="HASHEX2_0"
></A
>An example illustrating the mechanics
      of hashing, but from a different point of view.</P
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="HASHEX2"
></A
><P
><B
>Example A-22. More on hash functions</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#!/bin/bash
   2&nbsp;# $Id: ha.sh,v 1.2 2005/04/21 23:24:26 oliver Exp $
   3&nbsp;# Copyright 2005 Oliver Beckstein
   4&nbsp;# Released under the GNU Public License
   5&nbsp;# Author of script granted permission for inclusion in ABS Guide.
   6&nbsp;# (Thank you!)
   7&nbsp;
   8&nbsp;#----------------------------------------------------------------
   9&nbsp;# pseudo hash based on indirect parameter expansion
  10&nbsp;# API: access through functions:
  11&nbsp;# 
  12&nbsp;# create the hash:
  13&nbsp;#  
  14&nbsp;#      newhash Lovers
  15&nbsp;#
  16&nbsp;# add entries (note single quotes for spaces)
  17&nbsp;#    
  18&nbsp;#      addhash Lovers Tristan Isolde
  19&nbsp;#      addhash Lovers 'Romeo Montague' 'Juliet Capulet'
  20&nbsp;#
  21&nbsp;# access value by key
  22&nbsp;#
  23&nbsp;#      gethash Lovers Tristan   ----&#62;  Isolde
  24&nbsp;#
  25&nbsp;# show all keys
  26&nbsp;#
  27&nbsp;#      keyshash Lovers         ----&#62; 'Tristan'  'Romeo Montague'
  28&nbsp;#
  29&nbsp;#
  30&nbsp;# Convention: instead of perls' foo{bar} = boing' syntax,
  31&nbsp;# use
  32&nbsp;#       '_foo_bar=boing' (two underscores, no spaces)
  33&nbsp;#
  34&nbsp;# 1) store key   in _NAME_keys[]
  35&nbsp;# 2) store value in _NAME_values[] using the same integer index
  36&nbsp;# The integer index for the last entry is _NAME_ptr
  37&nbsp;#
  38&nbsp;# NOTE: No error or sanity checks, just bare bones.
  39&nbsp;
  40&nbsp;
  41&nbsp;function _inihash () {
  42&nbsp;    # private function
  43&nbsp;    # call at the beginning of each procedure
  44&nbsp;    # defines: _keys _values _ptr
  45&nbsp;    #
  46&nbsp;    # Usage: _inihash NAME
  47&nbsp;    local name=$1
  48&nbsp;    _keys=_${name}_keys
  49&nbsp;    _values=_${name}_values
  50&nbsp;    _ptr=_${name}_ptr
  51&nbsp;}
  52&nbsp;
  53&nbsp;function newhash () {
  54&nbsp;    # Usage: newhash NAME
  55&nbsp;    #        NAME should not contain spaces or dots.
  56&nbsp;    #        Actually: it must be a legal name for a Bash variable.
  57&nbsp;    # We rely on Bash automatically recognising arrays.
  58&nbsp;    local name=$1 
  59&nbsp;    local _keys _values _ptr
  60&nbsp;    _inihash ${name}
  61&nbsp;    eval ${_ptr}=0
  62&nbsp;}
  63&nbsp;
  64&nbsp;
  65&nbsp;function addhash () {
  66&nbsp;    # Usage: addhash NAME KEY 'VALUE with spaces'
  67&nbsp;    #        arguments with spaces need to be quoted with single quotes ''
  68&nbsp;    local name=$1 k="$2" v="$3" 
  69&nbsp;    local _keys _values _ptr
  70&nbsp;    _inihash ${name}
  71&nbsp;
  72&nbsp;    #echo "DEBUG(addhash): ${_ptr}=${!_ptr}"
  73&nbsp;
  74&nbsp;    eval let ${_ptr}=${_ptr}+1
  75&nbsp;    eval "$_keys[${!_ptr}]=\"${k}\""
  76&nbsp;    eval "$_values[${!_ptr}]=\"${v}\""
  77&nbsp;}
  78&nbsp;
  79&nbsp;function gethash () {
  80&nbsp;    #  Usage: gethash NAME KEY
  81&nbsp;    #         Returns boing
  82&nbsp;    #         ERR=0 if entry found, 1 otherwise
  83&nbsp;    #  That's not a proper hash --
  84&nbsp;    #+ we simply linearly search through the keys.
  85&nbsp;    local name=$1 key="$2" 
  86&nbsp;    local _keys _values _ptr 
  87&nbsp;    local k v i found h
  88&nbsp;    _inihash ${name}
  89&nbsp;    
  90&nbsp;    # _ptr holds the highest index in the hash
  91&nbsp;    found=0
  92&nbsp;
  93&nbsp;    for i in $(seq 1 ${!_ptr}); do
  94&nbsp;	h="\${${_keys}[${i}]}"  #  Safer to do it in two steps,
  95&nbsp;	eval k=${h}             #+ especially when quoting for spaces.
  96&nbsp;	if [ "${k}" = "${key}" ]; then found=1; break; fi
  97&nbsp;    done;
  98&nbsp;
  99&nbsp;    [ ${found} = 0 ] &#38;&#38; return 1;
 100&nbsp;    # else: i is the index that matches the key
 101&nbsp;    h="\${${_values}[${i}]}"
 102&nbsp;    eval echo "${h}"
 103&nbsp;    return 0;	
 104&nbsp;}
 105&nbsp;
 106&nbsp;function keyshash () {
 107&nbsp;    # Usage: keyshash NAME
 108&nbsp;    # Returns list of all keys defined for hash name.
 109&nbsp;    local name=$1 key="$2" 
 110&nbsp;    local _keys _values _ptr 
 111&nbsp;    local k i h
 112&nbsp;    _inihash ${name}
 113&nbsp;    
 114&nbsp;    # _ptr holds the highest index in the hash
 115&nbsp;    for i in $(seq 1 ${!_ptr}); do
 116&nbsp;	h="\${${_keys}[${i}]}"   #  Safer to do it in two steps,
 117&nbsp;	eval k=${h}              #+ especially when quoting for spaces.
 118&nbsp;	echo -n "'${k}' "
 119&nbsp;    done;
 120&nbsp;}
 121&nbsp;
 122&nbsp;
 123&nbsp;# -----------------------------------------------------------------------
 124&nbsp;
 125&nbsp;# Now, let's test it.
 126&nbsp;# (Per comments at the beginning of the script.)
 127&nbsp;newhash Lovers
 128&nbsp;addhash Lovers Tristan Isolde
 129&nbsp;addhash Lovers 'Romeo Montague' 'Juliet Capulet'
 130&nbsp;
 131&nbsp;# Output results.
 132&nbsp;echo
 133&nbsp;gethash Lovers Tristan      # Isolde
 134&nbsp;echo
 135&nbsp;keyshash Lovers             # 'Tristan' 'Romeo Montague'
 136&nbsp;echo; echo
 137&nbsp;
 138&nbsp;
 139&nbsp;exit 0
 140&nbsp;
 141&nbsp;# Exercise:
 142&nbsp;# --------
 143&nbsp;
 144&nbsp;# Add error checks to the functions.</PRE
></TD
></TR
></TABLE
><HR></DIV
><P
>Now for a script that installs and mounts
      those cute USB keychain solid-state <SPAN
CLASS="QUOTE"
>"hard drives."</SPAN
></P
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="USBINST"
></A
><P
><B
>Example A-23. Mounting USB keychain storage devices</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#!/bin/bash
   2&nbsp;# ==&#62; usb.sh
   3&nbsp;# ==&#62; Script for mounting and installing pen/keychain USB storage devices.
   4&nbsp;# ==&#62; Runs as root at system startup (see below).
   5&nbsp;# ==&#62;
   6&nbsp;# ==&#62; Newer Linux distros (2004 or later) autodetect
   7&nbsp;# ==&#62; and install USB pen drives, and therefore don't need this script.
   8&nbsp;# ==&#62; But, it's still instructive.
   9&nbsp; 
  10&nbsp;#  This code is free software covered by GNU GPL license version 2 or above.
  11&nbsp;#  Please refer to http://www.gnu.org/ for the full license text.
  12&nbsp;#
  13&nbsp;#  Some code lifted from usb-mount by Michael Hamilton's usb-mount (LGPL)
  14&nbsp;#+ see http://users.actrix.co.nz/michael/usbmount.html
  15&nbsp;#
  16&nbsp;#  INSTALL
  17&nbsp;#  -------
  18&nbsp;#  Put this in /etc/hotplug/usb/diskonkey.
  19&nbsp;#  Then look in /etc/hotplug/usb.distmap, and copy all usb-storage entries
  20&nbsp;#+ into /etc/hotplug/usb.usermap, substituting "usb-storage" for "diskonkey".
  21&nbsp;#  Otherwise this code is only run during the kernel module invocation/removal
  22&nbsp;#+ (at least in my tests), which defeats the purpose.
  23&nbsp;#
  24&nbsp;#  TODO
  25&nbsp;#  ----
  26&nbsp;#  Handle more than one diskonkey device at one time (e.g. /dev/diskonkey1
  27&nbsp;#+ and /mnt/diskonkey1), etc. The biggest problem here is the handling in
  28&nbsp;#+ devlabel, which I haven't yet tried.
  29&nbsp;#
  30&nbsp;#  AUTHOR and SUPPORT
  31&nbsp;#  ------------------
  32&nbsp;#  Konstantin Riabitsev, &#60;icon linux duke edu&#62;.
  33&nbsp;#  Send any problem reports to my email address at the moment.
  34&nbsp;#
  35&nbsp;# ==&#62; Comments added by ABS Guide author.
  36&nbsp;
  37&nbsp;
  38&nbsp;
  39&nbsp;SYMLINKDEV=/dev/diskonkey
  40&nbsp;MOUNTPOINT=/mnt/diskonkey
  41&nbsp;DEVLABEL=/sbin/devlabel
  42&nbsp;DEVLABELCONFIG=/etc/sysconfig/devlabel
  43&nbsp;IAM=$0
  44&nbsp;
  45&nbsp;##
  46&nbsp;# Functions lifted near-verbatim from usb-mount code.
  47&nbsp;#
  48&nbsp;function allAttachedScsiUsb {
  49&nbsp;  find /proc/scsi/ -path '/proc/scsi/usb-storage*' -type f |
  50&nbsp;  xargs grep -l 'Attached: Yes'
  51&nbsp;}
  52&nbsp;function scsiDevFromScsiUsb {
  53&nbsp;  echo $1 | awk -F"[-/]" '{ n=$(NF-1);
  54&nbsp;  print "/dev/sd" substr("abcdefghijklmnopqrstuvwxyz", n+1, 1) }'
  55&nbsp;}
  56&nbsp;
  57&nbsp;if [ "${ACTION}" = "add" ] &#38;&#38; [ -f "${DEVICE}" ]; then
  58&nbsp;    ##
  59&nbsp;    # lifted from usbcam code.
  60&nbsp;    #
  61&nbsp;    if [ -f /var/run/console.lock ]; then
  62&nbsp;        CONSOLEOWNER=`cat /var/run/console.lock`
  63&nbsp;    elif [ -f /var/lock/console.lock ]; then
  64&nbsp;        CONSOLEOWNER=`cat /var/lock/console.lock`
  65&nbsp;    else
  66&nbsp;        CONSOLEOWNER=
  67&nbsp;    fi
  68&nbsp;    for procEntry in $(allAttachedScsiUsb); do
  69&nbsp;        scsiDev=$(scsiDevFromScsiUsb $procEntry)
  70&nbsp;        #  Some bug with usb-storage?
  71&nbsp;        #  Partitions are not in /proc/partitions until they are accessed
  72&nbsp;        #+ somehow.
  73&nbsp;        /sbin/fdisk -l $scsiDev &#62;/dev/null
  74&nbsp;        ##
  75&nbsp;        #  Most devices have partitioning info, so the data would be on
  76&nbsp;        #+ /dev/sd?1. However, some stupider ones don't have any partitioning
  77&nbsp;        #+ and use the entire device for data storage. This tries to
  78&nbsp;        #+ guess semi-intelligently if we have a /dev/sd?1 and if not, then
  79&nbsp;        #+ it uses the entire device and hopes for the better.
  80&nbsp;        #
  81&nbsp;        if grep -q `basename $scsiDev`1 /proc/partitions; then
  82&nbsp;            part="$scsiDev""1"
  83&nbsp;        else
  84&nbsp;            part=$scsiDev
  85&nbsp;        fi
  86&nbsp;        ##
  87&nbsp;        #  Change ownership of the partition to the console user so they can
  88&nbsp;        #+ mount it.
  89&nbsp;        #
  90&nbsp;        if [ ! -z "$CONSOLEOWNER" ]; then
  91&nbsp;            chown $CONSOLEOWNER:disk $part
  92&nbsp;        fi
  93&nbsp;        ##
  94&nbsp;        # This checks if we already have this UUID defined with devlabel.
  95&nbsp;        # If not, it then adds the device to the list.
  96&nbsp;        #
  97&nbsp;        prodid=`$DEVLABEL printid -d $part`
  98&nbsp;        if ! grep -q $prodid $DEVLABELCONFIG; then
  99&nbsp;            # cross our fingers and hope it works
 100&nbsp;            $DEVLABEL add -d $part -s $SYMLINKDEV 2&#62;/dev/null
 101&nbsp;        fi
 102&nbsp;        ##
 103&nbsp;        # Check if the mount point exists and create if it doesn't.
 104&nbsp;        #
 105&nbsp;        if [ ! -e $MOUNTPOINT ]; then
 106&nbsp;            mkdir -p $MOUNTPOINT
 107&nbsp;        fi
 108&nbsp;        ##
 109&nbsp;        # Take care of /etc/fstab so mounting is easy.
 110&nbsp;        #
 111&nbsp;        if ! grep -q "^$SYMLINKDEV" /etc/fstab; then
 112&nbsp;            # Add an fstab entry
 113&nbsp;            echo -e \
 114&nbsp;                "$SYMLINKDEV\t\t$MOUNTPOINT\t\tauto\tnoauto,owner,kudzu 0 0" \
 115&nbsp;                &#62;&#62; /etc/fstab
 116&nbsp;        fi
 117&nbsp;    done
 118&nbsp;    if [ ! -z "$REMOVER" ]; then
 119&nbsp;        ##
 120&nbsp;        # Make sure this script is triggered on device removal.
 121&nbsp;        #
 122&nbsp;        mkdir -p `dirname $REMOVER`
 123&nbsp;        ln -s $IAM $REMOVER
 124&nbsp;    fi
 125&nbsp;elif [ "${ACTION}" = "remove" ]; then
 126&nbsp;    ##
 127&nbsp;    # If the device is mounted, unmount it cleanly.
 128&nbsp;    #
 129&nbsp;    if grep -q "$MOUNTPOINT" /etc/mtab; then
 130&nbsp;        # unmount cleanly
 131&nbsp;        umount -l $MOUNTPOINT
 132&nbsp;    fi
 133&nbsp;    ##
 134&nbsp;    # Remove it from /etc/fstab if it's there.
 135&nbsp;    #
 136&nbsp;    if grep -q "^$SYMLINKDEV" /etc/fstab; then
 137&nbsp;        grep -v "^$SYMLINKDEV" /etc/fstab &#62; /etc/.fstab.new
 138&nbsp;        mv -f /etc/.fstab.new /etc/fstab
 139&nbsp;    fi
 140&nbsp;fi
 141&nbsp;
 142&nbsp;exit 0</PRE
></TD
></TR
></TABLE
><HR></DIV
><P
>Converting a text file to HTML format.</P
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="TOHTML"
></A
><P
><B
>Example A-24. Converting to HTML</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#!/bin/bash
   2&nbsp;# tohtml.sh [v. 0.2.01, reldate: 04/13/12, a teeny bit less buggy]
   3&nbsp;
   4&nbsp;# Convert a text file to HTML format.
   5&nbsp;# Author: Mendel Cooper
   6&nbsp;# License: GPL3
   7&nbsp;# Usage: sh tohtml.sh &#60; textfile &#62; htmlfile
   8&nbsp;# Script can easily be modified to accept source and target filenames.
   9&nbsp;
  10&nbsp;#    Assumptions:
  11&nbsp;# 1) Paragraphs in (target) text file are separated by a blank line.
  12&nbsp;# 2) Jpeg images (*.jpg) are located in "images" subdirectory.
  13&nbsp;#    In the target file, the image names are enclosed in square brackets,
  14&nbsp;#    for example, [image01.jpg].
  15&nbsp;# 3) Emphasized (italic) phrases begin with a space+underscore
  16&nbsp;#+   or the first character on the line is an underscore,
  17&nbsp;#+   and end with an underscore+space or underscore+end-of-line.
  18&nbsp;
  19&nbsp;
  20&nbsp;# Settings
  21&nbsp;FNTSIZE=2        # Small-medium font size
  22&nbsp;IMGDIR="images"  # Image directory
  23&nbsp;# Headers
  24&nbsp;HDR01='&#60;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"&#62;'
  25&nbsp;HDR02='&#60;!-- Converted to HTML by ***tohtml.sh*** script --&#62;'
  26&nbsp;HDR03='&#60;!-- script author: M. Leo Cooper &#60;thegrendel.abs@gmail.com&#62; --&#62;'
  27&nbsp;HDR10='&#60;html&#62;'
  28&nbsp;HDR11='&#60;head&#62;'
  29&nbsp;HDR11a='&#60;/head&#62;'
  30&nbsp;HDR12a='&#60;title&#62;'
  31&nbsp;HDR12b='&#60;/title&#62;'
  32&nbsp;HDR121='&#60;META NAME="GENERATOR" CONTENT="tohtml.sh script"&#62;'
  33&nbsp;HDR13='&#60;body bgcolor="#dddddd"&#62;'   # Change background color to suit.
  34&nbsp;HDR14a='&#60;font size='
  35&nbsp;HDR14b='&#62;'
  36&nbsp;# Footers
  37&nbsp;FTR10='&#60;/body&#62;'
  38&nbsp;FTR11='&#60;/html&#62;'
  39&nbsp;# Tags
  40&nbsp;BOLD="&#60;b&#62;"
  41&nbsp;CENTER="&#60;center&#62;"
  42&nbsp;END_CENTER="&#60;/center&#62;"
  43&nbsp;LF="&#60;br&#62;"
  44&nbsp;
  45&nbsp;
  46&nbsp;write_headers ()
  47&nbsp;  {
  48&nbsp;  echo "$HDR01"
  49&nbsp;  echo
  50&nbsp;  echo "$HDR02"
  51&nbsp;  echo "$HDR03"
  52&nbsp;  echo
  53&nbsp;  echo
  54&nbsp;  echo "$HDR10"
  55&nbsp;  echo "$HDR11"
  56&nbsp;  echo "$HDR121"
  57&nbsp;  echo "$HDR11a"
  58&nbsp;  echo "$HDR13"
  59&nbsp;  echo
  60&nbsp;  echo -n "$HDR14a"
  61&nbsp;  echo -n "$FNTSIZE"
  62&nbsp;  echo "$HDR14b"
  63&nbsp;  echo
  64&nbsp;  echo "$BOLD"        # Everything in bold (more easily readable).
  65&nbsp;  }
  66&nbsp;
  67&nbsp;
  68&nbsp;process_text ()
  69&nbsp;  {
  70&nbsp;  while read line     # Read one line at a time.
  71&nbsp;  do
  72&nbsp;    {
  73&nbsp;    if [ ! "$line" ]  # Blank line?
  74&nbsp;    then              # Then new paragraph must follow.
  75&nbsp;      echo
  76&nbsp;      echo "$LF"      # Insert two &#60;br&#62; tags.
  77&nbsp;      echo "$LF"
  78&nbsp;      echo
  79&nbsp;      continue        # Skip the underscore test.
  80&nbsp;    else              # Otherwise . . .
  81&nbsp;
  82&nbsp;      if [[ "$line" =~ \[*jpg\] ]]    # Is a graphic?
  83&nbsp;      then                            # Strip away brackets.
  84&nbsp;        temp=$( echo "$line" | sed -e 's/\[//' -e 's/\]//' )
  85&nbsp;        line=""$CENTER" &#60;img src="\"$IMGDIR"/$temp\"&#62; "$END_CENTER" "
  86&nbsp;                                      # Add image tag.
  87&nbsp;                                      # And, center it.
  88&nbsp;      fi
  89&nbsp;
  90&nbsp;    fi
  91&nbsp;
  92&nbsp;
  93&nbsp;    echo "$line" | grep -q _
  94&nbsp;    if [ "$?" -eq 0 ]    # If line contains underscore ...
  95&nbsp;    then
  96&nbsp;      # ===================================================
  97&nbsp;      # Convert underscored phrase to italics.
  98&nbsp;      temp=$( echo "$line" |
  99&nbsp;              sed -e 's/ _/ &#60;i&#62;/' -e 's/_/&#60;\/i&#62; /' |
 100&nbsp;              sed -e 's/^_/&#60;i&#62;/'  -e 's/_/&#60;\/i&#62;/' )
 101&nbsp;      #  Process only underscores prefixed by space,
 102&nbsp;      #+ or at beginning or end of line.
 103&nbsp;      #  Do not convert underscores embedded within a word!
 104&nbsp;      line="$temp"
 105&nbsp;      # Slows script execution. Can be optimized?
 106&nbsp;      # ===================================================
 107&nbsp;    fi
 108&nbsp;
 109&nbsp;
 110&nbsp;   
 111&nbsp;#   echo
 112&nbsp;    echo "$line"
 113&nbsp;#   echo
 114&nbsp;#   Don't want extra blank lines in generated text!
 115&nbsp;    } # End while
 116&nbsp;  done
 117&nbsp;  }   # End process_text ()
 118&nbsp;
 119&nbsp;
 120&nbsp;write_footers ()  # Termination tags.
 121&nbsp;  {
 122&nbsp;  echo "$FTR10"
 123&nbsp;  echo "$FTR11"
 124&nbsp;  }
 125&nbsp;
 126&nbsp;
 127&nbsp;# main () {
 128&nbsp;# =========
 129&nbsp;write_headers
 130&nbsp;process_text
 131&nbsp;write_footers
 132&nbsp;# =========
 133&nbsp;#         }
 134&nbsp;
 135&nbsp;exit $?
 136&nbsp;
 137&nbsp;#  Exercises:
 138&nbsp;#  ---------
 139&nbsp;#  1) Fixup: Check for closing underscore before a comma or period.
 140&nbsp;#  2) Add a test for the presence of a closing underscore
 141&nbsp;#+    in phrases to be italicized.</PRE
></TD
></TR
></TABLE
><HR></DIV
><P
>Here is something to warm the hearts of webmasters and mistresses:
      a script that saves weblogs.</P
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="ARCHIVWEBLOGS"
></A
><P
><B
>Example A-25. Preserving weblogs</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#!/bin/bash
   2&nbsp;# archiveweblogs.sh v1.0
   3&nbsp;
   4&nbsp;# Troy Engel &#60;tengel@fluid.com&#62;
   5&nbsp;# Slightly modified by document author.
   6&nbsp;# Used with permission.
   7&nbsp;#
   8&nbsp;#  This script will preserve the normally rotated and
   9&nbsp;#+ thrown away weblogs from a default RedHat/Apache installation.
  10&nbsp;#  It will save the files with a date/time stamp in the filename,
  11&nbsp;#+ bzipped, to a given directory.
  12&nbsp;#
  13&nbsp;#  Run this from crontab nightly at an off hour,
  14&nbsp;#+ as bzip2 can suck up some serious CPU on huge logs:
  15&nbsp;#  0 2 * * * /opt/sbin/archiveweblogs.sh
  16&nbsp;
  17&nbsp;
  18&nbsp;PROBLEM=66
  19&nbsp;
  20&nbsp;# Set this to your backup dir.
  21&nbsp;BKP_DIR=/opt/backups/weblogs
  22&nbsp;
  23&nbsp;# Default Apache/RedHat stuff
  24&nbsp;LOG_DAYS="4 3 2 1"
  25&nbsp;LOG_DIR=/var/log/httpd
  26&nbsp;LOG_FILES="access_log error_log"
  27&nbsp;
  28&nbsp;# Default RedHat program locations
  29&nbsp;LS=/bin/ls
  30&nbsp;MV=/bin/mv
  31&nbsp;ID=/usr/bin/id
  32&nbsp;CUT=/bin/cut
  33&nbsp;COL=/usr/bin/column
  34&nbsp;BZ2=/usr/bin/bzip2
  35&nbsp;
  36&nbsp;# Are we root?
  37&nbsp;USER=`$ID -u`
  38&nbsp;if [ "X$USER" != "X0" ]; then
  39&nbsp;  echo "PANIC: Only root can run this script!"
  40&nbsp;  exit $PROBLEM
  41&nbsp;fi
  42&nbsp;
  43&nbsp;# Backup dir exists/writable?
  44&nbsp;if [ ! -x $BKP_DIR ]; then
  45&nbsp;  echo "PANIC: $BKP_DIR doesn't exist or isn't writable!"
  46&nbsp;  exit $PROBLEM
  47&nbsp;fi
  48&nbsp;
  49&nbsp;# Move, rename and bzip2 the logs
  50&nbsp;for logday in $LOG_DAYS; do
  51&nbsp;  for logfile in $LOG_FILES; do
  52&nbsp;    MYFILE="$LOG_DIR/$logfile.$logday"
  53&nbsp;    if [ -w $MYFILE ]; then
  54&nbsp;      DTS=`$LS -lgo --time-style=+%Y%m%d $MYFILE | $COL -t | $CUT -d ' ' -f7`
  55&nbsp;      $MV $MYFILE $BKP_DIR/$logfile.$DTS
  56&nbsp;      $BZ2 $BKP_DIR/$logfile.$DTS
  57&nbsp;    else
  58&nbsp;      # Only spew an error if the file exits (ergo non-writable).
  59&nbsp;      if [ -f $MYFILE ]; then
  60&nbsp;        echo "ERROR: $MYFILE not writable. Skipping."
  61&nbsp;      fi
  62&nbsp;    fi
  63&nbsp;  done
  64&nbsp;done
  65&nbsp;
  66&nbsp;exit 0</PRE
></TD
></TR
></TABLE
><HR></DIV
><P
><A
NAME="PROTECTLITERAL0"
></A
>How to keep the shell from
      expanding and reinterpreting text strings.</P
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="PROTECTLITERAL"
></A
><P
><B
>Example A-26. Protecting literal strings</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#! /bin/bash
   2&nbsp;# protect_literal.sh
   3&nbsp;
   4&nbsp;# set -vx
   5&nbsp;
   6&nbsp;:&#60;&#60;-'_Protect_Literal_String_Doc'
   7&nbsp;
   8&nbsp;    Copyright (c) Michael S. Zick, 2003; All Rights Reserved
   9&nbsp;    License: Unrestricted reuse in any form, for any purpose.
  10&nbsp;    Warranty: None
  11&nbsp;    Revision: $ID$
  12&nbsp;
  13&nbsp;    Documentation redirected to the Bash no-operation.
  14&nbsp;    Bash will '/dev/null' this block when the script is first read.
  15&nbsp;    (Uncomment the above set command to see this action.)
  16&nbsp;
  17&nbsp;    Remove the first (Sha-Bang) line when sourcing this as a library
  18&nbsp;    procedure.  Also comment out the example use code in the two
  19&nbsp;    places where shown.
  20&nbsp;
  21&nbsp;
  22&nbsp;    Usage:
  23&nbsp;        _protect_literal_str 'Whatever string meets your ${fancy}'
  24&nbsp;        Just echos the argument to standard out, hard quotes
  25&nbsp;        restored.
  26&nbsp;
  27&nbsp;        $(_protect_literal_str 'Whatever string meets your ${fancy}')
  28&nbsp;        as the right-hand-side of an assignment statement.
  29&nbsp;
  30&nbsp;    Does:
  31&nbsp;        As the right-hand-side of an assignment, preserves the
  32&nbsp;        hard quotes protecting the contents of the literal during
  33&nbsp;        assignment.
  34&nbsp;
  35&nbsp;    Notes:
  36&nbsp;        The strange names (_*) are used to avoid trampling on
  37&nbsp;        the user's chosen names when this is sourced as a
  38&nbsp;        library.
  39&nbsp;
  40&nbsp;_Protect_Literal_String_Doc
  41&nbsp;
  42&nbsp;# The 'for illustration' function form
  43&nbsp;
  44&nbsp;_protect_literal_str() {
  45&nbsp;
  46&nbsp;# Pick an un-used, non-printing character as local IFS.
  47&nbsp;# Not required, but shows that we are ignoring it.
  48&nbsp;    local IFS=$'\x1B'               # \ESC character
  49&nbsp;
  50&nbsp;# Enclose the All-Elements-Of in hard quotes during assignment.
  51&nbsp;    local tmp=$'\x27'$@$'\x27'
  52&nbsp;#    local tmp=$'\''$@$'\''         # Even uglier.
  53&nbsp;
  54&nbsp;    local len=${#tmp}               # Info only.
  55&nbsp;    echo $tmp is $len long.         # Output AND information.
  56&nbsp;}
  57&nbsp;
  58&nbsp;# This is the short-named version.
  59&nbsp;_pls() {
  60&nbsp;    local IFS=$'x1B'                # \ESC character (not required)
  61&nbsp;    echo $'\x27'$@$'\x27'           # Hard quoted parameter glob
  62&nbsp;}
  63&nbsp;
  64&nbsp;# :&#60;&#60;-'_Protect_Literal_String_Test'
  65&nbsp;# # # Remove the above "# " to disable this code. # # #
  66&nbsp;
  67&nbsp;# See how that looks when printed.
  68&nbsp;echo
  69&nbsp;echo "- - Test One - -"
  70&nbsp;_protect_literal_str 'Hello $user'
  71&nbsp;_protect_literal_str 'Hello "${username}"'
  72&nbsp;echo
  73&nbsp;
  74&nbsp;# Which yields:
  75&nbsp;# - - Test One - -
  76&nbsp;# 'Hello $user' is 13 long.
  77&nbsp;# 'Hello "${username}"' is 21 long.
  78&nbsp;
  79&nbsp;#  Looks as expected, but why all of the trouble?
  80&nbsp;#  The difference is hidden inside the Bash internal order
  81&nbsp;#+ of operations.
  82&nbsp;#  Which shows when you use it on the RHS of an assignment.
  83&nbsp;
  84&nbsp;# Declare an array for test values.
  85&nbsp;declare -a arrayZ
  86&nbsp;
  87&nbsp;# Assign elements with various types of quotes and escapes.
  88&nbsp;arrayZ=( zero "$(_pls 'Hello ${Me}')" 'Hello ${You}' "\'Pass: ${pw}\'" )
  89&nbsp;
  90&nbsp;# Now list that array and see what is there.
  91&nbsp;echo "- - Test Two - -"
  92&nbsp;for (( i=0 ; i&#60;${#arrayZ[*]} ; i++ ))
  93&nbsp;do
  94&nbsp;    echo  Element $i: ${arrayZ[$i]} is: ${#arrayZ[$i]} long.
  95&nbsp;done
  96&nbsp;echo
  97&nbsp;
  98&nbsp;# Which yields:
  99&nbsp;# - - Test Two - -
 100&nbsp;# Element 0: zero is: 4 long.           # Our marker element
 101&nbsp;# Element 1: 'Hello ${Me}' is: 13 long. # Our "$(_pls '...' )"
 102&nbsp;# Element 2: Hello ${You} is: 12 long.  # Quotes are missing
 103&nbsp;# Element 3: \'Pass: \' is: 10 long.    # ${pw} expanded to nothing
 104&nbsp;
 105&nbsp;# Now make an assignment with that result.
 106&nbsp;declare -a array2=( ${arrayZ[@]} )
 107&nbsp;
 108&nbsp;# And print what happened.
 109&nbsp;echo "- - Test Three - -"
 110&nbsp;for (( i=0 ; i&#60;${#array2[*]} ; i++ ))
 111&nbsp;do
 112&nbsp;    echo  Element $i: ${array2[$i]} is: ${#array2[$i]} long.
 113&nbsp;done
 114&nbsp;echo
 115&nbsp;
 116&nbsp;# Which yields:
 117&nbsp;# - - Test Three - -
 118&nbsp;# Element 0: zero is: 4 long.           # Our marker element.
 119&nbsp;# Element 1: Hello ${Me} is: 11 long.   # Intended result.
 120&nbsp;# Element 2: Hello is: 5 long.          # ${You} expanded to nothing.
 121&nbsp;# Element 3: 'Pass: is: 6 long.         # Split on the whitespace.
 122&nbsp;# Element 4: ' is: 1 long.              # The end quote is here now.
 123&nbsp;
 124&nbsp;#  Our Element 1 has had its leading and trailing hard quotes stripped.
 125&nbsp;#  Although not shown, leading and trailing whitespace is also stripped.
 126&nbsp;#  Now that the string contents are set, Bash will always, internally,
 127&nbsp;#+ hard quote the contents as required during its operations.
 128&nbsp;
 129&nbsp;#  Why?
 130&nbsp;#  Considering our "$(_pls 'Hello ${Me}')" construction:
 131&nbsp;#  " ... " -&#62; Expansion required, strip the quotes.
 132&nbsp;#  $( ... ) -&#62; Replace with the result of..., strip this.
 133&nbsp;#  _pls ' ... ' -&#62; called with literal arguments, strip the quotes.
 134&nbsp;#  The result returned includes hard quotes; BUT the above processing
 135&nbsp;#+ has already been done, so they become part of the value assigned.
 136&nbsp;#
 137&nbsp;#  Similarly, during further usage of the string variable, the ${Me}
 138&nbsp;#+ is part of the contents (result) and survives any operations
 139&nbsp;#  (Until explicitly told to evaluate the string).
 140&nbsp;
 141&nbsp;#  Hint: See what happens when the hard quotes ($'\x27') are replaced
 142&nbsp;#+ with soft quotes ($'\x22') in the above procedures.
 143&nbsp;#  Interesting also is to remove the addition of any quoting.
 144&nbsp;
 145&nbsp;# _Protect_Literal_String_Test
 146&nbsp;# # # Remove the above "# " to disable this code. # # #
 147&nbsp;
 148&nbsp;exit 0</PRE
></TD
></TR
></TABLE
><HR></DIV
><P
><A
NAME="UNPROTECTLITERAL0"
></A
>But, what if you
      <SPAN
CLASS="emphasis"
><I
CLASS="EMPHASIS"
>want</I
></SPAN
> the shell to expand
      and reinterpret strings?</P
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="UNPROTECTLITERAL"
></A
><P
><B
>Example A-27. Unprotecting literal strings</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#! /bin/bash
   2&nbsp;# unprotect_literal.sh
   3&nbsp;
   4&nbsp;# set -vx
   5&nbsp;
   6&nbsp;:&#60;&#60;-'_UnProtect_Literal_String_Doc'
   7&nbsp;
   8&nbsp;    Copyright (c) Michael S. Zick, 2003; All Rights Reserved
   9&nbsp;    License: Unrestricted reuse in any form, for any purpose.
  10&nbsp;    Warranty: None
  11&nbsp;    Revision: $ID$
  12&nbsp;
  13&nbsp;    Documentation redirected to the Bash no-operation. Bash will
  14&nbsp;    '/dev/null' this block when the script is first read.
  15&nbsp;    (Uncomment the above set command to see this action.)
  16&nbsp;
  17&nbsp;    Remove the first (Sha-Bang) line when sourcing this as a library
  18&nbsp;    procedure.  Also comment out the example use code in the two
  19&nbsp;    places where shown.
  20&nbsp;
  21&nbsp;
  22&nbsp;    Usage:
  23&nbsp;        Complement of the "$(_pls 'Literal String')" function.
  24&nbsp;        (See the protect_literal.sh example.)
  25&nbsp;
  26&nbsp;        StringVar=$(_upls ProtectedSringVariable)
  27&nbsp;
  28&nbsp;    Does:
  29&nbsp;        When used on the right-hand-side of an assignment statement;
  30&nbsp;        makes the substitions embedded in the protected string.
  31&nbsp;
  32&nbsp;    Notes:
  33&nbsp;        The strange names (_*) are used to avoid trampling on
  34&nbsp;        the user's chosen names when this is sourced as a
  35&nbsp;        library.
  36&nbsp;
  37&nbsp;
  38&nbsp;_UnProtect_Literal_String_Doc
  39&nbsp;
  40&nbsp;_upls() {
  41&nbsp;    local IFS=$'x1B'                # \ESC character (not required)
  42&nbsp;    eval echo $@                    # Substitution on the glob.
  43&nbsp;}
  44&nbsp;
  45&nbsp;# :&#60;&#60;-'_UnProtect_Literal_String_Test'
  46&nbsp;# # # Remove the above "# " to disable this code. # # #
  47&nbsp;
  48&nbsp;
  49&nbsp;_pls() {
  50&nbsp;    local IFS=$'x1B'                # \ESC character (not required)
  51&nbsp;    echo $'\x27'$@$'\x27'           # Hard quoted parameter glob
  52&nbsp;}
  53&nbsp;
  54&nbsp;# Declare an array for test values.
  55&nbsp;declare -a arrayZ
  56&nbsp;
  57&nbsp;# Assign elements with various types of quotes and escapes.
  58&nbsp;arrayZ=( zero "$(_pls 'Hello ${Me}')" 'Hello ${You}' "\'Pass: ${pw}\'" )
  59&nbsp;
  60&nbsp;# Now make an assignment with that result.
  61&nbsp;declare -a array2=( ${arrayZ[@]} )
  62&nbsp;
  63&nbsp;# Which yielded:
  64&nbsp;# - - Test Three - -
  65&nbsp;# Element 0: zero is: 4 long            # Our marker element.
  66&nbsp;# Element 1: Hello ${Me} is: 11 long    # Intended result.
  67&nbsp;# Element 2: Hello is: 5 long           # ${You} expanded to nothing.
  68&nbsp;# Element 3: 'Pass: is: 6 long          # Split on the whitespace.
  69&nbsp;# Element 4: ' is: 1 long               # The end quote is here now.
  70&nbsp;
  71&nbsp;# set -vx
  72&nbsp;
  73&nbsp;#  Initialize 'Me' to something for the embedded ${Me} substitution.
  74&nbsp;#  This needs to be done ONLY just prior to evaluating the
  75&nbsp;#+ protected string.
  76&nbsp;#  (This is why it was protected to begin with.)
  77&nbsp;
  78&nbsp;Me="to the array guy."
  79&nbsp;
  80&nbsp;# Set a string variable destination to the result.
  81&nbsp;newVar=$(_upls ${array2[1]})
  82&nbsp;
  83&nbsp;# Show what the contents are.
  84&nbsp;echo $newVar
  85&nbsp;
  86&nbsp;# Do we really need a function to do this?
  87&nbsp;newerVar=$(eval echo ${array2[1]})
  88&nbsp;echo $newerVar
  89&nbsp;
  90&nbsp;#  I guess not, but the _upls function gives us a place to hang
  91&nbsp;#+ the documentation on.
  92&nbsp;#  This helps when we forget what a # construction like:
  93&nbsp;#+ $(eval echo ... ) means.
  94&nbsp;
  95&nbsp;# What if Me isn't set when the protected string is evaluated?
  96&nbsp;unset Me
  97&nbsp;newestVar=$(_upls ${array2[1]})
  98&nbsp;echo $newestVar
  99&nbsp;
 100&nbsp;# Just gone, no hints, no runs, no errors.
 101&nbsp;
 102&nbsp;#  Why in the world?
 103&nbsp;#  Setting the contents of a string variable containing character
 104&nbsp;#+ sequences that have a meaning in Bash is a general problem in
 105&nbsp;#+ script programming.
 106&nbsp;#
 107&nbsp;#  This problem is now solved in eight lines of code
 108&nbsp;#+ (and four pages of description).
 109&nbsp;
 110&nbsp;#  Where is all this going?
 111&nbsp;#  Dynamic content Web pages as an array of Bash strings.
 112&nbsp;#  Content set per request by a Bash 'eval' command
 113&nbsp;#+ on the stored page template.
 114&nbsp;#  Not intended to replace PHP, just an interesting thing to do.
 115&nbsp;###
 116&nbsp;#  Don't have a webserver application?
 117&nbsp;#  No problem, check the example directory of the Bash source;
 118&nbsp;#+ there is a Bash script for that also.
 119&nbsp;
 120&nbsp;# _UnProtect_Literal_String_Test
 121&nbsp;# # # Remove the above "# " to disable this code. # # #
 122&nbsp;
 123&nbsp;exit 0</PRE
></TD
></TR
></TABLE
><HR></DIV
><P
>This interesting script helps hunt down spammers.</P
><P
><A
NAME="ISSPAMMER2_0"
></A
></P
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="ISSPAMMER2"
></A
><P
><B
>Example A-28. Spammer Identification</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#!/bin/bash
   2&nbsp;
   3&nbsp;# $Id: is_spammer.bash,v 1.12.2.11 2004/10/01 21:42:33 mszick Exp $
   4&nbsp;# Above line is RCS info.
   5&nbsp;
   6&nbsp;# The latest version of this script is available from http://www.morethan.org.
   7&nbsp;#
   8&nbsp;# Spammer-identification
   9&nbsp;# by Michael S. Zick
  10&nbsp;# Used in the ABS Guide with permission.
  11&nbsp;
  12&nbsp;
  13&nbsp;
  14&nbsp;#######################################################
  15&nbsp;# Documentation
  16&nbsp;# See also "Quickstart" at end of script.
  17&nbsp;#######################################################
  18&nbsp;
  19&nbsp;:&#60;&#60;-'__is_spammer_Doc_'
  20&nbsp;
  21&nbsp;    Copyright (c) Michael S. Zick, 2004
  22&nbsp;    License: Unrestricted reuse in any form, for any purpose.
  23&nbsp;    Warranty: None -{Its a script; the user is on their own.}-
  24&nbsp;
  25&nbsp;Impatient?
  26&nbsp;    Application code: goto "# # # Hunt the Spammer' program code # # #"
  27&nbsp;    Example output: ":&#60;&#60;-'_is_spammer_outputs_'"
  28&nbsp;    How to use: Enter script name without arguments.
  29&nbsp;                Or goto "Quickstart" at end of script.
  30&nbsp;
  31&nbsp;Provides
  32&nbsp;    Given a domain name or IP(v4) address as input:
  33&nbsp;
  34&nbsp;    Does an exhaustive set of queries to find the associated
  35&nbsp;    network resources (short of recursing into TLDs).
  36&nbsp;
  37&nbsp;    Checks the IP(v4) addresses found against Blacklist
  38&nbsp;    nameservers.
  39&nbsp;
  40&nbsp;    If found to be a blacklisted IP(v4) address,
  41&nbsp;    reports the blacklist text records.
  42&nbsp;    (Usually hyper-links to the specific report.)
  43&nbsp;
  44&nbsp;Requires
  45&nbsp;    A working Internet connection.
  46&nbsp;    (Exercise: Add check and/or abort if not on-line when running script.)
  47&nbsp;    Bash with arrays (2.05b+).
  48&nbsp;
  49&nbsp;    The external program 'dig' --
  50&nbsp;    a utility program provided with the 'bind' set of programs.
  51&nbsp;    Specifically, the version which is part of Bind series 9.x
  52&nbsp;    See: http://www.isc.org
  53&nbsp;
  54&nbsp;    All usages of 'dig' are limited to wrapper functions,
  55&nbsp;    which may be rewritten as required.
  56&nbsp;    See: dig_wrappers.bash for details.
  57&nbsp;         ("Additional documentation" -- below)
  58&nbsp;
  59&nbsp;Usage
  60&nbsp;    Script requires a single argument, which may be:
  61&nbsp;    1) A domain name;
  62&nbsp;    2) An IP(v4) address;
  63&nbsp;    3) A filename, with one name or address per line.
  64&nbsp;
  65&nbsp;    Script accepts an optional second argument, which may be:
  66&nbsp;    1) A Blacklist server name;
  67&nbsp;    2) A filename, with one Blacklist server name per line.
  68&nbsp;
  69&nbsp;    If the second argument is not provided, the script uses
  70&nbsp;    a built-in set of (free) Blacklist servers.
  71&nbsp;
  72&nbsp;    See also, the Quickstart at the end of this script (after 'exit').
  73&nbsp;
  74&nbsp;Return Codes
  75&nbsp;    0 - All OK
  76&nbsp;    1 - Script failure
  77&nbsp;    2 - Something is Blacklisted
  78&nbsp;
  79&nbsp;Optional environment variables
  80&nbsp;    SPAMMER_TRACE
  81&nbsp;        If set to a writable file,
  82&nbsp;        script will log an execution flow trace.
  83&nbsp;
  84&nbsp;    SPAMMER_DATA
  85&nbsp;        If set to a writable file, script will dump its
  86&nbsp;        discovered data in the form of GraphViz file.
  87&nbsp;        See: http://www.research.att.com/sw/tools/graphviz
  88&nbsp;
  89&nbsp;    SPAMMER_LIMIT
  90&nbsp;        Limits the depth of resource tracing.
  91&nbsp;
  92&nbsp;        Default is 2 levels.
  93&nbsp;
  94&nbsp;        A setting of 0 (zero) means 'unlimited' . . .
  95&nbsp;          Caution: script might recurse the whole Internet!
  96&nbsp;
  97&nbsp;        A limit of 1 or 2 is most useful when processing
  98&nbsp;        a file of domain names and addresses.
  99&nbsp;        A higher limit can be useful when hunting spam gangs.
 100&nbsp;
 101&nbsp;
 102&nbsp;Additional documentation
 103&nbsp;    Download the archived set of scripts
 104&nbsp;    explaining and illustrating the function contained within this script.
 105&nbsp;    http://bash.deta.in/mszick_clf.tar.bz2
 106&nbsp;
 107&nbsp;
 108&nbsp;Study notes
 109&nbsp;    This script uses a large number of functions.
 110&nbsp;    Nearly all general functions have their own example script.
 111&nbsp;    Each of the example scripts have tutorial level comments.
 112&nbsp;
 113&nbsp;Scripting project
 114&nbsp;    Add support for IP(v6) addresses.
 115&nbsp;    IP(v6) addresses are recognized but not processed.
 116&nbsp;
 117&nbsp;Advanced project
 118&nbsp;    Add the reverse lookup detail to the discovered information.
 119&nbsp;
 120&nbsp;    Report the delegation chain and abuse contacts.
 121&nbsp;
 122&nbsp;    Modify the GraphViz file output to include the
 123&nbsp;    newly discovered information.
 124&nbsp;
 125&nbsp;__is_spammer_Doc_
 126&nbsp;
 127&nbsp;#######################################################
 128&nbsp;
 129&nbsp;
 130&nbsp;
 131&nbsp;
 132&nbsp;#### Special IFS settings used for string parsing. ####
 133&nbsp;
 134&nbsp;# Whitespace == :Space:Tab:Line Feed:Carriage Return:
 135&nbsp;WSP_IFS=$'\x20'$'\x09'$'\x0A'$'\x0D'
 136&nbsp;
 137&nbsp;# No Whitespace == Line Feed:Carriage Return
 138&nbsp;NO_WSP=$'\x0A'$'\x0D'
 139&nbsp;
 140&nbsp;# Field separator for dotted decimal IP addresses
 141&nbsp;ADR_IFS=${NO_WSP}'.'
 142&nbsp;
 143&nbsp;# Array to dotted string conversions
 144&nbsp;DOT_IFS='.'${WSP_IFS}
 145&nbsp;
 146&nbsp;# # # Pending operations stack machine # # #
 147&nbsp;# This set of functions described in func_stack.bash.
 148&nbsp;# (See "Additional documentation" above.)
 149&nbsp;# # #
 150&nbsp;
 151&nbsp;# Global stack of pending operations.
 152&nbsp;declare -f -a _pending_
 153&nbsp;# Global sentinel for stack runners
 154&nbsp;declare -i _p_ctrl_
 155&nbsp;# Global holder for currently executing function
 156&nbsp;declare -f _pend_current_
 157&nbsp;
 158&nbsp;# # # Debug version only - remove for regular use # # #
 159&nbsp;#
 160&nbsp;# The function stored in _pend_hook_ is called
 161&nbsp;# immediately before each pending function is
 162&nbsp;# evaluated.  Stack clean, _pend_current_ set.
 163&nbsp;#
 164&nbsp;# This thingy demonstrated in pend_hook.bash.
 165&nbsp;declare -f _pend_hook_
 166&nbsp;# # #
 167&nbsp;
 168&nbsp;# The do nothing function
 169&nbsp;pend_dummy() { : ; }
 170&nbsp;
 171&nbsp;# Clear and initialize the function stack.
 172&nbsp;pend_init() {
 173&nbsp;    unset _pending_[@]
 174&nbsp;    pend_func pend_stop_mark
 175&nbsp;    _pend_hook_='pend_dummy'  # Debug only.
 176&nbsp;}
 177&nbsp;
 178&nbsp;# Discard the top function on the stack.
 179&nbsp;pend_pop() {
 180&nbsp;    if [ ${#_pending_[@]} -gt 0 ]
 181&nbsp;    then
 182&nbsp;        local -i _top_
 183&nbsp;        _top_=${#_pending_[@]}-1
 184&nbsp;        unset _pending_[$_top_]
 185&nbsp;    fi
 186&nbsp;}
 187&nbsp;
 188&nbsp;# pend_func function_name [$(printf '%q\n' arguments)]
 189&nbsp;pend_func() {
 190&nbsp;    local IFS=${NO_WSP}
 191&nbsp;    set -f
 192&nbsp;    _pending_[${#_pending_[@]}]=$@
 193&nbsp;    set +f
 194&nbsp;}
 195&nbsp;
 196&nbsp;# The function which stops the release:
 197&nbsp;pend_stop_mark() {
 198&nbsp;    _p_ctrl_=0
 199&nbsp;}
 200&nbsp;
 201&nbsp;pend_mark() {
 202&nbsp;    pend_func pend_stop_mark
 203&nbsp;}
 204&nbsp;
 205&nbsp;# Execute functions until 'pend_stop_mark' . . .
 206&nbsp;pend_release() {
 207&nbsp;    local -i _top_             # Declare _top_ as integer.
 208&nbsp;    _p_ctrl_=${#_pending_[@]}
 209&nbsp;    while [ ${_p_ctrl_} -gt 0 ]
 210&nbsp;    do
 211&nbsp;       _top_=${#_pending_[@]}-1
 212&nbsp;       _pend_current_=${_pending_[$_top_]}
 213&nbsp;       unset _pending_[$_top_]
 214&nbsp;       $_pend_hook_            # Debug only.
 215&nbsp;       eval $_pend_current_
 216&nbsp;    done
 217&nbsp;}
 218&nbsp;
 219&nbsp;# Drop functions until 'pend_stop_mark' . . .
 220&nbsp;pend_drop() {
 221&nbsp;    local -i _top_
 222&nbsp;    local _pd_ctrl_=${#_pending_[@]}
 223&nbsp;    while [ ${_pd_ctrl_} -gt 0 ]
 224&nbsp;    do
 225&nbsp;       _top_=$_pd_ctrl_-1
 226&nbsp;       if [ "${_pending_[$_top_]}" == 'pend_stop_mark' ]
 227&nbsp;       then
 228&nbsp;           unset _pending_[$_top_]
 229&nbsp;           break
 230&nbsp;       else
 231&nbsp;           unset _pending_[$_top_]
 232&nbsp;           _pd_ctrl_=$_top_
 233&nbsp;       fi
 234&nbsp;    done
 235&nbsp;    if [ ${#_pending_[@]} -eq 0 ]
 236&nbsp;    then
 237&nbsp;        pend_func pend_stop_mark
 238&nbsp;    fi
 239&nbsp;}
 240&nbsp;
 241&nbsp;#### Array editors ####
 242&nbsp;
 243&nbsp;# This function described in edit_exact.bash.
 244&nbsp;# (See "Additional documentation," above.)
 245&nbsp;# edit_exact &#60;excludes_array_name&#62; &#60;target_array_name&#62;
 246&nbsp;edit_exact() {
 247&nbsp;    [ $# -eq 2 ] ||
 248&nbsp;    [ $# -eq 3 ] || return 1
 249&nbsp;    local -a _ee_Excludes
 250&nbsp;    local -a _ee_Target
 251&nbsp;    local _ee_x
 252&nbsp;    local _ee_t
 253&nbsp;    local IFS=${NO_WSP}
 254&nbsp;    set -f
 255&nbsp;    eval _ee_Excludes=\( \$\{$1\[@\]\} \)
 256&nbsp;    eval _ee_Target=\( \$\{$2\[@\]\} \)
 257&nbsp;    local _ee_len=${#_ee_Target[@]}     # Original length.
 258&nbsp;    local _ee_cnt=${#_ee_Excludes[@]}   # Exclude list length.
 259&nbsp;    [ ${_ee_len} -ne 0 ] || return 0    # Can't edit zero length.
 260&nbsp;    [ ${_ee_cnt} -ne 0 ] || return 0    # Can't edit zero length.
 261&nbsp;    for (( x = 0; x &#60; ${_ee_cnt} ; x++ ))
 262&nbsp;    do
 263&nbsp;        _ee_x=${_ee_Excludes[$x]}
 264&nbsp;        for (( n = 0 ; n &#60; ${_ee_len} ; n++ ))
 265&nbsp;        do
 266&nbsp;            _ee_t=${_ee_Target[$n]}
 267&nbsp;            if [ x"${_ee_t}" == x"${_ee_x}" ]
 268&nbsp;            then
 269&nbsp;                unset _ee_Target[$n]     # Discard match.
 270&nbsp;                [ $# -eq 2 ] &#38;&#38; break    # If 2 arguments, then done.
 271&nbsp;            fi
 272&nbsp;        done
 273&nbsp;    done
 274&nbsp;    eval $2=\( \$\{_ee_Target\[@\]\} \)
 275&nbsp;    set +f
 276&nbsp;    return 0
 277&nbsp;}
 278&nbsp;
 279&nbsp;# This function described in edit_by_glob.bash.
 280&nbsp;# edit_by_glob &#60;excludes_array_name&#62; &#60;target_array_name&#62;
 281&nbsp;edit_by_glob() {
 282&nbsp;    [ $# -eq 2 ] ||
 283&nbsp;    [ $# -eq 3 ] || return 1
 284&nbsp;    local -a _ebg_Excludes
 285&nbsp;    local -a _ebg_Target
 286&nbsp;    local _ebg_x
 287&nbsp;    local _ebg_t
 288&nbsp;    local IFS=${NO_WSP}
 289&nbsp;    set -f
 290&nbsp;    eval _ebg_Excludes=\( \$\{$1\[@\]\} \)
 291&nbsp;    eval _ebg_Target=\( \$\{$2\[@\]\} \)
 292&nbsp;    local _ebg_len=${#_ebg_Target[@]}
 293&nbsp;    local _ebg_cnt=${#_ebg_Excludes[@]}
 294&nbsp;    [ ${_ebg_len} -ne 0 ] || return 0
 295&nbsp;    [ ${_ebg_cnt} -ne 0 ] || return 0
 296&nbsp;    for (( x = 0; x &#60; ${_ebg_cnt} ; x++ ))
 297&nbsp;    do
 298&nbsp;        _ebg_x=${_ebg_Excludes[$x]}
 299&nbsp;        for (( n = 0 ; n &#60; ${_ebg_len} ; n++ ))
 300&nbsp;        do
 301&nbsp;            [ $# -eq 3 ] &#38;&#38; _ebg_x=${_ebg_x}'*'  #  Do prefix edit
 302&nbsp;            if [ ${_ebg_Target[$n]:=} ]          #+ if defined &#38; set.
 303&nbsp;            then
 304&nbsp;                _ebg_t=${_ebg_Target[$n]/#${_ebg_x}/}
 305&nbsp;                [ ${#_ebg_t} -eq 0 ] &#38;&#38; unset _ebg_Target[$n]
 306&nbsp;            fi
 307&nbsp;        done
 308&nbsp;    done
 309&nbsp;    eval $2=\( \$\{_ebg_Target\[@\]\} \)
 310&nbsp;    set +f
 311&nbsp;    return 0
 312&nbsp;}
 313&nbsp;
 314&nbsp;# This function described in unique_lines.bash.
 315&nbsp;# unique_lines &#60;in_name&#62; &#60;out_name&#62;
 316&nbsp;unique_lines() {
 317&nbsp;    [ $# -eq 2 ] || return 1
 318&nbsp;    local -a _ul_in
 319&nbsp;    local -a _ul_out
 320&nbsp;    local -i _ul_cnt
 321&nbsp;    local -i _ul_pos
 322&nbsp;    local _ul_tmp
 323&nbsp;    local IFS=${NO_WSP}
 324&nbsp;    set -f
 325&nbsp;    eval _ul_in=\( \$\{$1\[@\]\} \)
 326&nbsp;    _ul_cnt=${#_ul_in[@]}
 327&nbsp;    for (( _ul_pos = 0 ; _ul_pos &#60; ${_ul_cnt} ; _ul_pos++ ))
 328&nbsp;    do
 329&nbsp;        if [ ${_ul_in[${_ul_pos}]:=} ]      # If defined &#38; not empty
 330&nbsp;        then
 331&nbsp;            _ul_tmp=${_ul_in[${_ul_pos}]}
 332&nbsp;            _ul_out[${#_ul_out[@]}]=${_ul_tmp}
 333&nbsp;            for (( zap = _ul_pos ; zap &#60; ${_ul_cnt} ; zap++ ))
 334&nbsp;            do
 335&nbsp;                [ ${_ul_in[${zap}]:=} ] &#38;&#38;
 336&nbsp;                [ 'x'${_ul_in[${zap}]} == 'x'${_ul_tmp} ] &#38;&#38;
 337&nbsp;                    unset _ul_in[${zap}]
 338&nbsp;            done
 339&nbsp;        fi
 340&nbsp;    done
 341&nbsp;    eval $2=\( \$\{_ul_out\[@\]\} \)
 342&nbsp;    set +f
 343&nbsp;    return 0
 344&nbsp;}
 345&nbsp;
 346&nbsp;# This function described in char_convert.bash.
 347&nbsp;# to_lower &#60;string&#62;
 348&nbsp;to_lower() {
 349&nbsp;    [ $# -eq 1 ] || return 1
 350&nbsp;    local _tl_out
 351&nbsp;    _tl_out=${1//A/a}
 352&nbsp;    _tl_out=${_tl_out//B/b}
 353&nbsp;    _tl_out=${_tl_out//C/c}
 354&nbsp;    _tl_out=${_tl_out//D/d}
 355&nbsp;    _tl_out=${_tl_out//E/e}
 356&nbsp;    _tl_out=${_tl_out//F/f}
 357&nbsp;    _tl_out=${_tl_out//G/g}
 358&nbsp;    _tl_out=${_tl_out//H/h}
 359&nbsp;    _tl_out=${_tl_out//I/i}
 360&nbsp;    _tl_out=${_tl_out//J/j}
 361&nbsp;    _tl_out=${_tl_out//K/k}
 362&nbsp;    _tl_out=${_tl_out//L/l}
 363&nbsp;    _tl_out=${_tl_out//M/m}
 364&nbsp;    _tl_out=${_tl_out//N/n}
 365&nbsp;    _tl_out=${_tl_out//O/o}
 366&nbsp;    _tl_out=${_tl_out//P/p}
 367&nbsp;    _tl_out=${_tl_out//Q/q}
 368&nbsp;    _tl_out=${_tl_out//R/r}
 369&nbsp;    _tl_out=${_tl_out//S/s}
 370&nbsp;    _tl_out=${_tl_out//T/t}
 371&nbsp;    _tl_out=${_tl_out//U/u}
 372&nbsp;    _tl_out=${_tl_out//V/v}
 373&nbsp;    _tl_out=${_tl_out//W/w}
 374&nbsp;    _tl_out=${_tl_out//X/x}
 375&nbsp;    _tl_out=${_tl_out//Y/y}
 376&nbsp;    _tl_out=${_tl_out//Z/z}
 377&nbsp;    echo ${_tl_out}
 378&nbsp;    return 0
 379&nbsp;}
 380&nbsp;
 381&nbsp;#### Application helper functions ####
 382&nbsp;
 383&nbsp;# Not everybody uses dots as separators (APNIC, for example).
 384&nbsp;# This function described in to_dot.bash
 385&nbsp;# to_dot &#60;string&#62;
 386&nbsp;to_dot() {
 387&nbsp;    [ $# -eq 1 ] || return 1
 388&nbsp;    echo ${1//[#|@|%]/.}
 389&nbsp;    return 0
 390&nbsp;}
 391&nbsp;
 392&nbsp;# This function described in is_number.bash.
 393&nbsp;# is_number &#60;input&#62;
 394&nbsp;is_number() {
 395&nbsp;    [ "$#" -eq 1 ]    || return 1  # is blank?
 396&nbsp;    [ x"$1" == 'x0' ] &#38;&#38; return 0  # is zero?
 397&nbsp;    local -i tst
 398&nbsp;    let tst=$1 2&#62;/dev/null         # else is numeric!
 399&nbsp;    return $?
 400&nbsp;}
 401&nbsp;
 402&nbsp;# This function described in is_address.bash.
 403&nbsp;# is_address &#60;input&#62;
 404&nbsp;is_address() {
 405&nbsp;    [ $# -eq 1 ] || return 1    # Blank ==&#62; false
 406&nbsp;    local -a _ia_input
 407&nbsp;    local IFS=${ADR_IFS}
 408&nbsp;    _ia_input=( $1 )
 409&nbsp;    if  [ ${#_ia_input[@]} -eq 4 ]  &#38;&#38;
 410&nbsp;        is_number ${_ia_input[0]}   &#38;&#38;
 411&nbsp;        is_number ${_ia_input[1]}   &#38;&#38;
 412&nbsp;        is_number ${_ia_input[2]}   &#38;&#38;
 413&nbsp;        is_number ${_ia_input[3]}   &#38;&#38;
 414&nbsp;        [ ${_ia_input[0]} -lt 256 ] &#38;&#38;
 415&nbsp;        [ ${_ia_input[1]} -lt 256 ] &#38;&#38;
 416&nbsp;        [ ${_ia_input[2]} -lt 256 ] &#38;&#38;
 417&nbsp;        [ ${_ia_input[3]} -lt 256 ]
 418&nbsp;    then
 419&nbsp;        return 0
 420&nbsp;    else
 421&nbsp;        return 1
 422&nbsp;    fi
 423&nbsp;}
 424&nbsp;
 425&nbsp;#  This function described in split_ip.bash.
 426&nbsp;#  split_ip &#60;IP_address&#62;
 427&nbsp;#+ &#60;array_name_norm&#62; [&#60;array_name_rev&#62;]
 428&nbsp;split_ip() {
 429&nbsp;    [ $# -eq 3 ] ||              #  Either three
 430&nbsp;    [ $# -eq 2 ] || return 1     #+ or two arguments
 431&nbsp;    local -a _si_input
 432&nbsp;    local IFS=${ADR_IFS}
 433&nbsp;    _si_input=( $1 )
 434&nbsp;    IFS=${WSP_IFS}
 435&nbsp;    eval $2=\(\ \$\{_si_input\[@\]\}\ \)
 436&nbsp;    if [ $# -eq 3 ]
 437&nbsp;    then
 438&nbsp;        # Build query order array.
 439&nbsp;        local -a _dns_ip
 440&nbsp;        _dns_ip[0]=${_si_input[3]}
 441&nbsp;        _dns_ip[1]=${_si_input[2]}
 442&nbsp;        _dns_ip[2]=${_si_input[1]}
 443&nbsp;        _dns_ip[3]=${_si_input[0]}
 444&nbsp;        eval $3=\(\ \$\{_dns_ip\[@\]\}\ \)
 445&nbsp;    fi
 446&nbsp;    return 0
 447&nbsp;}
 448&nbsp;
 449&nbsp;# This function described in dot_array.bash.
 450&nbsp;# dot_array &#60;array_name&#62;
 451&nbsp;dot_array() {
 452&nbsp;    [ $# -eq 1 ] || return 1     # Single argument required.
 453&nbsp;    local -a _da_input
 454&nbsp;    eval _da_input=\(\ \$\{$1\[@\]\}\ \)
 455&nbsp;    local IFS=${DOT_IFS}
 456&nbsp;    local _da_output=${_da_input[@]}
 457&nbsp;    IFS=${WSP_IFS}
 458&nbsp;    echo ${_da_output}
 459&nbsp;    return 0
 460&nbsp;}
 461&nbsp;
 462&nbsp;# This function described in file_to_array.bash
 463&nbsp;# file_to_array &#60;file_name&#62; &#60;line_array_name&#62;
 464&nbsp;file_to_array() {
 465&nbsp;    [ $# -eq 2 ] || return 1  # Two arguments required.
 466&nbsp;    local IFS=${NO_WSP}
 467&nbsp;    local -a _fta_tmp_
 468&nbsp;    _fta_tmp_=( $(cat $1) )
 469&nbsp;    eval $2=\( \$\{_fta_tmp_\[@\]\} \)
 470&nbsp;    return 0
 471&nbsp;}
 472&nbsp;
 473&nbsp;#  Columnized print of an array of multi-field strings.
 474&nbsp;#  col_print &#60;array_name&#62; &#60;min_space&#62; &#60;
 475&nbsp;#+ tab_stop [tab_stops]&#62;
 476&nbsp;col_print() {
 477&nbsp;    [ $# -gt 2 ] || return 0
 478&nbsp;    local -a _cp_inp
 479&nbsp;    local -a _cp_spc
 480&nbsp;    local -a _cp_line
 481&nbsp;    local _cp_min
 482&nbsp;    local _cp_mcnt
 483&nbsp;    local _cp_pos
 484&nbsp;    local _cp_cnt
 485&nbsp;    local _cp_tab
 486&nbsp;    local -i _cp
 487&nbsp;    local -i _cpf
 488&nbsp;    local _cp_fld
 489&nbsp;    # WARNING: FOLLOWING LINE NOT BLANK -- IT IS QUOTED SPACES.
 490&nbsp;    local _cp_max='                                                            '
 491&nbsp;    set -f
 492&nbsp;    local IFS=${NO_WSP}
 493&nbsp;    eval _cp_inp=\(\ \$\{$1\[@\]\}\ \)
 494&nbsp;    [ ${#_cp_inp[@]} -gt 0 ] || return 0 # Empty is easy.
 495&nbsp;    _cp_mcnt=$2
 496&nbsp;    _cp_min=${_cp_max:1:${_cp_mcnt}}
 497&nbsp;    shift
 498&nbsp;    shift
 499&nbsp;    _cp_cnt=$#
 500&nbsp;    for (( _cp = 0 ; _cp &#60; _cp_cnt ; _cp++ ))
 501&nbsp;    do
 502&nbsp;        _cp_spc[${#_cp_spc[@]}]="${_cp_max:2:$1}" #"
 503&nbsp;        shift
 504&nbsp;    done
 505&nbsp;    _cp_cnt=${#_cp_inp[@]}
 506&nbsp;    for (( _cp = 0 ; _cp &#60; _cp_cnt ; _cp++ ))
 507&nbsp;    do
 508&nbsp;        _cp_pos=1
 509&nbsp;        IFS=${NO_WSP}$'\x20'
 510&nbsp;        _cp_line=( ${_cp_inp[${_cp}]} )
 511&nbsp;        IFS=${NO_WSP}
 512&nbsp;        for (( _cpf = 0 ; _cpf &#60; ${#_cp_line[@]} ; _cpf++ ))
 513&nbsp;        do
 514&nbsp;            _cp_tab=${_cp_spc[${_cpf}]:${_cp_pos}}
 515&nbsp;            if [ ${#_cp_tab} -lt ${_cp_mcnt} ]
 516&nbsp;            then
 517&nbsp;                _cp_tab="${_cp_min}"
 518&nbsp;            fi
 519&nbsp;            echo -n "${_cp_tab}"
 520&nbsp;            (( _cp_pos = ${_cp_pos} + ${#_cp_tab} ))
 521&nbsp;            _cp_fld="${_cp_line[${_cpf}]}"
 522&nbsp;            echo -n ${_cp_fld}
 523&nbsp;            (( _cp_pos = ${_cp_pos} + ${#_cp_fld} ))
 524&nbsp;        done
 525&nbsp;        echo
 526&nbsp;    done
 527&nbsp;    set +f
 528&nbsp;    return 0
 529&nbsp;}
 530&nbsp;
 531&nbsp;# # # # 'Hunt the Spammer' data flow # # # #
 532&nbsp;
 533&nbsp;# Application return code
 534&nbsp;declare -i _hs_RC
 535&nbsp;
 536&nbsp;# Original input, from which IP addresses are removed
 537&nbsp;# After which, domain names to check
 538&nbsp;declare -a uc_name
 539&nbsp;
 540&nbsp;# Original input IP addresses are moved here
 541&nbsp;# After which, IP addresses to check
 542&nbsp;declare -a uc_address
 543&nbsp;
 544&nbsp;# Names against which address expansion run
 545&nbsp;# Ready for name detail lookup
 546&nbsp;declare -a chk_name
 547&nbsp;
 548&nbsp;# Addresses against which name expansion run
 549&nbsp;# Ready for address detail lookup
 550&nbsp;declare -a chk_address
 551&nbsp;
 552&nbsp;#  Recursion is depth-first-by-name.
 553&nbsp;#  The expand_input_address maintains this list
 554&nbsp;#+ to prohibit looking up addresses twice during
 555&nbsp;#+ domain name recursion.
 556&nbsp;declare -a been_there_addr
 557&nbsp;been_there_addr=( '127.0.0.1' ) # Whitelist localhost
 558&nbsp;
 559&nbsp;# Names which we have checked (or given up on)
 560&nbsp;declare -a known_name
 561&nbsp;
 562&nbsp;# Addresses which we have checked (or given up on)
 563&nbsp;declare -a known_address
 564&nbsp;
 565&nbsp;#  List of zero or more Blacklist servers to check.
 566&nbsp;#  Each 'known_address' will be checked against each server,
 567&nbsp;#+ with negative replies and failures suppressed.
 568&nbsp;declare -a list_server
 569&nbsp;
 570&nbsp;# Indirection limit - set to zero == no limit
 571&nbsp;indirect=${SPAMMER_LIMIT:=2}
 572&nbsp;
 573&nbsp;# # # # 'Hunt the Spammer' information output data # # # #
 574&nbsp;
 575&nbsp;# Any domain name may have multiple IP addresses.
 576&nbsp;# Any IP address may have multiple domain names.
 577&nbsp;# Therefore, track unique address-name pairs.
 578&nbsp;declare -a known_pair
 579&nbsp;declare -a reverse_pair
 580&nbsp;
 581&nbsp;#  In addition to the data flow variables; known_address
 582&nbsp;#+ known_name and list_server, the following are output to the
 583&nbsp;#+ external graphics interface file.
 584&nbsp;
 585&nbsp;# Authority chain, parent -&#62; SOA fields.
 586&nbsp;declare -a auth_chain
 587&nbsp;
 588&nbsp;# Reference chain, parent name -&#62; child name
 589&nbsp;declare -a ref_chain
 590&nbsp;
 591&nbsp;# DNS chain - domain name -&#62; address
 592&nbsp;declare -a name_address
 593&nbsp;
 594&nbsp;# Name and service pairs - domain name -&#62; service
 595&nbsp;declare -a name_srvc
 596&nbsp;
 597&nbsp;# Name and resource pairs - domain name -&#62; Resource Record
 598&nbsp;declare -a name_resource
 599&nbsp;
 600&nbsp;# Parent and Child pairs - parent name -&#62; child name
 601&nbsp;# This MAY NOT be the same as the ref_chain followed!
 602&nbsp;declare -a parent_child
 603&nbsp;
 604&nbsp;# Address and Blacklist hit pairs - address-&#62;server
 605&nbsp;declare -a address_hits
 606&nbsp;
 607&nbsp;# Dump interface file data
 608&nbsp;declare -f _dot_dump
 609&nbsp;_dot_dump=pend_dummy   # Initially a no-op
 610&nbsp;
 611&nbsp;#  Data dump is enabled by setting the environment variable SPAMMER_DATA
 612&nbsp;#+ to the name of a writable file.
 613&nbsp;declare _dot_file
 614&nbsp;
 615&nbsp;# Helper function for the dump-to-dot-file function
 616&nbsp;# dump_to_dot &#60;array_name&#62; &#60;prefix&#62;
 617&nbsp;dump_to_dot() {
 618&nbsp;    local -a _dda_tmp
 619&nbsp;    local -i _dda_cnt
 620&nbsp;    local _dda_form='    '${2}'%04u %s\n'
 621&nbsp;    local IFS=${NO_WSP}
 622&nbsp;    eval _dda_tmp=\(\ \$\{$1\[@\]\}\ \)
 623&nbsp;    _dda_cnt=${#_dda_tmp[@]}
 624&nbsp;    if [ ${_dda_cnt} -gt 0 ]
 625&nbsp;    then
 626&nbsp;        for (( _dda = 0 ; _dda &#60; _dda_cnt ; _dda++ ))
 627&nbsp;        do
 628&nbsp;            printf "${_dda_form}" \
 629&nbsp;                   "${_dda}" "${_dda_tmp[${_dda}]}" &#62;&#62;${_dot_file}
 630&nbsp;        done
 631&nbsp;    fi
 632&nbsp;}
 633&nbsp;
 634&nbsp;# Which will also set _dot_dump to this function . . .
 635&nbsp;dump_dot() {
 636&nbsp;    local -i _dd_cnt
 637&nbsp;    echo '# Data vintage: '$(date -R) &#62;${_dot_file}
 638&nbsp;    echo '# ABS Guide: is_spammer.bash; v2, 2004-msz' &#62;&#62;${_dot_file}
 639&nbsp;    echo &#62;&#62;${_dot_file}
 640&nbsp;    echo 'digraph G {' &#62;&#62;${_dot_file}
 641&nbsp;
 642&nbsp;    if [ ${#known_name[@]} -gt 0 ]
 643&nbsp;    then
 644&nbsp;        echo &#62;&#62;${_dot_file}
 645&nbsp;        echo '# Known domain name nodes' &#62;&#62;${_dot_file}
 646&nbsp;        _dd_cnt=${#known_name[@]}
 647&nbsp;        for (( _dd = 0 ; _dd &#60; _dd_cnt ; _dd++ ))
 648&nbsp;        do
 649&nbsp;            printf '    N%04u [label="%s"] ;\n' \
 650&nbsp;                   "${_dd}" "${known_name[${_dd}]}" &#62;&#62;${_dot_file}
 651&nbsp;        done
 652&nbsp;    fi
 653&nbsp;
 654&nbsp;    if [ ${#known_address[@]} -gt 0 ]
 655&nbsp;    then
 656&nbsp;        echo &#62;&#62;${_dot_file}
 657&nbsp;        echo '# Known address nodes' &#62;&#62;${_dot_file}
 658&nbsp;        _dd_cnt=${#known_address[@]}
 659&nbsp;        for (( _dd = 0 ; _dd &#60; _dd_cnt ; _dd++ ))
 660&nbsp;        do
 661&nbsp;            printf '    A%04u [label="%s"] ;\n' \
 662&nbsp;                   "${_dd}" "${known_address[${_dd}]}" &#62;&#62;${_dot_file}
 663&nbsp;        done
 664&nbsp;    fi
 665&nbsp;
 666&nbsp;    echo                                   &#62;&#62;${_dot_file}
 667&nbsp;    echo '/*'                              &#62;&#62;${_dot_file}
 668&nbsp;    echo ' * Known relationships :: User conversion to'  &#62;&#62;${_dot_file}
 669&nbsp;    echo ' * graphic form by hand or program required.'  &#62;&#62;${_dot_file}
 670&nbsp;    echo ' *'                              &#62;&#62;${_dot_file}
 671&nbsp;
 672&nbsp;    if [ ${#auth_chain[@]} -gt 0 ]
 673&nbsp;    then
 674&nbsp;      echo &#62;&#62;${_dot_file}
 675&nbsp;      echo '# Authority ref. edges followed &#38; field source.' &#62;&#62;${_dot_file}
 676&nbsp;        dump_to_dot auth_chain AC
 677&nbsp;    fi
 678&nbsp;
 679&nbsp;    if [ ${#ref_chain[@]} -gt 0 ]
 680&nbsp;    then
 681&nbsp;        echo &#62;&#62;${_dot_file}
 682&nbsp;        echo '# Name ref. edges followed and field source.' &#62;&#62;${_dot_file}
 683&nbsp;        dump_to_dot ref_chain RC
 684&nbsp;    fi
 685&nbsp;
 686&nbsp;    if [ ${#name_address[@]} -gt 0 ]
 687&nbsp;    then
 688&nbsp;        echo &#62;&#62;${_dot_file}
 689&nbsp;        echo '# Known name-&#62;address edges' &#62;&#62;${_dot_file}
 690&nbsp;        dump_to_dot name_address NA
 691&nbsp;    fi
 692&nbsp;
 693&nbsp;    if [ ${#name_srvc[@]} -gt 0 ]
 694&nbsp;    then
 695&nbsp;        echo &#62;&#62;${_dot_file}
 696&nbsp;        echo '# Known name-&#62;service edges' &#62;&#62;${_dot_file}
 697&nbsp;        dump_to_dot name_srvc NS
 698&nbsp;    fi
 699&nbsp;
 700&nbsp;    if [ ${#name_resource[@]} -gt 0 ]
 701&nbsp;    then
 702&nbsp;        echo &#62;&#62;${_dot_file}
 703&nbsp;        echo '# Known name-&#62;resource edges' &#62;&#62;${_dot_file}
 704&nbsp;        dump_to_dot name_resource NR
 705&nbsp;    fi
 706&nbsp;
 707&nbsp;    if [ ${#parent_child[@]} -gt 0 ]
 708&nbsp;    then
 709&nbsp;        echo &#62;&#62;${_dot_file}
 710&nbsp;        echo '# Known parent-&#62;child edges' &#62;&#62;${_dot_file}
 711&nbsp;        dump_to_dot parent_child PC
 712&nbsp;    fi
 713&nbsp;
 714&nbsp;    if [ ${#list_server[@]} -gt 0 ]
 715&nbsp;    then
 716&nbsp;        echo &#62;&#62;${_dot_file}
 717&nbsp;        echo '# Known Blacklist nodes' &#62;&#62;${_dot_file}
 718&nbsp;        _dd_cnt=${#list_server[@]}
 719&nbsp;        for (( _dd = 0 ; _dd &#60; _dd_cnt ; _dd++ ))
 720&nbsp;        do
 721&nbsp;            printf '    LS%04u [label="%s"] ;\n' \
 722&nbsp;                   "${_dd}" "${list_server[${_dd}]}" &#62;&#62;${_dot_file}
 723&nbsp;        done
 724&nbsp;    fi
 725&nbsp;
 726&nbsp;    unique_lines address_hits address_hits
 727&nbsp;    if [ ${#address_hits[@]} -gt 0 ]
 728&nbsp;    then
 729&nbsp;      echo &#62;&#62;${_dot_file}
 730&nbsp;      echo '# Known address-&#62;Blacklist_hit edges' &#62;&#62;${_dot_file}
 731&nbsp;      echo '# CAUTION: dig warnings can trigger false hits.' &#62;&#62;${_dot_file}
 732&nbsp;       dump_to_dot address_hits AH
 733&nbsp;    fi
 734&nbsp;    echo          &#62;&#62;${_dot_file}
 735&nbsp;    echo ' *'     &#62;&#62;${_dot_file}
 736&nbsp;    echo ' * That is a lot of relationships. Happy graphing.' &#62;&#62;${_dot_file}
 737&nbsp;    echo ' */'    &#62;&#62;${_dot_file}
 738&nbsp;    echo '}'      &#62;&#62;${_dot_file}
 739&nbsp;    return 0
 740&nbsp;}
 741&nbsp;
 742&nbsp;# # # # 'Hunt the Spammer' execution flow # # # #
 743&nbsp;
 744&nbsp;#  Execution trace is enabled by setting the
 745&nbsp;#+ environment variable SPAMMER_TRACE to the name of a writable file.
 746&nbsp;declare -a _trace_log
 747&nbsp;declare _log_file
 748&nbsp;
 749&nbsp;# Function to fill the trace log
 750&nbsp;trace_logger() {
 751&nbsp;    _trace_log[${#_trace_log[@]}]=${_pend_current_}
 752&nbsp;}
 753&nbsp;
 754&nbsp;# Dump trace log to file function variable.
 755&nbsp;declare -f _log_dump
 756&nbsp;_log_dump=pend_dummy   # Initially a no-op.
 757&nbsp;
 758&nbsp;# Dump the trace log to a file.
 759&nbsp;dump_log() {
 760&nbsp;    local -i _dl_cnt
 761&nbsp;    _dl_cnt=${#_trace_log[@]}
 762&nbsp;    for (( _dl = 0 ; _dl &#60; _dl_cnt ; _dl++ ))
 763&nbsp;    do
 764&nbsp;        echo ${_trace_log[${_dl}]} &#62;&#62; ${_log_file}
 765&nbsp;    done
 766&nbsp;    _dl_cnt=${#_pending_[@]}
 767&nbsp;    if [ ${_dl_cnt} -gt 0 ]
 768&nbsp;    then
 769&nbsp;        _dl_cnt=${_dl_cnt}-1
 770&nbsp;        echo '# # # Operations stack not empty # # #' &#62;&#62; ${_log_file}
 771&nbsp;        for (( _dl = ${_dl_cnt} ; _dl &#62;= 0 ; _dl-- ))
 772&nbsp;        do
 773&nbsp;            echo ${_pending_[${_dl}]} &#62;&#62; ${_log_file}
 774&nbsp;        done
 775&nbsp;    fi
 776&nbsp;}
 777&nbsp;
 778&nbsp;# # # Utility program 'dig' wrappers # # #
 779&nbsp;#
 780&nbsp;#  These wrappers are derived from the
 781&nbsp;#+ examples shown in dig_wrappers.bash.
 782&nbsp;#
 783&nbsp;#  The major difference is these return
 784&nbsp;#+ their results as a list in an array.
 785&nbsp;#
 786&nbsp;#  See dig_wrappers.bash for details and
 787&nbsp;#+ use that script to develop any changes.
 788&nbsp;#
 789&nbsp;# # #
 790&nbsp;
 791&nbsp;# Short form answer: 'dig' parses answer.
 792&nbsp;
 793&nbsp;# Forward lookup :: Name -&#62; Address
 794&nbsp;# short_fwd &#60;domain_name&#62; &#60;array_name&#62;
 795&nbsp;short_fwd() {
 796&nbsp;    local -a _sf_reply
 797&nbsp;    local -i _sf_rc
 798&nbsp;    local -i _sf_cnt
 799&nbsp;    IFS=${NO_WSP}
 800&nbsp;echo -n '.'
 801&nbsp;# echo 'sfwd: '${1}
 802&nbsp;  _sf_reply=( $(dig +short ${1} -c in -t a 2&#62;/dev/null) )
 803&nbsp;  _sf_rc=$?
 804&nbsp;  if [ ${_sf_rc} -ne 0 ]
 805&nbsp;  then
 806&nbsp;    _trace_log[${#_trace_log[@]}]='## Lookup error '${_sf_rc}' on '${1}' ##'
 807&nbsp;# [ ${_sf_rc} -ne 9 ] &#38;&#38; pend_drop
 808&nbsp;        return ${_sf_rc}
 809&nbsp;    else
 810&nbsp;        # Some versions of 'dig' return warnings on stdout.
 811&nbsp;        _sf_cnt=${#_sf_reply[@]}
 812&nbsp;        for (( _sf = 0 ; _sf &#60; ${_sf_cnt} ; _sf++ ))
 813&nbsp;        do
 814&nbsp;            [ 'x'${_sf_reply[${_sf}]:0:2} == 'x;;' ] &#38;&#38;
 815&nbsp;                unset _sf_reply[${_sf}]
 816&nbsp;        done
 817&nbsp;        eval $2=\( \$\{_sf_reply\[@\]\} \)
 818&nbsp;    fi
 819&nbsp;    return 0
 820&nbsp;}
 821&nbsp;
 822&nbsp;# Reverse lookup :: Address -&#62; Name
 823&nbsp;# short_rev &#60;ip_address&#62; &#60;array_name&#62;
 824&nbsp;short_rev() {
 825&nbsp;    local -a _sr_reply
 826&nbsp;    local -i _sr_rc
 827&nbsp;    local -i _sr_cnt
 828&nbsp;    IFS=${NO_WSP}
 829&nbsp;echo -n '.'
 830&nbsp;# echo 'srev: '${1}
 831&nbsp;  _sr_reply=( $(dig +short -x ${1} 2&#62;/dev/null) )
 832&nbsp;  _sr_rc=$?
 833&nbsp;  if [ ${_sr_rc} -ne 0 ]
 834&nbsp;  then
 835&nbsp;    _trace_log[${#_trace_log[@]}]='## Lookup error '${_sr_rc}' on '${1}' ##'
 836&nbsp;# [ ${_sr_rc} -ne 9 ] &#38;&#38; pend_drop
 837&nbsp;        return ${_sr_rc}
 838&nbsp;    else
 839&nbsp;        # Some versions of 'dig' return warnings on stdout.
 840&nbsp;        _sr_cnt=${#_sr_reply[@]}
 841&nbsp;        for (( _sr = 0 ; _sr &#60; ${_sr_cnt} ; _sr++ ))
 842&nbsp;        do
 843&nbsp;            [ 'x'${_sr_reply[${_sr}]:0:2} == 'x;;' ] &#38;&#38;
 844&nbsp;                unset _sr_reply[${_sr}]
 845&nbsp;        done
 846&nbsp;        eval $2=\( \$\{_sr_reply\[@\]\} \)
 847&nbsp;    fi
 848&nbsp;    return 0
 849&nbsp;}
 850&nbsp;
 851&nbsp;# Special format lookup used to query blacklist servers.
 852&nbsp;# short_text &#60;ip_address&#62; &#60;array_name&#62;
 853&nbsp;short_text() {
 854&nbsp;    local -a _st_reply
 855&nbsp;    local -i _st_rc
 856&nbsp;    local -i _st_cnt
 857&nbsp;    IFS=${NO_WSP}
 858&nbsp;# echo 'stxt: '${1}
 859&nbsp;  _st_reply=( $(dig +short ${1} -c in -t txt 2&#62;/dev/null) )
 860&nbsp;  _st_rc=$?
 861&nbsp;  if [ ${_st_rc} -ne 0 ]
 862&nbsp;  then
 863&nbsp;    _trace_log[${#_trace_log[@]}]='##Text lookup error '${_st_rc}' on '${1}'##'
 864&nbsp;# [ ${_st_rc} -ne 9 ] &#38;&#38; pend_drop
 865&nbsp;        return ${_st_rc}
 866&nbsp;    else
 867&nbsp;        # Some versions of 'dig' return warnings on stdout.
 868&nbsp;        _st_cnt=${#_st_reply[@]}
 869&nbsp;        for (( _st = 0 ; _st &#60; ${#_st_cnt} ; _st++ ))
 870&nbsp;        do
 871&nbsp;            [ 'x'${_st_reply[${_st}]:0:2} == 'x;;' ] &#38;&#38;
 872&nbsp;                unset _st_reply[${_st}]
 873&nbsp;        done
 874&nbsp;        eval $2=\( \$\{_st_reply\[@\]\} \)
 875&nbsp;    fi
 876&nbsp;    return 0
 877&nbsp;}
 878&nbsp;
 879&nbsp;# The long forms, a.k.a., the parse it yourself versions
 880&nbsp;
 881&nbsp;# RFC 2782   Service lookups
 882&nbsp;# dig +noall +nofail +answer _ldap._tcp.openldap.org -t srv
 883&nbsp;# _&#60;service&#62;._&#60;protocol&#62;.&#60;domain_name&#62;
 884&nbsp;# _ldap._tcp.openldap.org. 3600   IN     SRV    0 0 389 ldap.openldap.org.
 885&nbsp;# domain TTL Class SRV Priority Weight Port Target
 886&nbsp;
 887&nbsp;# Forward lookup :: Name -&#62; poor man's zone transfer
 888&nbsp;# long_fwd &#60;domain_name&#62; &#60;array_name&#62;
 889&nbsp;long_fwd() {
 890&nbsp;    local -a _lf_reply
 891&nbsp;    local -i _lf_rc
 892&nbsp;    local -i _lf_cnt
 893&nbsp;    IFS=${NO_WSP}
 894&nbsp;echo -n ':'
 895&nbsp;# echo 'lfwd: '${1}
 896&nbsp;  _lf_reply=( $(
 897&nbsp;     dig +noall +nofail +answer +authority +additional \
 898&nbsp;         ${1} -t soa ${1} -t mx ${1} -t any 2&#62;/dev/null) )
 899&nbsp;  _lf_rc=$?
 900&nbsp;  if [ ${_lf_rc} -ne 0 ]
 901&nbsp;  then
 902&nbsp;    _trace_log[${#_trace_log[@]}]='# Zone lookup err '${_lf_rc}' on '${1}' #'
 903&nbsp;# [ ${_lf_rc} -ne 9 ] &#38;&#38; pend_drop
 904&nbsp;        return ${_lf_rc}
 905&nbsp;    else
 906&nbsp;        # Some versions of 'dig' return warnings on stdout.
 907&nbsp;        _lf_cnt=${#_lf_reply[@]}
 908&nbsp;        for (( _lf = 0 ; _lf &#60; ${_lf_cnt} ; _lf++ ))
 909&nbsp;        do
 910&nbsp;            [ 'x'${_lf_reply[${_lf}]:0:2} == 'x;;' ] &#38;&#38;
 911&nbsp;                unset _lf_reply[${_lf}]
 912&nbsp;        done
 913&nbsp;        eval $2=\( \$\{_lf_reply\[@\]\} \)
 914&nbsp;    fi
 915&nbsp;    return 0
 916&nbsp;}
 917&nbsp;#  The reverse lookup domain name corresponding to the IPv6 address:
 918&nbsp;#      4321:0:1:2:3:4:567:89ab
 919&nbsp;#  would be (nibble, I.E: Hexdigit) reversed:
 920&nbsp;#  b.a.9.8.7.6.5.0.4.0.0.0.3.0.0.0.2.0.0.0.1.0.0.0.0.0.0.0.1.2.3.4.IP6.ARPA.
 921&nbsp;
 922&nbsp;# Reverse lookup :: Address -&#62; poor man's delegation chain
 923&nbsp;# long_rev &#60;rev_ip_address&#62; &#60;array_name&#62;
 924&nbsp;long_rev() {
 925&nbsp;    local -a _lr_reply
 926&nbsp;    local -i _lr_rc
 927&nbsp;    local -i _lr_cnt
 928&nbsp;    local _lr_dns
 929&nbsp;    _lr_dns=${1}'.in-addr.arpa.'
 930&nbsp;    IFS=${NO_WSP}
 931&nbsp;echo -n ':'
 932&nbsp;# echo 'lrev: '${1}
 933&nbsp;  _lr_reply=( $(
 934&nbsp;       dig +noall +nofail +answer +authority +additional \
 935&nbsp;           ${_lr_dns} -t soa ${_lr_dns} -t any 2&#62;/dev/null) )
 936&nbsp;  _lr_rc=$?
 937&nbsp;  if [ ${_lr_rc} -ne 0 ]
 938&nbsp;  then
 939&nbsp;    _trace_log[${#_trace_log[@]}]='# Deleg lkp error '${_lr_rc}' on '${1}' #'
 940&nbsp;# [ ${_lr_rc} -ne 9 ] &#38;&#38; pend_drop
 941&nbsp;        return ${_lr_rc}
 942&nbsp;    else
 943&nbsp;        # Some versions of 'dig' return warnings on stdout.
 944&nbsp;        _lr_cnt=${#_lr_reply[@]}
 945&nbsp;        for (( _lr = 0 ; _lr &#60; ${_lr_cnt} ; _lr++ ))
 946&nbsp;        do
 947&nbsp;            [ 'x'${_lr_reply[${_lr}]:0:2} == 'x;;' ] &#38;&#38;
 948&nbsp;                unset _lr_reply[${_lr}]
 949&nbsp;        done
 950&nbsp;        eval $2=\( \$\{_lr_reply\[@\]\} \)
 951&nbsp;    fi
 952&nbsp;    return 0
 953&nbsp;}
 954&nbsp;
 955&nbsp;# # # Application specific functions # # #
 956&nbsp;
 957&nbsp;# Mung a possible name; suppresses root and TLDs.
 958&nbsp;# name_fixup &#60;string&#62;
 959&nbsp;name_fixup(){
 960&nbsp;    local -a _nf_tmp
 961&nbsp;    local -i _nf_end
 962&nbsp;    local _nf_str
 963&nbsp;    local IFS
 964&nbsp;    _nf_str=$(to_lower ${1})
 965&nbsp;    _nf_str=$(to_dot ${_nf_str})
 966&nbsp;    _nf_end=${#_nf_str}-1
 967&nbsp;    [ ${_nf_str:${_nf_end}} != '.' ] &#38;&#38;
 968&nbsp;        _nf_str=${_nf_str}'.'
 969&nbsp;    IFS=${ADR_IFS}
 970&nbsp;    _nf_tmp=( ${_nf_str} )
 971&nbsp;    IFS=${WSP_IFS}
 972&nbsp;    _nf_end=${#_nf_tmp[@]}
 973&nbsp;    case ${_nf_end} in
 974&nbsp;    0) # No dots, only dots.
 975&nbsp;        echo
 976&nbsp;        return 1
 977&nbsp;    ;;
 978&nbsp;    1) # Only a TLD.
 979&nbsp;        echo
 980&nbsp;        return 1
 981&nbsp;    ;;
 982&nbsp;    2) # Maybe okay.
 983&nbsp;       echo ${_nf_str}
 984&nbsp;       return 0
 985&nbsp;       # Needs a lookup table?
 986&nbsp;       if [ ${#_nf_tmp[1]} -eq 2 ]
 987&nbsp;       then # Country coded TLD.
 988&nbsp;           echo
 989&nbsp;           return 1
 990&nbsp;       else
 991&nbsp;           echo ${_nf_str}
 992&nbsp;           return 0
 993&nbsp;       fi
 994&nbsp;    ;;
 995&nbsp;    esac
 996&nbsp;    echo ${_nf_str}
 997&nbsp;    return 0
 998&nbsp;}
 999&nbsp;
 1000&nbsp;# Grope and mung original input(s).
 1001&nbsp;split_input() {
 1002&nbsp;    [ ${#uc_name[@]} -gt 0 ] || return 0
 1003&nbsp;    local -i _si_cnt
 1004&nbsp;    local -i _si_len
 1005&nbsp;    local _si_str
 1006&nbsp;    unique_lines uc_name uc_name
 1007&nbsp;    _si_cnt=${#uc_name[@]}
 1008&nbsp;    for (( _si = 0 ; _si &#60; _si_cnt ; _si++ ))
 1009&nbsp;    do
 1010&nbsp;        _si_str=${uc_name[$_si]}
 1011&nbsp;        if is_address ${_si_str}
 1012&nbsp;        then
 1013&nbsp;            uc_address[${#uc_address[@]}]=${_si_str}
 1014&nbsp;            unset uc_name[$_si]
 1015&nbsp;        else
 1016&nbsp;            if ! uc_name[$_si]=$(name_fixup ${_si_str})
 1017&nbsp;            then
 1018&nbsp;                unset ucname[$_si]
 1019&nbsp;            fi
 1020&nbsp;        fi
 1021&nbsp;    done
 1022&nbsp;  uc_name=( ${uc_name[@]} )
 1023&nbsp;  _si_cnt=${#uc_name[@]}
 1024&nbsp;  _trace_log[${#_trace_log[@]}]='#Input '${_si_cnt}' unchkd name input(s).#'
 1025&nbsp;  _si_cnt=${#uc_address[@]}
 1026&nbsp;  _trace_log[${#_trace_log[@]}]='#Input '${_si_cnt}' unchkd addr input(s).#'
 1027&nbsp;    return 0
 1028&nbsp;}
 1029&nbsp;
 1030&nbsp;# # # Discovery functions -- recursively interlocked by external data # # #
 1031&nbsp;# # # The leading 'if list is empty; return 0' in each is required. # # #
 1032&nbsp;
 1033&nbsp;# Recursion limiter
 1034&nbsp;# limit_chk() &#60;next_level&#62;
 1035&nbsp;limit_chk() {
 1036&nbsp;    local -i _lc_lmt
 1037&nbsp;    # Check indirection limit.
 1038&nbsp;    if [ ${indirect} -eq 0 ] || [ $# -eq 0 ]
 1039&nbsp;    then
 1040&nbsp;        # The 'do-forever' choice
 1041&nbsp;        echo 1                 # Any value will do.
 1042&nbsp;        return 0               # OK to continue.
 1043&nbsp;    else
 1044&nbsp;        # Limiting is in effect.
 1045&nbsp;        if [ ${indirect} -lt ${1} ]
 1046&nbsp;        then
 1047&nbsp;            echo ${1}          # Whatever.
 1048&nbsp;            return 1           # Stop here.
 1049&nbsp;        else
 1050&nbsp;            _lc_lmt=${1}+1     # Bump the given limit.
 1051&nbsp;            echo ${_lc_lmt}    # Echo it.
 1052&nbsp;            return 0           # OK to continue.
 1053&nbsp;        fi
 1054&nbsp;    fi
 1055&nbsp;}
 1056&nbsp;
 1057&nbsp;# For each name in uc_name:
 1058&nbsp;#     Move name to chk_name.
 1059&nbsp;#     Add addresses to uc_address.
 1060&nbsp;#     Pend expand_input_address.
 1061&nbsp;#     Repeat until nothing new found.
 1062&nbsp;# expand_input_name &#60;indirection_limit&#62;
 1063&nbsp;expand_input_name() {
 1064&nbsp;    [ ${#uc_name[@]} -gt 0 ] || return 0
 1065&nbsp;    local -a _ein_addr
 1066&nbsp;    local -a _ein_new
 1067&nbsp;    local -i _ucn_cnt
 1068&nbsp;    local -i _ein_cnt
 1069&nbsp;    local _ein_tst
 1070&nbsp;    _ucn_cnt=${#uc_name[@]}
 1071&nbsp;
 1072&nbsp;    if  ! _ein_cnt=$(limit_chk ${1})
 1073&nbsp;    then
 1074&nbsp;        return 0
 1075&nbsp;    fi
 1076&nbsp;
 1077&nbsp;    for (( _ein = 0 ; _ein &#60; _ucn_cnt ; _ein++ ))
 1078&nbsp;    do
 1079&nbsp;        if short_fwd ${uc_name[${_ein}]} _ein_new
 1080&nbsp;        then
 1081&nbsp;          for (( _ein_cnt = 0 ; _ein_cnt &#60; ${#_ein_new[@]}; _ein_cnt++ ))
 1082&nbsp;          do
 1083&nbsp;              _ein_tst=${_ein_new[${_ein_cnt}]}
 1084&nbsp;              if is_address ${_ein_tst}
 1085&nbsp;              then
 1086&nbsp;                  _ein_addr[${#_ein_addr[@]}]=${_ein_tst}
 1087&nbsp;              fi
 1088&nbsp;    done
 1089&nbsp;        fi
 1090&nbsp;    done
 1091&nbsp;    unique_lines _ein_addr _ein_addr     # Scrub duplicates.
 1092&nbsp;    edit_exact chk_address _ein_addr     # Scrub pending detail.
 1093&nbsp;    edit_exact known_address _ein_addr   # Scrub already detailed.
 1094&nbsp; if [ ${#_ein_addr[@]} -gt 0 ]        # Anything new?
 1095&nbsp; then
 1096&nbsp;   uc_address=( ${uc_address[@]} ${_ein_addr[@]} )
 1097&nbsp;   pend_func expand_input_address ${1}
 1098&nbsp;   _trace_log[${#_trace_log[@]}]='#Add '${#_ein_addr[@]}' unchkd addr inp.#'
 1099&nbsp;    fi
 1100&nbsp;    edit_exact chk_name uc_name          # Scrub pending detail.
 1101&nbsp;    edit_exact known_name uc_name        # Scrub already detailed.
 1102&nbsp;    if [ ${#uc_name[@]} -gt 0 ]
 1103&nbsp;    then
 1104&nbsp;        chk_name=( ${chk_name[@]} ${uc_name[@]}  )
 1105&nbsp;        pend_func detail_each_name ${1}
 1106&nbsp;    fi
 1107&nbsp;    unset uc_name[@]
 1108&nbsp;    return 0
 1109&nbsp;}
 1110&nbsp;
 1111&nbsp;# For each address in uc_address:
 1112&nbsp;#     Move address to chk_address.
 1113&nbsp;#     Add names to uc_name.
 1114&nbsp;#     Pend expand_input_name.
 1115&nbsp;#     Repeat until nothing new found.
 1116&nbsp;# expand_input_address &#60;indirection_limit&#62;
 1117&nbsp;expand_input_address() {
 1118&nbsp;    [ ${#uc_address[@]} -gt 0 ] || return 0
 1119&nbsp;    local -a _eia_addr
 1120&nbsp;    local -a _eia_name
 1121&nbsp;    local -a _eia_new
 1122&nbsp;    local -i _uca_cnt
 1123&nbsp;    local -i _eia_cnt
 1124&nbsp;    local _eia_tst
 1125&nbsp;    unique_lines uc_address _eia_addr
 1126&nbsp;    unset uc_address[@]
 1127&nbsp;    edit_exact been_there_addr _eia_addr
 1128&nbsp;    _uca_cnt=${#_eia_addr[@]}
 1129&nbsp;    [ ${_uca_cnt} -gt 0 ] &#38;&#38;
 1130&nbsp;        been_there_addr=( ${been_there_addr[@]} ${_eia_addr[@]} )
 1131&nbsp;
 1132&nbsp;    for (( _eia = 0 ; _eia &#60; _uca_cnt ; _eia++ ))
 1133&nbsp;     do
 1134&nbsp;       if short_rev ${_eia_addr[${_eia}]} _eia_new
 1135&nbsp;       then
 1136&nbsp;         for (( _eia_cnt = 0 ; _eia_cnt &#60; ${#_eia_new[@]} ; _eia_cnt++ ))
 1137&nbsp;         do
 1138&nbsp;           _eia_tst=${_eia_new[${_eia_cnt}]}
 1139&nbsp;           if _eia_tst=$(name_fixup ${_eia_tst})
 1140&nbsp;           then
 1141&nbsp;             _eia_name[${#_eia_name[@]}]=${_eia_tst}
 1142&nbsp;       fi
 1143&nbsp;     done
 1144&nbsp;           fi
 1145&nbsp;    done
 1146&nbsp;    unique_lines _eia_name _eia_name     # Scrub duplicates.
 1147&nbsp;    edit_exact chk_name _eia_name        # Scrub pending detail.
 1148&nbsp;    edit_exact known_name _eia_name      # Scrub already detailed.
 1149&nbsp; if [ ${#_eia_name[@]} -gt 0 ]        # Anything new?
 1150&nbsp; then
 1151&nbsp;   uc_name=( ${uc_name[@]} ${_eia_name[@]} )
 1152&nbsp;   pend_func expand_input_name ${1}
 1153&nbsp;   _trace_log[${#_trace_log[@]}]='#Add '${#_eia_name[@]}' unchkd name inp.#'
 1154&nbsp;    fi
 1155&nbsp;    edit_exact chk_address _eia_addr     # Scrub pending detail.
 1156&nbsp;    edit_exact known_address _eia_addr   # Scrub already detailed.
 1157&nbsp;    if [ ${#_eia_addr[@]} -gt 0 ]        # Anything new?
 1158&nbsp;    then
 1159&nbsp;        chk_address=( ${chk_address[@]} ${_eia_addr[@]} )
 1160&nbsp;        pend_func detail_each_address ${1}
 1161&nbsp;    fi
 1162&nbsp;    return 0
 1163&nbsp;}
 1164&nbsp;
 1165&nbsp;# The parse-it-yourself zone reply.
 1166&nbsp;# The input is the chk_name list.
 1167&nbsp;# detail_each_name &#60;indirection_limit&#62;
 1168&nbsp;detail_each_name() {
 1169&nbsp;    [ ${#chk_name[@]} -gt 0 ] || return 0
 1170&nbsp;    local -a _den_chk       # Names to check
 1171&nbsp;    local -a _den_name      # Names found here
 1172&nbsp;    local -a _den_address   # Addresses found here
 1173&nbsp;    local -a _den_pair      # Pairs found here
 1174&nbsp;    local -a _den_rev       # Reverse pairs found here
 1175&nbsp;    local -a _den_tmp       # Line being parsed
 1176&nbsp;    local -a _den_auth      # SOA contact being parsed
 1177&nbsp;    local -a _den_new       # The zone reply
 1178&nbsp;    local -a _den_pc        # Parent-Child gets big fast
 1179&nbsp;    local -a _den_ref       # So does reference chain
 1180&nbsp;    local -a _den_nr        # Name-Resource can be big
 1181&nbsp;    local -a _den_na        # Name-Address
 1182&nbsp;    local -a _den_ns        # Name-Service
 1183&nbsp;    local -a _den_achn      # Chain of Authority
 1184&nbsp;    local -i _den_cnt       # Count of names to detail
 1185&nbsp;    local -i _den_lmt       # Indirection limit
 1186&nbsp;    local _den_who          # Named being processed
 1187&nbsp;    local _den_rec          # Record type being processed
 1188&nbsp;    local _den_cont         # Contact domain
 1189&nbsp;    local _den_str          # Fixed up name string
 1190&nbsp;    local _den_str2         # Fixed up reverse
 1191&nbsp;    local IFS=${WSP_IFS}
 1192&nbsp;
 1193&nbsp;    # Local, unique copy of names to check
 1194&nbsp;    unique_lines chk_name _den_chk
 1195&nbsp;    unset chk_name[@]       # Done with globals.
 1196&nbsp;
 1197&nbsp;    # Less any names already known
 1198&nbsp;    edit_exact known_name _den_chk
 1199&nbsp;    _den_cnt=${#_den_chk[@]}
 1200&nbsp;
 1201&nbsp;    # If anything left, add to known_name.
 1202&nbsp;    [ ${_den_cnt} -gt 0 ] &#38;&#38;
 1203&nbsp;        known_name=( ${known_name[@]} ${_den_chk[@]} )
 1204&nbsp;
 1205&nbsp;    # for the list of (previously) unknown names . . .
 1206&nbsp;    for (( _den = 0 ; _den &#60; _den_cnt ; _den++ ))
 1207&nbsp;    do
 1208&nbsp;        _den_who=${_den_chk[${_den}]}
 1209&nbsp;        if long_fwd ${_den_who} _den_new
 1210&nbsp;        then
 1211&nbsp;            unique_lines _den_new _den_new
 1212&nbsp;            if [ ${#_den_new[@]} -eq 0 ]
 1213&nbsp;            then
 1214&nbsp;                _den_pair[${#_den_pair[@]}]='0.0.0.0 '${_den_who}
 1215&nbsp;            fi
 1216&nbsp;
 1217&nbsp;            # Parse each line in the reply.
 1218&nbsp;            for (( _line = 0 ; _line &#60; ${#_den_new[@]} ; _line++ ))
 1219&nbsp;            do
 1220&nbsp;                IFS=${NO_WSP}$'\x09'$'\x20'
 1221&nbsp;                _den_tmp=( ${_den_new[${_line}]} )
 1222&nbsp;                IFS=${WSP_IFS}
 1223&nbsp;              # If usable record and not a warning message . . .
 1224&nbsp;              if [ ${#_den_tmp[@]} -gt 4 ] &#38;&#38; [ 'x'${_den_tmp[0]} != 'x;;' ]
 1225&nbsp;              then
 1226&nbsp;                    _den_rec=${_den_tmp[3]}
 1227&nbsp;                    _den_nr[${#_den_nr[@]}]=${_den_who}' '${_den_rec}
 1228&nbsp;                    # Begin at RFC1033 (+++)
 1229&nbsp;                    case ${_den_rec} in
 1230&nbsp;
 1231&nbsp;#&#60;name&#62; [&#60;ttl&#62;]  [&#60;class&#62;] SOA &#60;origin&#62; &#60;person&#62;
 1232&nbsp;                    SOA) # Start Of Authority
 1233&nbsp;    if _den_str=$(name_fixup ${_den_tmp[0]})
 1234&nbsp;    then
 1235&nbsp;      _den_name[${#_den_name[@]}]=${_den_str}
 1236&nbsp;      _den_achn[${#_den_achn[@]}]=${_den_who}' '${_den_str}' SOA'
 1237&nbsp;      # SOA origin -- domain name of master zone record
 1238&nbsp;      if _den_str2=$(name_fixup ${_den_tmp[4]})
 1239&nbsp;      then
 1240&nbsp;        _den_name[${#_den_name[@]}]=${_den_str2}
 1241&nbsp;        _den_achn[${#_den_achn[@]}]=${_den_who}' '${_den_str2}' SOA.O'
 1242&nbsp;      fi
 1243&nbsp;      # Responsible party e-mail address (possibly bogus).
 1244&nbsp;      # Possibility of first.last@domain.name ignored.
 1245&nbsp;      set -f
 1246&nbsp;      if _den_str2=$(name_fixup ${_den_tmp[5]})
 1247&nbsp;      then
 1248&nbsp;        IFS=${ADR_IFS}
 1249&nbsp;        _den_auth=( ${_den_str2} )
 1250&nbsp;        IFS=${WSP_IFS}
 1251&nbsp;        if [ ${#_den_auth[@]} -gt 2 ]
 1252&nbsp;        then
 1253&nbsp;          _den_cont=${_den_auth[1]}
 1254&nbsp;          for (( _auth = 2 ; _auth &#60; ${#_den_auth[@]} ; _auth++ ))
 1255&nbsp;          do
 1256&nbsp;            _den_cont=${_den_cont}'.'${_den_auth[${_auth}]}
 1257&nbsp;          done
 1258&nbsp;          _den_name[${#_den_name[@]}]=${_den_cont}'.'
 1259&nbsp;          _den_achn[${#_den_achn[@]}]=${_den_who}' '${_den_cont}'. SOA.C'
 1260&nbsp;                                fi
 1261&nbsp;        fi
 1262&nbsp;        set +f
 1263&nbsp;                        fi
 1264&nbsp;                    ;;
 1265&nbsp;
 1266&nbsp;
 1267&nbsp;      A) # IP(v4) Address Record
 1268&nbsp;      if _den_str=$(name_fixup ${_den_tmp[0]})
 1269&nbsp;      then
 1270&nbsp;        _den_name[${#_den_name[@]}]=${_den_str}
 1271&nbsp;        _den_pair[${#_den_pair[@]}]=${_den_tmp[4]}' '${_den_str}
 1272&nbsp;        _den_na[${#_den_na[@]}]=${_den_str}' '${_den_tmp[4]}
 1273&nbsp;        _den_ref[${#_den_ref[@]}]=${_den_who}' '${_den_str}' A'
 1274&nbsp;      else
 1275&nbsp;        _den_pair[${#_den_pair[@]}]=${_den_tmp[4]}' unknown.domain'
 1276&nbsp;        _den_na[${#_den_na[@]}]='unknown.domain '${_den_tmp[4]}
 1277&nbsp;        _den_ref[${#_den_ref[@]}]=${_den_who}' unknown.domain A'
 1278&nbsp;      fi
 1279&nbsp;      _den_address[${#_den_address[@]}]=${_den_tmp[4]}
 1280&nbsp;      _den_pc[${#_den_pc[@]}]=${_den_who}' '${_den_tmp[4]}
 1281&nbsp;             ;;
 1282&nbsp;
 1283&nbsp;             NS) # Name Server Record
 1284&nbsp;             # Domain name being serviced (may be other than current)
 1285&nbsp;               if _den_str=$(name_fixup ${_den_tmp[0]})
 1286&nbsp;                 then
 1287&nbsp;                   _den_name[${#_den_name[@]}]=${_den_str}
 1288&nbsp;                   _den_ref[${#_den_ref[@]}]=${_den_who}' '${_den_str}' NS'
 1289&nbsp;
 1290&nbsp;             # Domain name of service provider
 1291&nbsp;             if _den_str2=$(name_fixup ${_den_tmp[4]})
 1292&nbsp;             then
 1293&nbsp;               _den_name[${#_den_name[@]}]=${_den_str2}
 1294&nbsp;               _den_ref[${#_den_ref[@]}]=${_den_who}' '${_den_str2}' NSH'
 1295&nbsp;               _den_ns[${#_den_ns[@]}]=${_den_str2}' NS'
 1296&nbsp;               _den_pc[${#_den_pc[@]}]=${_den_str}' '${_den_str2}
 1297&nbsp;              fi
 1298&nbsp;               fi
 1299&nbsp;                    ;;
 1300&nbsp;
 1301&nbsp;             MX) # Mail Server Record
 1302&nbsp;                 # Domain name being serviced (wildcards not handled here)
 1303&nbsp;             if _den_str=$(name_fixup ${_den_tmp[0]})
 1304&nbsp;             then
 1305&nbsp;               _den_name[${#_den_name[@]}]=${_den_str}
 1306&nbsp;               _den_ref[${#_den_ref[@]}]=${_den_who}' '${_den_str}' MX'
 1307&nbsp;             fi
 1308&nbsp;             # Domain name of service provider
 1309&nbsp;             if _den_str=$(name_fixup ${_den_tmp[5]})
 1310&nbsp;             then
 1311&nbsp;               _den_name[${#_den_name[@]}]=${_den_str}
 1312&nbsp;               _den_ref[${#_den_ref[@]}]=${_den_who}' '${_den_str}' MXH'
 1313&nbsp;               _den_ns[${#_den_ns[@]}]=${_den_str}' MX'
 1314&nbsp;               _den_pc[${#_den_pc[@]}]=${_den_who}' '${_den_str}
 1315&nbsp;             fi
 1316&nbsp;                    ;;
 1317&nbsp;
 1318&nbsp;             PTR) # Reverse address record
 1319&nbsp;                  # Special name
 1320&nbsp;             if _den_str=$(name_fixup ${_den_tmp[0]})
 1321&nbsp;             then
 1322&nbsp;               _den_ref[${#_den_ref[@]}]=${_den_who}' '${_den_str}' PTR'
 1323&nbsp;               # Host name (not a CNAME)
 1324&nbsp;               if _den_str2=$(name_fixup ${_den_tmp[4]})
 1325&nbsp;               then
 1326&nbsp;                 _den_rev[${#_den_rev[@]}]=${_den_str}' '${_den_str2}
 1327&nbsp;                 _den_ref[${#_den_ref[@]}]=${_den_who}' '${_den_str2}' PTRH'
 1328&nbsp;                 _den_pc[${#_den_pc[@]}]=${_den_who}' '${_den_str}
 1329&nbsp;               fi
 1330&nbsp;             fi
 1331&nbsp;                    ;;
 1332&nbsp;
 1333&nbsp;             AAAA) # IP(v6) Address Record
 1334&nbsp;             if _den_str=$(name_fixup ${_den_tmp[0]})
 1335&nbsp;             then
 1336&nbsp;               _den_name[${#_den_name[@]}]=${_den_str}
 1337&nbsp;               _den_pair[${#_den_pair[@]}]=${_den_tmp[4]}' '${_den_str}
 1338&nbsp;               _den_na[${#_den_na[@]}]=${_den_str}' '${_den_tmp[4]}
 1339&nbsp;               _den_ref[${#_den_ref[@]}]=${_den_who}' '${_den_str}' AAAA'
 1340&nbsp;               else
 1341&nbsp;                 _den_pair[${#_den_pair[@]}]=${_den_tmp[4]}' unknown.domain'
 1342&nbsp;                 _den_na[${#_den_na[@]}]='unknown.domain '${_den_tmp[4]}
 1343&nbsp;                 _den_ref[${#_den_ref[@]}]=${_den_who}' unknown.domain'
 1344&nbsp;               fi
 1345&nbsp;               # No processing for IPv6 addresses
 1346&nbsp;               _den_pc[${#_den_pc[@]}]=${_den_who}' '${_den_tmp[4]}
 1347&nbsp;                    ;;
 1348&nbsp;
 1349&nbsp;             CNAME) # Alias name record
 1350&nbsp;                    # Nickname
 1351&nbsp;             if _den_str=$(name_fixup ${_den_tmp[0]})
 1352&nbsp;             then
 1353&nbsp;               _den_name[${#_den_name[@]}]=${_den_str}
 1354&nbsp;               _den_ref[${#_den_ref[@]}]=${_den_who}' '${_den_str}' CNAME'
 1355&nbsp;               _den_pc[${#_den_pc[@]}]=${_den_who}' '${_den_str}
 1356&nbsp;             fi
 1357&nbsp;                    # Hostname
 1358&nbsp;             if _den_str=$(name_fixup ${_den_tmp[4]})
 1359&nbsp;             then
 1360&nbsp;               _den_name[${#_den_name[@]}]=${_den_str}
 1361&nbsp;               _den_ref[${#_den_ref[@]}]=${_den_who}' '${_den_str}' CHOST'
 1362&nbsp;               _den_pc[${#_den_pc[@]}]=${_den_who}' '${_den_str}
 1363&nbsp;             fi
 1364&nbsp;                    ;;
 1365&nbsp;#            TXT)
 1366&nbsp;#            ;;
 1367&nbsp;                    esac
 1368&nbsp;                fi
 1369&nbsp;            done
 1370&nbsp;        else # Lookup error == 'A' record 'unknown address'
 1371&nbsp;            _den_pair[${#_den_pair[@]}]='0.0.0.0 '${_den_who}
 1372&nbsp;        fi
 1373&nbsp;    done
 1374&nbsp;
 1375&nbsp;    # Control dot array growth.
 1376&nbsp;    unique_lines _den_achn _den_achn      # Works best, all the same.
 1377&nbsp;    edit_exact auth_chain _den_achn       # Works best, unique items.
 1378&nbsp;    if [ ${#_den_achn[@]} -gt 0 ]
 1379&nbsp;    then
 1380&nbsp;        IFS=${NO_WSP}
 1381&nbsp;        auth_chain=( ${auth_chain[@]} ${_den_achn[@]} )
 1382&nbsp;        IFS=${WSP_IFS}
 1383&nbsp;    fi
 1384&nbsp;
 1385&nbsp;    unique_lines _den_ref _den_ref      # Works best, all the same.
 1386&nbsp;    edit_exact ref_chain _den_ref       # Works best, unique items.
 1387&nbsp;    if [ ${#_den_ref[@]} -gt 0 ]
 1388&nbsp;    then
 1389&nbsp;        IFS=${NO_WSP}
 1390&nbsp;        ref_chain=( ${ref_chain[@]} ${_den_ref[@]} )
 1391&nbsp;        IFS=${WSP_IFS}
 1392&nbsp;    fi
 1393&nbsp;
 1394&nbsp;    unique_lines _den_na _den_na
 1395&nbsp;    edit_exact name_address _den_na
 1396&nbsp;    if [ ${#_den_na[@]} -gt 0 ]
 1397&nbsp;    then
 1398&nbsp;        IFS=${NO_WSP}
 1399&nbsp;        name_address=( ${name_address[@]} ${_den_na[@]} )
 1400&nbsp;        IFS=${WSP_IFS}
 1401&nbsp;    fi
 1402&nbsp;
 1403&nbsp;    unique_lines _den_ns _den_ns
 1404&nbsp;    edit_exact name_srvc _den_ns
 1405&nbsp;    if [ ${#_den_ns[@]} -gt 0 ]
 1406&nbsp;    then
 1407&nbsp;        IFS=${NO_WSP}
 1408&nbsp;        name_srvc=( ${name_srvc[@]} ${_den_ns[@]} )
 1409&nbsp;        IFS=${WSP_IFS}
 1410&nbsp;    fi
 1411&nbsp;
 1412&nbsp;    unique_lines _den_nr _den_nr
 1413&nbsp;    edit_exact name_resource _den_nr
 1414&nbsp;    if [ ${#_den_nr[@]} -gt 0 ]
 1415&nbsp;    then
 1416&nbsp;        IFS=${NO_WSP}
 1417&nbsp;        name_resource=( ${name_resource[@]} ${_den_nr[@]} )
 1418&nbsp;        IFS=${WSP_IFS}
 1419&nbsp;    fi
 1420&nbsp;
 1421&nbsp;    unique_lines _den_pc _den_pc
 1422&nbsp;    edit_exact parent_child _den_pc
 1423&nbsp;    if [ ${#_den_pc[@]} -gt 0 ]
 1424&nbsp;    then
 1425&nbsp;        IFS=${NO_WSP}
 1426&nbsp;        parent_child=( ${parent_child[@]} ${_den_pc[@]} )
 1427&nbsp;        IFS=${WSP_IFS}
 1428&nbsp;    fi
 1429&nbsp;
 1430&nbsp;    # Update list known_pair (Address and Name).
 1431&nbsp;    unique_lines _den_pair _den_pair
 1432&nbsp;    edit_exact known_pair _den_pair
 1433&nbsp;    if [ ${#_den_pair[@]} -gt 0 ]  # Anything new?
 1434&nbsp;    then
 1435&nbsp;        IFS=${NO_WSP}
 1436&nbsp;        known_pair=( ${known_pair[@]} ${_den_pair[@]} )
 1437&nbsp;        IFS=${WSP_IFS}
 1438&nbsp;    fi
 1439&nbsp;
 1440&nbsp;    # Update list of reverse pairs.
 1441&nbsp;    unique_lines _den_rev _den_rev
 1442&nbsp;    edit_exact reverse_pair _den_rev
 1443&nbsp;    if [ ${#_den_rev[@]} -gt 0 ]   # Anything new?
 1444&nbsp;    then
 1445&nbsp;        IFS=${NO_WSP}
 1446&nbsp;        reverse_pair=( ${reverse_pair[@]} ${_den_rev[@]} )
 1447&nbsp;        IFS=${WSP_IFS}
 1448&nbsp;    fi
 1449&nbsp;
 1450&nbsp;    # Check indirection limit -- give up if reached.
 1451&nbsp;    if ! _den_lmt=$(limit_chk ${1})
 1452&nbsp;    then
 1453&nbsp;        return 0
 1454&nbsp;    fi
 1455&nbsp;
 1456&nbsp;# Execution engine is LIFO. Order of pend operations is important.
 1457&nbsp;# Did we define any new addresses?
 1458&nbsp;unique_lines _den_address _den_address    # Scrub duplicates.
 1459&nbsp;edit_exact known_address _den_address     # Scrub already processed.
 1460&nbsp;edit_exact un_address _den_address        # Scrub already waiting.
 1461&nbsp;if [ ${#_den_address[@]} -gt 0 ]          # Anything new?
 1462&nbsp;then
 1463&nbsp;  uc_address=( ${uc_address[@]} ${_den_address[@]} )
 1464&nbsp;  pend_func expand_input_address ${_den_lmt}
 1465&nbsp;  _trace_log[${#_trace_log[@]}]='# Add '${#_den_address[@]}' unchkd addr. #'
 1466&nbsp;    fi
 1467&nbsp;
 1468&nbsp;# Did we find any new names?
 1469&nbsp;unique_lines _den_name _den_name          # Scrub duplicates.
 1470&nbsp;edit_exact known_name _den_name           # Scrub already processed.
 1471&nbsp;edit_exact uc_name _den_name              # Scrub already waiting.
 1472&nbsp;if [ ${#_den_name[@]} -gt 0 ]             # Anything new?
 1473&nbsp;then
 1474&nbsp;  uc_name=( ${uc_name[@]} ${_den_name[@]} )
 1475&nbsp;  pend_func expand_input_name ${_den_lmt}
 1476&nbsp;  _trace_log[${#_trace_log[@]}]='#Added '${#_den_name[@]}' unchkd name#'
 1477&nbsp;    fi
 1478&nbsp;    return 0
 1479&nbsp;}
 1480&nbsp;
 1481&nbsp;# The parse-it-yourself delegation reply
 1482&nbsp;# Input is the chk_address list.
 1483&nbsp;# detail_each_address &#60;indirection_limit&#62;
 1484&nbsp;detail_each_address() {
 1485&nbsp;    [ ${#chk_address[@]} -gt 0 ] || return 0
 1486&nbsp;    unique_lines chk_address chk_address
 1487&nbsp;    edit_exact known_address chk_address
 1488&nbsp;    if [ ${#chk_address[@]} -gt 0 ]
 1489&nbsp;    then
 1490&nbsp;        known_address=( ${known_address[@]} ${chk_address[@]} )
 1491&nbsp;        unset chk_address[@]
 1492&nbsp;    fi
 1493&nbsp;    return 0
 1494&nbsp;}
 1495&nbsp;
 1496&nbsp;# # # Application specific output functions # # #
 1497&nbsp;
 1498&nbsp;# Pretty print the known pairs.
 1499&nbsp;report_pairs() {
 1500&nbsp;    echo
 1501&nbsp;    echo 'Known network pairs.'
 1502&nbsp;    col_print known_pair 2 5 30
 1503&nbsp;
 1504&nbsp;    if [ ${#auth_chain[@]} -gt 0 ]
 1505&nbsp;    then
 1506&nbsp;        echo
 1507&nbsp;        echo 'Known chain of authority.'
 1508&nbsp;        col_print auth_chain 2 5 30 55
 1509&nbsp;    fi
 1510&nbsp;
 1511&nbsp;    if [ ${#reverse_pair[@]} -gt 0 ]
 1512&nbsp;    then
 1513&nbsp;        echo
 1514&nbsp;        echo 'Known reverse pairs.'
 1515&nbsp;        col_print reverse_pair 2 5 55
 1516&nbsp;    fi
 1517&nbsp;    return 0
 1518&nbsp;}
 1519&nbsp;
 1520&nbsp;# Check an address against the list of blacklist servers.
 1521&nbsp;# A good place to capture for GraphViz: address-&#62;status(server(reports))
 1522&nbsp;# check_lists &#60;ip_address&#62;
 1523&nbsp;check_lists() {
 1524&nbsp;    [ $# -eq 1 ] || return 1
 1525&nbsp;    local -a _cl_fwd_addr
 1526&nbsp;    local -a _cl_rev_addr
 1527&nbsp;    local -a _cl_reply
 1528&nbsp;    local -i _cl_rc
 1529&nbsp;    local -i _ls_cnt
 1530&nbsp;    local _cl_dns_addr
 1531&nbsp;    local _cl_lkup
 1532&nbsp;
 1533&nbsp;    split_ip ${1} _cl_fwd_addr _cl_rev_addr
 1534&nbsp;    _cl_dns_addr=$(dot_array _cl_rev_addr)'.'
 1535&nbsp;    _ls_cnt=${#list_server[@]}
 1536&nbsp;    echo '    Checking address '${1}
 1537&nbsp;    for (( _cl = 0 ; _cl &#60; _ls_cnt ; _cl++ ))
 1538&nbsp;    do
 1539&nbsp;      _cl_lkup=${_cl_dns_addr}${list_server[${_cl}]}
 1540&nbsp;      if short_text ${_cl_lkup} _cl_reply
 1541&nbsp;      then
 1542&nbsp;        if [ ${#_cl_reply[@]} -gt 0 ]
 1543&nbsp;        then
 1544&nbsp;          echo '        Records from '${list_server[${_cl}]}
 1545&nbsp;          address_hits[${#address_hits[@]}]=${1}' '${list_server[${_cl}]}
 1546&nbsp;          _hs_RC=2
 1547&nbsp;          for (( _clr = 0 ; _clr &#60; ${#_cl_reply[@]} ; _clr++ ))
 1548&nbsp;          do
 1549&nbsp;            echo '            '${_cl_reply[${_clr}]}
 1550&nbsp;          done
 1551&nbsp;        fi
 1552&nbsp;      fi
 1553&nbsp;    done
 1554&nbsp;    return 0
 1555&nbsp;}
 1556&nbsp;
 1557&nbsp;# # # The usual application glue # # #
 1558&nbsp;
 1559&nbsp;# Who did it?
 1560&nbsp;credits() {
 1561&nbsp;   echo
 1562&nbsp;   echo 'Advanced Bash Scripting Guide: is_spammer.bash, v2, 2004-msz'
 1563&nbsp;}
 1564&nbsp;
 1565&nbsp;# How to use it?
 1566&nbsp;# (See also, "Quickstart" at end of script.)
 1567&nbsp;usage() {
 1568&nbsp;    cat &#60;&#60;-'_usage_statement_'
 1569&nbsp;    The script is_spammer.bash requires either one or two arguments.
 1570&nbsp;
 1571&nbsp;    arg 1) May be one of:
 1572&nbsp;        a) A domain name
 1573&nbsp;        b) An IPv4 address
 1574&nbsp;        c) The name of a file with any mix of names
 1575&nbsp;           and addresses, one per line.
 1576&nbsp;
 1577&nbsp;    arg 2) May be one of:
 1578&nbsp;        a) A Blacklist server domain name
 1579&nbsp;        b) The name of a file with Blacklist server
 1580&nbsp;           domain names, one per line.
 1581&nbsp;        c) If not present, a default list of (free)
 1582&nbsp;           Blacklist servers is used.
 1583&nbsp;        d) If a filename of an empty, readable, file
 1584&nbsp;           is given,
 1585&nbsp;           Blacklist server lookup is disabled.
 1586&nbsp;
 1587&nbsp;    All script output is written to stdout.
 1588&nbsp;
 1589&nbsp;    Return codes: 0 -&#62; All OK, 1 -&#62; Script failure,
 1590&nbsp;                  2 -&#62; Something is Blacklisted.
 1591&nbsp;
 1592&nbsp;    Requires the external program 'dig' from the 'bind-9'
 1593&nbsp;    set of DNS programs.  See: http://www.isc.org
 1594&nbsp;
 1595&nbsp;    The domain name lookup depth limit defaults to 2 levels.
 1596&nbsp;    Set the environment variable SPAMMER_LIMIT to change.
 1597&nbsp;    SPAMMER_LIMIT=0 means 'unlimited'
 1598&nbsp;
 1599&nbsp;    Limit may also be set on the command-line.
 1600&nbsp;    If arg#1 is an integer, the limit is set to that value
 1601&nbsp;    and then the above argument rules are applied.
 1602&nbsp;
 1603&nbsp;    Setting the environment variable 'SPAMMER_DATA' to a filename
 1604&nbsp;    will cause the script to write a GraphViz graphic file.
 1605&nbsp;
 1606&nbsp;    For the development version;
 1607&nbsp;    Setting the environment variable 'SPAMMER_TRACE' to a filename
 1608&nbsp;    will cause the execution engine to log a function call trace.
 1609&nbsp;
 1610&nbsp;_usage_statement_
 1611&nbsp;}
 1612&nbsp;
 1613&nbsp;# The default list of Blacklist servers:
 1614&nbsp;# Many choices, see: http://www.spews.org/lists.html
 1615&nbsp;
 1616&nbsp;declare -a default_servers
 1617&nbsp;# See: http://www.spamhaus.org (Conservative, well maintained)
 1618&nbsp;default_servers[0]='sbl-xbl.spamhaus.org'
 1619&nbsp;# See: http://ordb.org (Open mail relays)
 1620&nbsp;default_servers[1]='relays.ordb.org'
 1621&nbsp;# See: http://www.spamcop.net/ (You can report spammers here)
 1622&nbsp;default_servers[2]='bl.spamcop.net'
 1623&nbsp;# See: http://www.spews.org (An 'early detect' system)
 1624&nbsp;default_servers[3]='l2.spews.dnsbl.sorbs.net'
 1625&nbsp;# See: http://www.dnsbl.us.sorbs.net/using.shtml
 1626&nbsp;default_servers[4]='dnsbl.sorbs.net'
 1627&nbsp;# See: http://dsbl.org/usage (Various mail relay lists)
 1628&nbsp;default_servers[5]='list.dsbl.org'
 1629&nbsp;default_servers[6]='multihop.dsbl.org'
 1630&nbsp;default_servers[7]='unconfirmed.dsbl.org'
 1631&nbsp;
 1632&nbsp;# User input argument #1
 1633&nbsp;setup_input() {
 1634&nbsp;    if [ -e ${1} ] &#38;&#38; [ -r ${1} ]  # Name of readable file
 1635&nbsp;    then
 1636&nbsp;        file_to_array ${1} uc_name
 1637&nbsp;        echo 'Using filename &#62;'${1}'&#60; as input.'
 1638&nbsp;    else
 1639&nbsp;        if is_address ${1}          # IP address?
 1640&nbsp;        then
 1641&nbsp;            uc_address=( ${1} )
 1642&nbsp;            echo 'Starting with address &#62;'${1}'&#60;'
 1643&nbsp;        else                       # Must be a name.
 1644&nbsp;            uc_name=( ${1} )
 1645&nbsp;            echo 'Starting with domain name &#62;'${1}'&#60;'
 1646&nbsp;        fi
 1647&nbsp;    fi
 1648&nbsp;    return 0
 1649&nbsp;}
 1650&nbsp;
 1651&nbsp;# User input argument #2
 1652&nbsp;setup_servers() {
 1653&nbsp;    if [ -e ${1} ] &#38;&#38; [ -r ${1} ]  # Name of a readable file
 1654&nbsp;    then
 1655&nbsp;        file_to_array ${1} list_server
 1656&nbsp;        echo 'Using filename &#62;'${1}'&#60; as blacklist server list.'
 1657&nbsp;    else
 1658&nbsp;        list_server=( ${1} )
 1659&nbsp;        echo 'Using blacklist server &#62;'${1}'&#60;'
 1660&nbsp;    fi
 1661&nbsp;    return 0
 1662&nbsp;}
 1663&nbsp;
 1664&nbsp;# User environment variable SPAMMER_TRACE
 1665&nbsp;live_log_die() {
 1666&nbsp;    if [ ${SPAMMER_TRACE:=} ]    # Wants trace log?
 1667&nbsp;    then
 1668&nbsp;        if [ ! -e ${SPAMMER_TRACE} ]
 1669&nbsp;        then
 1670&nbsp;            if ! touch ${SPAMMER_TRACE} 2&#62;/dev/null
 1671&nbsp;            then
 1672&nbsp;                pend_func echo $(printf '%q\n' \
 1673&nbsp;                'Unable to create log file &#62;'${SPAMMER_TRACE}'&#60;')
 1674&nbsp;                pend_release
 1675&nbsp;                exit 1
 1676&nbsp;            fi
 1677&nbsp;            _log_file=${SPAMMER_TRACE}
 1678&nbsp;            _pend_hook_=trace_logger
 1679&nbsp;            _log_dump=dump_log
 1680&nbsp;        else
 1681&nbsp;            if [ ! -w ${SPAMMER_TRACE} ]
 1682&nbsp;            then
 1683&nbsp;                pend_func echo $(printf '%q\n' \
 1684&nbsp;                'Unable to write log file &#62;'${SPAMMER_TRACE}'&#60;')
 1685&nbsp;                pend_release
 1686&nbsp;                exit 1
 1687&nbsp;            fi
 1688&nbsp;            _log_file=${SPAMMER_TRACE}
 1689&nbsp;            echo '' &#62; ${_log_file}
 1690&nbsp;            _pend_hook_=trace_logger
 1691&nbsp;            _log_dump=dump_log
 1692&nbsp;        fi
 1693&nbsp;    fi
 1694&nbsp;    return 0
 1695&nbsp;}
 1696&nbsp;
 1697&nbsp;# User environment variable SPAMMER_DATA
 1698&nbsp;data_capture() {
 1699&nbsp;    if [ ${SPAMMER_DATA:=} ]    # Wants a data dump?
 1700&nbsp;    then
 1701&nbsp;        if [ ! -e ${SPAMMER_DATA} ]
 1702&nbsp;        then
 1703&nbsp;            if ! touch ${SPAMMER_DATA} 2&#62;/dev/null
 1704&nbsp;            then
 1705&nbsp;                pend_func echo $(printf '%q]n' \
 1706&nbsp;                'Unable to create data output file &#62;'${SPAMMER_DATA}'&#60;')
 1707&nbsp;                pend_release
 1708&nbsp;                exit 1
 1709&nbsp;            fi
 1710&nbsp;            _dot_file=${SPAMMER_DATA}
 1711&nbsp;            _dot_dump=dump_dot
 1712&nbsp;        else
 1713&nbsp;            if [ ! -w ${SPAMMER_DATA} ]
 1714&nbsp;            then
 1715&nbsp;                pend_func echo $(printf '%q\n' \
 1716&nbsp;                'Unable to write data output file &#62;'${SPAMMER_DATA}'&#60;')
 1717&nbsp;                pend_release
 1718&nbsp;                exit 1
 1719&nbsp;            fi
 1720&nbsp;            _dot_file=${SPAMMER_DATA}
 1721&nbsp;            _dot_dump=dump_dot
 1722&nbsp;        fi
 1723&nbsp;    fi
 1724&nbsp;    return 0
 1725&nbsp;}
 1726&nbsp;
 1727&nbsp;# Grope user specified arguments.
 1728&nbsp;do_user_args() {
 1729&nbsp;    if [ $# -gt 0 ] &#38;&#38; is_number $1
 1730&nbsp;    then
 1731&nbsp;        indirect=$1
 1732&nbsp;        shift
 1733&nbsp;    fi
 1734&nbsp;
 1735&nbsp;    case $# in                     # Did user treat us well?
 1736&nbsp;        1)
 1737&nbsp;            if ! setup_input $1    # Needs error checking.
 1738&nbsp;            then
 1739&nbsp;                pend_release
 1740&nbsp;                $_log_dump
 1741&nbsp;                exit 1
 1742&nbsp;            fi
 1743&nbsp;            list_server=( ${default_servers[@]} )
 1744&nbsp;            _list_cnt=${#list_server[@]}
 1745&nbsp;            echo 'Using default blacklist server list.'
 1746&nbsp;            echo 'Search depth limit: '${indirect}
 1747&nbsp;            ;;
 1748&nbsp;        2)
 1749&nbsp;            if ! setup_input $1    # Needs error checking.
 1750&nbsp;            then
 1751&nbsp;                pend_release
 1752&nbsp;                $_log_dump
 1753&nbsp;                exit 1
 1754&nbsp;            fi
 1755&nbsp;            if ! setup_servers $2  # Needs error checking.
 1756&nbsp;            then
 1757&nbsp;                pend_release
 1758&nbsp;                $_log_dump
 1759&nbsp;                exit 1
 1760&nbsp;            fi
 1761&nbsp;            echo 'Search depth limit: '${indirect}
 1762&nbsp;            ;;
 1763&nbsp;        *)
 1764&nbsp;            pend_func usage
 1765&nbsp;            pend_release
 1766&nbsp;            $_log_dump
 1767&nbsp;            exit 1
 1768&nbsp;            ;;
 1769&nbsp;    esac
 1770&nbsp;    return 0
 1771&nbsp;}
 1772&nbsp;
 1773&nbsp;# A general purpose debug tool.
 1774&nbsp;# list_array &#60;array_name&#62;
 1775&nbsp;list_array() {
 1776&nbsp;    [ $# -eq 1 ] || return 1  # One argument required.
 1777&nbsp;
 1778&nbsp;    local -a _la_lines
 1779&nbsp;    set -f
 1780&nbsp;    local IFS=${NO_WSP}
 1781&nbsp;    eval _la_lines=\(\ \$\{$1\[@\]\}\ \)
 1782&nbsp;    echo
 1783&nbsp;    echo "Element count "${#_la_lines[@]}" array "${1}
 1784&nbsp;    local _ln_cnt=${#_la_lines[@]}
 1785&nbsp;
 1786&nbsp;    for (( _i = 0; _i &#60; ${_ln_cnt}; _i++ ))
 1787&nbsp;    do
 1788&nbsp;        echo 'Element '$_i' &#62;'${_la_lines[$_i]}'&#60;'
 1789&nbsp;    done
 1790&nbsp;    set +f
 1791&nbsp;    return 0
 1792&nbsp;}
 1793&nbsp;
 1794&nbsp;# # # 'Hunt the Spammer' program code # # #
 1795&nbsp;pend_init                               # Ready stack engine.
 1796&nbsp;pend_func credits                       # Last thing to print.
 1797&nbsp;
 1798&nbsp;# # # Deal with user # # #
 1799&nbsp;live_log_die                            # Setup debug trace log.
 1800&nbsp;data_capture                            # Setup data capture file.
 1801&nbsp;echo
 1802&nbsp;do_user_args $@
 1803&nbsp;
 1804&nbsp;# # # Haven't exited yet - There is some hope # # #
 1805&nbsp;# Discovery group - Execution engine is LIFO - pend
 1806&nbsp;# in reverse order of execution.
 1807&nbsp;_hs_RC=0                                # Hunt the Spammer return code
 1808&nbsp;pend_mark
 1809&nbsp;    pend_func report_pairs              # Report name-address pairs.
 1810&nbsp;
 1811&nbsp;    # The two detail_* are mutually recursive functions.
 1812&nbsp;    # They also pend expand_* functions as required.
 1813&nbsp;    # These two (the last of ???) exit the recursion.
 1814&nbsp;    pend_func detail_each_address       # Get all resources of addresses.
 1815&nbsp;    pend_func detail_each_name          # Get all resources of names.
 1816&nbsp;
 1817&nbsp;    #  The two expand_* are mutually recursive functions,
 1818&nbsp;    #+ which pend additional detail_* functions as required.
 1819&nbsp;    pend_func expand_input_address 1    # Expand input names by address.
 1820&nbsp;    pend_func expand_input_name 1       # #xpand input addresses by name.
 1821&nbsp;
 1822&nbsp;    # Start with a unique set of names and addresses.
 1823&nbsp;    pend_func unique_lines uc_address uc_address
 1824&nbsp;    pend_func unique_lines uc_name uc_name
 1825&nbsp;
 1826&nbsp;    # Separate mixed input of names and addresses.
 1827&nbsp;    pend_func split_input
 1828&nbsp;pend_release
 1829&nbsp;
 1830&nbsp;# # # Pairs reported -- Unique list of IP addresses found
 1831&nbsp;echo
 1832&nbsp;_ip_cnt=${#known_address[@]}
 1833&nbsp;if [ ${#list_server[@]} -eq 0 ]
 1834&nbsp;then
 1835&nbsp;    echo 'Blacklist server list empty, none checked.'
 1836&nbsp;else
 1837&nbsp;    if [ ${_ip_cnt} -eq 0 ]
 1838&nbsp;    then
 1839&nbsp;        echo 'Known address list empty, none checked.'
 1840&nbsp;    else
 1841&nbsp;        _ip_cnt=${_ip_cnt}-1   # Start at top.
 1842&nbsp;        echo 'Checking Blacklist servers.'
 1843&nbsp;        for (( _ip = _ip_cnt ; _ip &#62;= 0 ; _ip-- ))
 1844&nbsp;        do
 1845&nbsp;          pend_func check_lists $( printf '%q\n' ${known_address[$_ip]} )
 1846&nbsp;        done
 1847&nbsp;    fi
 1848&nbsp;fi
 1849&nbsp;pend_release
 1850&nbsp;$_dot_dump                   # Graphics file dump
 1851&nbsp;$_log_dump                   # Execution trace
 1852&nbsp;echo
 1853&nbsp;
 1854&nbsp;
 1855&nbsp;##############################
 1856&nbsp;# Example output from script #
 1857&nbsp;##############################
 1858&nbsp;:&#60;&#60;-'_is_spammer_outputs_'
 1859&nbsp;
 1860&nbsp;./is_spammer.bash 0 web4.alojamentos7.com
 1861&nbsp;
 1862&nbsp;Starting with domain name &#62;web4.alojamentos7.com&#60;
 1863&nbsp;Using default blacklist server list.
 1864&nbsp;Search depth limit: 0
 1865&nbsp;.:....::::...:::...:::.......::..::...:::.......::
 1866&nbsp;Known network pairs.
 1867&nbsp;    66.98.208.97             web4.alojamentos7.com.
 1868&nbsp;    66.98.208.97             ns1.alojamentos7.com.
 1869&nbsp;    69.56.202.147            ns2.alojamentos.ws.
 1870&nbsp;    66.98.208.97             alojamentos7.com.
 1871&nbsp;    66.98.208.97             web.alojamentos7.com.
 1872&nbsp;    69.56.202.146            ns1.alojamentos.ws.
 1873&nbsp;    69.56.202.146            alojamentos.ws.
 1874&nbsp;    66.235.180.113           ns1.alojamentos.org.
 1875&nbsp;    66.235.181.192           ns2.alojamentos.org.
 1876&nbsp;    66.235.180.113           alojamentos.org.
 1877&nbsp;    66.235.180.113           web6.alojamentos.org.
 1878&nbsp;    216.234.234.30           ns1.theplanet.com.
 1879&nbsp;    12.96.160.115            ns2.theplanet.com.
 1880&nbsp;    216.185.111.52           mail1.theplanet.com.
 1881&nbsp;    69.56.141.4              spooling.theplanet.com.
 1882&nbsp;    216.185.111.40           theplanet.com.
 1883&nbsp;    216.185.111.40           www.theplanet.com.
 1884&nbsp;    216.185.111.52           mail.theplanet.com.
 1885&nbsp;
 1886&nbsp;Checking Blacklist servers.
 1887&nbsp;  Checking address 66.98.208.97
 1888&nbsp;      Records from dnsbl.sorbs.net
 1889&nbsp;  "Spam Received See: http://www.dnsbl.sorbs.net/lookup.shtml?66.98.208.97"
 1890&nbsp;    Checking address 69.56.202.147
 1891&nbsp;    Checking address 69.56.202.146
 1892&nbsp;    Checking address 66.235.180.113
 1893&nbsp;    Checking address 66.235.181.192
 1894&nbsp;    Checking address 216.185.111.40
 1895&nbsp;    Checking address 216.234.234.30
 1896&nbsp;    Checking address 12.96.160.115
 1897&nbsp;    Checking address 216.185.111.52
 1898&nbsp;    Checking address 69.56.141.4
 1899&nbsp;
 1900&nbsp;Advanced Bash Scripting Guide: is_spammer.bash, v2, 2004-msz
 1901&nbsp;
 1902&nbsp;_is_spammer_outputs_
 1903&nbsp;
 1904&nbsp;exit ${_hs_RC}
 1905&nbsp;
 1906&nbsp;####################################################
 1907&nbsp;#  The script ignores everything from here on down #
 1908&nbsp;#+ because of the 'exit' command, just above.      #
 1909&nbsp;####################################################
 1910&nbsp;
 1911&nbsp;
 1912&nbsp;
 1913&nbsp;Quickstart
 1914&nbsp;==========
 1915&nbsp;
 1916&nbsp; Prerequisites
 1917&nbsp;
 1918&nbsp;  Bash version 2.05b or 3.00 (bash --version)
 1919&nbsp;  A version of Bash which supports arrays. Array 
 1920&nbsp;  support is included by default Bash configurations.
 1921&nbsp;
 1922&nbsp;  'dig,' version 9.x.x (dig $HOSTNAME, see first line of output)
 1923&nbsp;  A version of dig which supports the +short options. 
 1924&nbsp;  See: dig_wrappers.bash for details.
 1925&nbsp;
 1926&nbsp;
 1927&nbsp; Optional Prerequisites
 1928&nbsp;
 1929&nbsp;  'named,' a local DNS caching program. Any flavor will do.
 1930&nbsp;  Do twice: dig $HOSTNAME 
 1931&nbsp;  Check near bottom of output for: SERVER: 127.0.0.1#53
 1932&nbsp;  That means you have one running.
 1933&nbsp;
 1934&nbsp;
 1935&nbsp; Optional Graphics Support
 1936&nbsp;
 1937&nbsp;  'date,' a standard *nix thing. (date -R)
 1938&nbsp;
 1939&nbsp;  dot Program to convert graphic description file to a 
 1940&nbsp;  diagram. (dot -V)
 1941&nbsp;  A part of the Graph-Viz set of programs.
 1942&nbsp;  See: [http://www.research.att.com/sw/tools/graphviz||GraphViz]
 1943&nbsp;
 1944&nbsp;  'dotty,' a visual editor for graphic description files.
 1945&nbsp;  Also a part of the Graph-Viz set of programs.
 1946&nbsp;
 1947&nbsp;
 1948&nbsp;
 1949&nbsp;
 1950&nbsp; Quick Start
 1951&nbsp;
 1952&nbsp;In the same directory as the is_spammer.bash script; 
 1953&nbsp;Do: ./is_spammer.bash
 1954&nbsp;
 1955&nbsp; Usage Details
 1956&nbsp;
 1957&nbsp;1. Blacklist server choices.
 1958&nbsp;
 1959&nbsp;  (a) To use default, built-in list: Do nothing.
 1960&nbsp;
 1961&nbsp;  (b) To use your own list: 
 1962&nbsp;
 1963&nbsp;    i. Create a file with a single Blacklist server 
 1964&nbsp;       domain name per line.
 1965&nbsp;
 1966&nbsp;    ii. Provide that filename as the last argument to 
 1967&nbsp;        the script.
 1968&nbsp;
 1969&nbsp;  (c) To use a single Blacklist server: Last argument 
 1970&nbsp;      to the script.
 1971&nbsp;
 1972&nbsp;  (d) To disable Blacklist lookups:
 1973&nbsp;
 1974&nbsp;    i. Create an empty file (touch spammer.nul)
 1975&nbsp;       Your choice of filename.
 1976&nbsp;
 1977&nbsp;    ii. Provide the filename of that empty file as the 
 1978&nbsp;        last argument to the script.
 1979&nbsp;
 1980&nbsp;2. Search depth limit.
 1981&nbsp;
 1982&nbsp;  (a) To use the default value of 2: Do nothing.
 1983&nbsp;
 1984&nbsp;  (b) To set a different limit: 
 1985&nbsp;      A limit of 0 means: no limit.
 1986&nbsp;
 1987&nbsp;    i. export SPAMMER_LIMIT=1
 1988&nbsp;       or whatever limit you want.
 1989&nbsp;
 1990&nbsp;    ii. OR provide the desired limit as the first 
 1991&nbsp;       argument to the script.
 1992&nbsp;
 1993&nbsp;3. Optional execution trace log.
 1994&nbsp;
 1995&nbsp;  (a) To use the default setting of no log output: Do nothing.
 1996&nbsp;
 1997&nbsp;  (b) To write an execution trace log:
 1998&nbsp;      export SPAMMER_TRACE=spammer.log
 1999&nbsp;      or whatever filename you want.
 2000&nbsp;
 2001&nbsp;4. Optional graphic description file.
 2002&nbsp;
 2003&nbsp;  (a) To use the default setting of no graphic file: Do nothing.
 2004&nbsp;
 2005&nbsp;  (b) To write a Graph-Viz graphic description file:
 2006&nbsp;      export SPAMMER_DATA=spammer.dot
 2007&nbsp;      or whatever filename you want.
 2008&nbsp;
 2009&nbsp;5. Where to start the search.
 2010&nbsp;
 2011&nbsp;  (a) Starting with a single domain name:
 2012&nbsp;
 2013&nbsp;    i. Without a command-line search limit: First 
 2014&nbsp;       argument to script.
 2015&nbsp;
 2016&nbsp;    ii. With a command-line search limit: Second 
 2017&nbsp;        argument to script.
 2018&nbsp;
 2019&nbsp;  (b) Starting with a single IP address:
 2020&nbsp;
 2021&nbsp;    i. Without a command-line search limit: First 
 2022&nbsp;       argument to script.
 2023&nbsp;
 2024&nbsp;    ii. With a command-line search limit: Second 
 2025&nbsp;        argument to script.
 2026&nbsp;
 2027&nbsp;  (c) Starting with (mixed) multiple name(s) and/or address(es):
 2028&nbsp;      Create a file with one name or address per line.
 2029&nbsp;      Your choice of filename.
 2030&nbsp;
 2031&nbsp;    i. Without a command-line search limit: Filename as 
 2032&nbsp;       first argument to script.
 2033&nbsp;
 2034&nbsp;    ii. With a command-line search limit: Filename as 
 2035&nbsp;        second argument to script.
 2036&nbsp;
 2037&nbsp;6. What to do with the display output.
 2038&nbsp;
 2039&nbsp;  (a) To view display output on screen: Do nothing.
 2040&nbsp;
 2041&nbsp;  (b) To save display output to a file: Redirect stdout to a filename.
 2042&nbsp;
 2043&nbsp;  (c) To discard display output: Redirect stdout to /dev/null.
 2044&nbsp;
 2045&nbsp;7. Temporary end of decision making. 
 2046&nbsp;   press RETURN 
 2047&nbsp;   wait (optionally, watch the dots and colons).
 2048&nbsp;
 2049&nbsp;8. Optionally check the return code.
 2050&nbsp;
 2051&nbsp;  (a) Return code 0: All OK
 2052&nbsp;
 2053&nbsp;  (b) Return code 1: Script setup failure
 2054&nbsp;
 2055&nbsp;  (c) Return code 2: Something was blacklisted.
 2056&nbsp;
 2057&nbsp;9. Where is my graph (diagram)?
 2058&nbsp;
 2059&nbsp;The script does not directly produce a graph (diagram). 
 2060&nbsp;It only produces a graphic description file. You can 
 2061&nbsp;process the graphic descriptor file that was output 
 2062&nbsp;with the 'dot' program.
 2063&nbsp;
 2064&nbsp;Until you edit that descriptor file, to describe the 
 2065&nbsp;relationships you want shown, all that you will get is 
 2066&nbsp;a bunch of labeled name and address nodes.
 2067&nbsp;
 2068&nbsp;All of the script's discovered relationships are within 
 2069&nbsp;a comment block in the graphic descriptor file, each 
 2070&nbsp;with a descriptive heading.
 2071&nbsp;
 2072&nbsp;The editing required to draw a line between a pair of 
 2073&nbsp;nodes from the information in the descriptor file may 
 2074&nbsp;be done with a text editor. 
 2075&nbsp;
 2076&nbsp;Given these lines somewhere in the descriptor file:
 2077&nbsp;
 2078&nbsp;# Known domain name nodes
 2079&nbsp;
 2080&nbsp;N0000 [label="guardproof.info."] ;
 2081&nbsp;
 2082&nbsp;N0002 [label="third.guardproof.info."] ;
 2083&nbsp;
 2084&nbsp;
 2085&nbsp;
 2086&nbsp;# Known address nodes
 2087&nbsp;
 2088&nbsp;A0000 [label="61.141.32.197"] ;
 2089&nbsp;
 2090&nbsp;
 2091&nbsp;
 2092&nbsp;/*
 2093&nbsp;
 2094&nbsp;# Known name-&#62;address edges
 2095&nbsp;
 2096&nbsp;NA0000 third.guardproof.info. 61.141.32.197
 2097&nbsp;
 2098&nbsp;
 2099&nbsp;
 2100&nbsp;# Known parent-&#62;child edges
 2101&nbsp;
 2102&nbsp;PC0000 guardproof.info. third.guardproof.info.
 2103&nbsp;
 2104&nbsp; */
 2105&nbsp;
 2106&nbsp;Turn that into the following lines by substituting node 
 2107&nbsp;identifiers into the relationships:
 2108&nbsp;
 2109&nbsp;# Known domain name nodes
 2110&nbsp;
 2111&nbsp;N0000 [label="guardproof.info."] ;
 2112&nbsp;
 2113&nbsp;N0002 [label="third.guardproof.info."] ;
 2114&nbsp;
 2115&nbsp;
 2116&nbsp;
 2117&nbsp;# Known address nodes
 2118&nbsp;
 2119&nbsp;A0000 [label="61.141.32.197"] ;
 2120&nbsp;
 2121&nbsp;
 2122&nbsp;
 2123&nbsp;# PC0000 guardproof.info. third.guardproof.info.
 2124&nbsp;
 2125&nbsp;N0000-&#62;N0002 ;
 2126&nbsp;
 2127&nbsp;
 2128&nbsp;
 2129&nbsp;# NA0000 third.guardproof.info. 61.141.32.197
 2130&nbsp;
 2131&nbsp;N0002-&#62;A0000 ;
 2132&nbsp;
 2133&nbsp;
 2134&nbsp;
 2135&nbsp;/*
 2136&nbsp;
 2137&nbsp;# Known name-&#62;address edges
 2138&nbsp;
 2139&nbsp;NA0000 third.guardproof.info. 61.141.32.197
 2140&nbsp;
 2141&nbsp;
 2142&nbsp;
 2143&nbsp;# Known parent-&#62;child edges
 2144&nbsp;
 2145&nbsp;PC0000 guardproof.info. third.guardproof.info.
 2146&nbsp;
 2147&nbsp; */
 2148&nbsp;
 2149&nbsp;Process that with the 'dot' program, and you have your 
 2150&nbsp;first network diagram.
 2151&nbsp;
 2152&nbsp;In addition to the conventional graphic edges, the 
 2153&nbsp;descriptor file includes similar format pair-data that 
 2154&nbsp;describes services, zone records (sub-graphs?), 
 2155&nbsp;blacklisted addresses, and other things which might be 
 2156&nbsp;interesting to include in your graph. This additional 
 2157&nbsp;information could be displayed as different node 
 2158&nbsp;shapes, colors, line sizes, etc.
 2159&nbsp;
 2160&nbsp;The descriptor file can also be read and edited by a 
 2161&nbsp;Bash script (of course). You should be able to find 
 2162&nbsp;most of the functions required within the 
 2163&nbsp;"is_spammer.bash" script.
 2164&nbsp;
 2165&nbsp;# End Quickstart.
 2166&nbsp;
 2167&nbsp;
 2168&nbsp;
 2169&nbsp;Additional Note
 2170&nbsp;========== ====
 2171&nbsp;
 2172&nbsp;Michael Zick points out that there is a "makeviz.bash" interactive
 2173&nbsp;Web site at rediris.es. Can't give the full URL, since this is not
 2174&nbsp;a publically accessible site.</PRE
></TD
></TR
></TABLE
><HR></DIV
><P
>Another anti-spam script.</P
><P
><A
NAME="WHX0"
></A
></P
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="WHX"
></A
><P
><B
>Example A-29. Spammer Hunt</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#!/bin/bash
   2&nbsp;# whx.sh: "whois" spammer lookup
   3&nbsp;# Author: Walter Dnes
   4&nbsp;# Slight revisions (first section) by ABS Guide author.
   5&nbsp;# Used in ABS Guide with permission.
   6&nbsp;
   7&nbsp;# Needs version 3.x or greater of Bash to run (because of =~ operator).
   8&nbsp;# Commented by script author and ABS Guide author.
   9&nbsp;
  10&nbsp;
  11&nbsp;
  12&nbsp;E_BADARGS=85        # Missing command-line arg.
  13&nbsp;E_NOHOST=86         # Host not found.
  14&nbsp;E_TIMEOUT=87        # Host lookup timed out.
  15&nbsp;E_UNDEF=88          # Some other (undefined) error.
  16&nbsp;
  17&nbsp;HOSTWAIT=10         # Specify up to 10 seconds for host query reply.
  18&nbsp;                    # The actual wait may be a bit longer.
  19&nbsp;OUTFILE=whois.txt   # Output file.
  20&nbsp;PORT=4321
  21&nbsp;
  22&nbsp;
  23&nbsp;if [ -z "$1" ]      # Check for (required) command-line arg.
  24&nbsp;then
  25&nbsp;  echo "Usage: $0 domain name or IP address"
  26&nbsp;  exit $E_BADARGS
  27&nbsp;fi
  28&nbsp;
  29&nbsp;
  30&nbsp;if [[ "$1" =~ [a-zA-Z][a-zA-Z]$ ]]  #  Ends in two alpha chars?
  31&nbsp;then                                  #  It's a domain name &#38;&#38;
  32&nbsp;                                      #+ must do host lookup.
  33&nbsp;  IPADDR=$(host -W $HOSTWAIT $1 | awk '{print $4}')
  34&nbsp;                                      #  Doing host lookup
  35&nbsp;                                      #+ to get IP address.
  36&nbsp;				      #  Extract final field.
  37&nbsp;else
  38&nbsp;  IPADDR="$1"                         #  Command-line arg was IP address.
  39&nbsp;fi
  40&nbsp;
  41&nbsp;echo; echo "IP Address is: "$IPADDR""; echo
  42&nbsp;
  43&nbsp;if [ -e "$OUTFILE" ]
  44&nbsp;then
  45&nbsp;  rm -f "$OUTFILE"
  46&nbsp;  echo "Stale output file \"$OUTFILE\" removed."; echo
  47&nbsp;fi
  48&nbsp;
  49&nbsp;
  50&nbsp;#  Sanity checks.
  51&nbsp;#  (This section needs more work.)
  52&nbsp;#  ===============================
  53&nbsp;if [ -z "$IPADDR" ]
  54&nbsp;# No response.
  55&nbsp;then
  56&nbsp;  echo "Host not found!"
  57&nbsp;  exit $E_NOHOST    # Bail out.
  58&nbsp;fi
  59&nbsp;
  60&nbsp;if [[ "$IPADDR" =~ ^[;;] ]]
  61&nbsp;#  ;; Connection timed out; no servers could be reached.
  62&nbsp;then
  63&nbsp;  echo "Host lookup timed out!"
  64&nbsp;  exit $E_TIMEOUT   # Bail out.
  65&nbsp;fi
  66&nbsp;
  67&nbsp;if [[ "$IPADDR" =~ [(NXDOMAIN)]$ ]]
  68&nbsp;#  Host xxxxxxxxx.xxx not found: 3(NXDOMAIN)
  69&nbsp;then
  70&nbsp;  echo "Host not found!"
  71&nbsp;  exit $E_NOHOST    # Bail out.
  72&nbsp;fi
  73&nbsp;
  74&nbsp;if [[ "$IPADDR" =~ [(SERVFAIL)]$ ]]
  75&nbsp;#  Host xxxxxxxxx.xxx not found: 2(SERVFAIL)
  76&nbsp;then
  77&nbsp;  echo "Host not found!"
  78&nbsp;  exit $E_NOHOST    # Bail out.
  79&nbsp;fi
  80&nbsp;
  81&nbsp;
  82&nbsp;
  83&nbsp;
  84&nbsp;# ======================== Main body of script ========================
  85&nbsp;
  86&nbsp;AFRINICquery() {
  87&nbsp;#  Define the function that queries AFRINIC. Echo a notification to the
  88&nbsp;#+ screen, and then run the actual query, redirecting output to $OUTFILE.
  89&nbsp;
  90&nbsp;  echo "Searching for $IPADDR in whois.afrinic.net"
  91&nbsp;  whois -h whois.afrinic.net "$IPADDR" &#62; $OUTFILE
  92&nbsp;
  93&nbsp;#  Check for presence of reference to an rwhois.
  94&nbsp;#  Warn about non-functional rwhois.infosat.net server
  95&nbsp;#+ and attempt rwhois query.
  96&nbsp;  if grep -e "^remarks: .*rwhois\.[^ ]\+" "$OUTFILE"
  97&nbsp;  then
  98&nbsp;    echo " " &#62;&#62; $OUTFILE
  99&nbsp;    echo "***" &#62;&#62; $OUTFILE
 100&nbsp;    echo "***" &#62;&#62; $OUTFILE
 101&nbsp;    echo "Warning: rwhois.infosat.net was not working \
 102&nbsp;      as of 2005/02/02" &#62;&#62; $OUTFILE
 103&nbsp;    echo "         when this script was written." &#62;&#62; $OUTFILE
 104&nbsp;    echo "***" &#62;&#62; $OUTFILE
 105&nbsp;    echo "***" &#62;&#62; $OUTFILE
 106&nbsp;    echo " " &#62;&#62; $OUTFILE
 107&nbsp;    RWHOIS=`grep "^remarks: .*rwhois\.[^ ]\+" "$OUTFILE" | tail -n 1 |\
 108&nbsp;    sed "s/\(^.*\)\(rwhois\..*\)\(:4.*\)/\2/"`
 109&nbsp;    whois -h ${RWHOIS}:${PORT} "$IPADDR" &#62;&#62; $OUTFILE
 110&nbsp;  fi
 111&nbsp;}
 112&nbsp;
 113&nbsp;APNICquery() {
 114&nbsp;  echo "Searching for $IPADDR in whois.apnic.net"
 115&nbsp;  whois -h whois.apnic.net "$IPADDR" &#62; $OUTFILE
 116&nbsp;
 117&nbsp;#  Just  about  every  country has its own internet registrar.
 118&nbsp;#  I don't normally bother consulting them, because the regional registry
 119&nbsp;#+ usually supplies sufficient information.
 120&nbsp;#  There are a few exceptions, where the regional registry simply
 121&nbsp;#+ refers to the national registry for direct data.
 122&nbsp;#  These are Japan and South Korea in APNIC, and Brasil in LACNIC.
 123&nbsp;#  The following if statement checks $OUTFILE (whois.txt) for the presence
 124&nbsp;#+ of "KR" (South Korea) or "JP" (Japan) in the country field.
 125&nbsp;#  If either is found, the query is re-run against the appropriate
 126&nbsp;#+ national registry.
 127&nbsp;
 128&nbsp;  if grep -E "^country:[ ]+KR$" "$OUTFILE"
 129&nbsp;  then
 130&nbsp;    echo "Searching for $IPADDR in whois.krnic.net"
 131&nbsp;    whois -h whois.krnic.net "$IPADDR" &#62;&#62; $OUTFILE
 132&nbsp;  elif grep -E "^country:[ ]+JP$" "$OUTFILE"
 133&nbsp;  then
 134&nbsp;    echo "Searching for $IPADDR in whois.nic.ad.jp"
 135&nbsp;    whois -h whois.nic.ad.jp "$IPADDR"/e &#62;&#62; $OUTFILE
 136&nbsp;  fi
 137&nbsp;}
 138&nbsp;
 139&nbsp;ARINquery() {
 140&nbsp;  echo "Searching for $IPADDR in whois.arin.net"
 141&nbsp;  whois -h whois.arin.net "$IPADDR" &#62; $OUTFILE
 142&nbsp;
 143&nbsp;#  Several large internet providers listed by ARIN have their own
 144&nbsp;#+ internal whois service, referred to as "rwhois".
 145&nbsp;#  A large block of IP addresses is listed with the provider
 146&nbsp;#+ under the ARIN registry.
 147&nbsp;#  To get the IP addresses of 2nd-level ISPs or other large customers,
 148&nbsp;#+ one has to refer to the rwhois server on port 4321.
 149&nbsp;#  I originally started with a bunch of "if" statements checking for
 150&nbsp;#+ the larger providers.
 151&nbsp;#  This approach is unwieldy, and there's always another rwhois server
 152&nbsp;#+ that I didn't know about.
 153&nbsp;#  A more elegant approach is to check $OUTFILE for a reference
 154&nbsp;#+ to a whois server, parse that server name out of the comment section,
 155&nbsp;#+ and re-run the query against the appropriate rwhois server.
 156&nbsp;#  The parsing looks a bit ugly, with a long continued line inside
 157&nbsp;#+ backticks.
 158&nbsp;#  But it only has to be done once, and will work as new servers are added.
 159&nbsp;#@   ABS Guide author comment: it isn't all that ugly, and is, in fact,
 160&nbsp;#@+  an instructive use of Regular Expressions.
 161&nbsp;
 162&nbsp;  if grep -E "^Comment: .*rwhois.[^ ]+" "$OUTFILE"
 163&nbsp;  then
 164&nbsp;    RWHOIS=`grep -e "^Comment:.*rwhois\.[^ ]\+" "$OUTFILE" | tail -n 1 |\
 165&nbsp;    sed "s/^\(.*\)\(rwhois\.[^ ]\+\)\(.*$\)/\2/"`
 166&nbsp;    echo "Searching for $IPADDR in ${RWHOIS}"
 167&nbsp;    whois -h ${RWHOIS}:${PORT} "$IPADDR" &#62;&#62; $OUTFILE
 168&nbsp;  fi
 169&nbsp;}
 170&nbsp;
 171&nbsp;LACNICquery() {
 172&nbsp;  echo "Searching for $IPADDR in whois.lacnic.net"
 173&nbsp;  whois -h whois.lacnic.net "$IPADDR" &#62; $OUTFILE
 174&nbsp;
 175&nbsp;#  The  following if statement checks $OUTFILE (whois.txt) for
 176&nbsp;#+ the presence of "BR" (Brasil) in the country field.
 177&nbsp;#  If it is found, the query is re-run against whois.registro.br.
 178&nbsp;
 179&nbsp;  if grep -E "^country:[ ]+BR$" "$OUTFILE"
 180&nbsp;  then
 181&nbsp;    echo "Searching for $IPADDR in whois.registro.br"
 182&nbsp;    whois -h whois.registro.br "$IPADDR" &#62;&#62; $OUTFILE
 183&nbsp;  fi
 184&nbsp;}
 185&nbsp;
 186&nbsp;RIPEquery() {
 187&nbsp;  echo "Searching for $IPADDR in whois.ripe.net"
 188&nbsp;  whois -h whois.ripe.net "$IPADDR" &#62; $OUTFILE
 189&nbsp;}
 190&nbsp;
 191&nbsp;#  Initialize a few variables.
 192&nbsp;#  * slash8 is the most significant octet
 193&nbsp;#  * slash16 consists of the two most significant octets
 194&nbsp;#  * octet2 is the second most significant octet
 195&nbsp;
 196&nbsp;
 197&nbsp;
 198&nbsp;
 199&nbsp;slash8=`echo $IPADDR | cut -d. -f 1`
 200&nbsp;  if [ -z "$slash8" ]  # Yet another sanity check.
 201&nbsp;  then
 202&nbsp;    echo "Undefined error!"
 203&nbsp;    exit $E_UNDEF
 204&nbsp;  fi
 205&nbsp;slash16=`echo $IPADDR | cut -d. -f 1-2`
 206&nbsp;#                             ^ Period specified as 'cut" delimiter.
 207&nbsp;  if [ -z "$slash16" ]
 208&nbsp;  then
 209&nbsp;    echo "Undefined error!"
 210&nbsp;    exit $E_UNDEF
 211&nbsp;  fi
 212&nbsp;octet2=`echo $slash16 | cut -d. -f 2`
 213&nbsp;  if [ -z "$octet2" ]
 214&nbsp;  then
 215&nbsp;    echo "Undefined error!"
 216&nbsp;    exit $E_UNDEF
 217&nbsp;  fi
 218&nbsp;
 219&nbsp;
 220&nbsp;#  Check for various odds and ends of reserved space.
 221&nbsp;#  There is no point in querying for those addresses.
 222&nbsp;
 223&nbsp;if [ $slash8 == 0 ]; then
 224&nbsp;  echo $IPADDR is '"This Network"' space\; Not querying
 225&nbsp;elif [ $slash8 == 10 ]; then
 226&nbsp;  echo $IPADDR is RFC1918 space\; Not querying
 227&nbsp;elif [ $slash8 == 14 ]; then
 228&nbsp;  echo $IPADDR is '"Public Data Network"' space\; Not querying
 229&nbsp;elif [ $slash8 == 127 ]; then
 230&nbsp;  echo $IPADDR is loopback space\; Not querying
 231&nbsp;elif [ $slash16 == 169.254 ]; then
 232&nbsp;  echo $IPADDR is link-local space\; Not querying
 233&nbsp;elif [ $slash8 == 172 ] &#38;&#38; [ $octet2 -ge 16 ] &#38;&#38; [ $octet2 -le 31 ];then
 234&nbsp;  echo $IPADDR is RFC1918 space\; Not querying
 235&nbsp;elif [ $slash16 == 192.168 ]; then
 236&nbsp;  echo $IPADDR is RFC1918 space\; Not querying
 237&nbsp;elif [ $slash8 -ge 224 ]; then
 238&nbsp;  echo $IPADDR is either Multicast or reserved space\; Not querying
 239&nbsp;elif [ $slash8 -ge 200 ] &#38;&#38; [ $slash8 -le 201 ]; then LACNICquery "$IPADDR"
 240&nbsp;elif [ $slash8 -ge 202 ] &#38;&#38; [ $slash8 -le 203 ]; then APNICquery "$IPADDR"
 241&nbsp;elif [ $slash8 -ge 210 ] &#38;&#38; [ $slash8 -le 211 ]; then APNICquery "$IPADDR"
 242&nbsp;elif [ $slash8 -ge 218 ] &#38;&#38; [ $slash8 -le 223 ]; then APNICquery "$IPADDR"
 243&nbsp;
 244&nbsp;#  If we got this far without making a decision, query ARIN.
 245&nbsp;#  If a reference is found in $OUTFILE to APNIC, AFRINIC, LACNIC, or RIPE,
 246&nbsp;#+ query the appropriate whois server.
 247&nbsp;
 248&nbsp;else
 249&nbsp;  ARINquery "$IPADDR"
 250&nbsp;  if grep "whois.afrinic.net" "$OUTFILE"; then
 251&nbsp;    AFRINICquery "$IPADDR"
 252&nbsp;  elif grep -E "^OrgID:[ ]+RIPE$" "$OUTFILE"; then
 253&nbsp;    RIPEquery "$IPADDR"
 254&nbsp;  elif grep -E "^OrgID:[ ]+APNIC$" "$OUTFILE"; then
 255&nbsp;    APNICquery "$IPADDR"
 256&nbsp;  elif grep -E "^OrgID:[ ]+LACNIC$" "$OUTFILE"; then
 257&nbsp;    LACNICquery "$IPADDR"
 258&nbsp;  fi
 259&nbsp;fi
 260&nbsp;
 261&nbsp;#@  ---------------------------------------------------------------
 262&nbsp;#   Try also:
 263&nbsp;#   wget http://logi.cc/nw/whois.php3?ACTION=doQuery&#38;DOMAIN=$IPADDR
 264&nbsp;#@  ---------------------------------------------------------------
 265&nbsp;
 266&nbsp;#  We've  now  finished  the querying.
 267&nbsp;#  Echo a copy of the final result to the screen.
 268&nbsp;
 269&nbsp;cat $OUTFILE
 270&nbsp;# Or "less $OUTFILE" . . .
 271&nbsp;
 272&nbsp;
 273&nbsp;exit 0
 274&nbsp;
 275&nbsp;#@  ABS Guide author comments:
 276&nbsp;#@  Nothing fancy here, but still a very useful tool for hunting spammers.
 277&nbsp;#@  Sure, the script can be cleaned up some, and it's still a bit buggy,
 278&nbsp;#@+ (exercise for reader), but all the same, it's a nice piece of coding
 279&nbsp;#@+ by Walter Dnes.
 280&nbsp;#@  Thank you!</PRE
></TD
></TR
></TABLE
><HR></DIV
><P
><SPAN
CLASS="QUOTE"
>"Little Monster's"</SPAN
> front end to <A
HREF="communications.html#WGETREF"
>wget</A
>.</P
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="WGETTER2"
></A
><P
><B
>Example A-30. Making <I
CLASS="FIRSTTERM"
>wget</I
> easier to use</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#!/bin/bash
   2&nbsp;# wgetter2.bash
   3&nbsp;
   4&nbsp;# Author: Little Monster [monster@monstruum.co.uk]
   5&nbsp;# ==&#62; Used in ABS Guide with permission of script author.
   6&nbsp;# ==&#62; This script still needs debugging and fixups (exercise for reader).
   7&nbsp;# ==&#62; It could also use some additional editing in the comments.
   8&nbsp;
   9&nbsp;
  10&nbsp;#  This is wgetter2 --
  11&nbsp;#+ a Bash script to make wget a bit more friendly, and save typing.
  12&nbsp;
  13&nbsp;#  Carefully crafted by Little Monster.
  14&nbsp;#  More or less complete on 02/02/2005.
  15&nbsp;#  If you think this script can be improved,
  16&nbsp;#+ email me at: monster@monstruum.co.uk
  17&nbsp;# ==&#62; and cc: to the author of the ABS Guide, please.
  18&nbsp;#  This script is licenced under the GPL.
  19&nbsp;#  You are free to copy, alter and re-use it,
  20&nbsp;#+ but please don't try to claim you wrote it.
  21&nbsp;#  Log your changes here instead.
  22&nbsp;
  23&nbsp;# =======================================================================
  24&nbsp;# changelog:
  25&nbsp;
  26&nbsp;# 07/02/2005.  Fixups by Little Monster.
  27&nbsp;# 02/02/2005.  Minor additions by Little Monster.
  28&nbsp;#              (See after # +++++++++++ )
  29&nbsp;# 29/01/2005.  Minor stylistic edits and cleanups by author of ABS Guide.
  30&nbsp;#              Added exit error codes.
  31&nbsp;# 22/11/2004.  Finished initial version of second version of wgetter:
  32&nbsp;#              wgetter2 is born.
  33&nbsp;# 01/12/2004.  Changed 'runn' function so it can be run 2 ways --
  34&nbsp;#              either ask for a file name or have one input on the CL.
  35&nbsp;# 01/12/2004.  Made sensible handling of no URL's given.
  36&nbsp;# 01/12/2004.  Made loop of main options, so you don't
  37&nbsp;#              have to keep calling wgetter 2 all the time.
  38&nbsp;#              Runs as a session instead.
  39&nbsp;# 01/12/2004.  Added looping to 'runn' function.
  40&nbsp;#              Simplified and improved.
  41&nbsp;# 01/12/2004.  Added state to recursion setting.
  42&nbsp;#              Enables re-use of previous value.
  43&nbsp;# 05/12/2004.  Modified the file detection routine in the 'runn' function
  44&nbsp;#              so it's not fooled by empty values, and is cleaner.
  45&nbsp;# 01/02/2004.  Added cookie finding routine from later version (which 
  46&nbsp;#              isn't ready yet), so as not to have hard-coded paths.
  47&nbsp;# =======================================================================
  48&nbsp;
  49&nbsp;# Error codes for abnormal exit.
  50&nbsp;E_USAGE=67        # Usage message, then quit.
  51&nbsp;E_NO_OPTS=68      # No command-line args entered.
  52&nbsp;E_NO_URLS=69      # No URLs passed to script.
  53&nbsp;E_NO_SAVEFILE=70  # No save filename passed to script.
  54&nbsp;E_USER_EXIT=71    # User decides to quit.
  55&nbsp;
  56&nbsp;
  57&nbsp;#  Basic default wget command we want to use.
  58&nbsp;#  This is the place to change it, if required.
  59&nbsp;#  NB: if using a proxy, set http_proxy = yourproxy in .wgetrc.
  60&nbsp;#  Otherwise delete --proxy=on, below.
  61&nbsp;# ====================================================================
  62&nbsp;CommandA="wget -nc -c -t 5 --progress=bar --random-wait --proxy=on -r"
  63&nbsp;# ====================================================================
  64&nbsp;
  65&nbsp;
  66&nbsp;
  67&nbsp;# --------------------------------------------------------------------
  68&nbsp;# Set some other variables and explain them.
  69&nbsp;
  70&nbsp;pattern=" -A .jpg,.JPG,.jpeg,.JPEG,.gif,.GIF,.htm,.html,.shtml,.php"
  71&nbsp;                    # wget's option to only get certain types of file.
  72&nbsp;                    # comment out if not using
  73&nbsp;today=`date +%F`    # Used for a filename.
  74&nbsp;home=$HOME          # Set HOME to an internal variable.
  75&nbsp;                    # In case some other path is used, change it here.
  76&nbsp;depthDefault=3      # Set a sensible default recursion.
  77&nbsp;Depth=$depthDefault # Otherwise user feedback doesn't tie in properly.
  78&nbsp;RefA=""             # Set blank referring page.
  79&nbsp;Flag=""             #  Default to not saving anything,
  80&nbsp;                    #+ or whatever else might be wanted in future.
  81&nbsp;lister=""           # Used for passing a list of urls directly to wget.
  82&nbsp;Woptions=""         # Used for passing wget some options for itself.
  83&nbsp;inFile=""           # Used for the run function.
  84&nbsp;newFile=""          # Used for the run function.
  85&nbsp;savePath="$home/w-save"
  86&nbsp;Config="$home/.wgetter2rc"
  87&nbsp;                    #  This is where some variables can be stored, 
  88&nbsp;                    #+ if permanently changed from within the script.
  89&nbsp;Cookie_List="$home/.cookielist"
  90&nbsp;                    # So we know where the cookies are kept . . .
  91&nbsp;cFlag=""            # Part of the cookie file selection routine.
  92&nbsp;
  93&nbsp;# Define the options available. Easy to change letters here if needed.
  94&nbsp;# These are the optional options; you don't just wait to be asked.
  95&nbsp;
  96&nbsp;save=s   # Save command instead of executing it.
  97&nbsp;cook=c   # Change cookie file for this session.
  98&nbsp;help=h   # Usage guide.
  99&nbsp;list=l   # Pass wget the -i option and URL list.
 100&nbsp;runn=r   # Run saved commands as an argument to the option.
 101&nbsp;inpu=i   # Run saved commands interactively.
 102&nbsp;wopt=w   # Allow to enter options to pass directly to wget.
 103&nbsp;# --------------------------------------------------------------------
 104&nbsp;
 105&nbsp;
 106&nbsp;if [ -z "$1" ]; then   # Make sure we get something for wget to eat.
 107&nbsp;   echo "You must at least enter a URL or option!"
 108&nbsp;   echo "-$help for usage."
 109&nbsp;   exit $E_NO_OPTS
 110&nbsp;fi
 111&nbsp;
 112&nbsp;
 113&nbsp;
 114&nbsp;# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 115&nbsp;# added added added added added added added added added added added added
 116&nbsp;
 117&nbsp;if [ ! -e "$Config" ]; then   # See if configuration file exists.
 118&nbsp;   echo "Creating configuration file, $Config"
 119&nbsp;   echo "# This is the configuration file for wgetter2" &#62; "$Config"
 120&nbsp;   echo "# Your customised settings will be saved in this file" &#62;&#62; "$Config"
 121&nbsp;else
 122&nbsp;   source $Config             # Import variables we set outside the script.
 123&nbsp;fi
 124&nbsp;
 125&nbsp;if [ ! -e "$Cookie_List" ]; then
 126&nbsp;   # Set up a list of cookie files, if there isn't one.
 127&nbsp;   echo "Hunting for cookies . . ."
 128&nbsp;   find -name cookies.txt &#62;&#62; $Cookie_List # Create the list of cookie files.
 129&nbsp;fi #  Isolate this in its own 'if' statement,
 130&nbsp;   #+ in case we got interrupted while searching.
 131&nbsp;
 132&nbsp;if [ -z "$cFlag" ]; then # If we haven't already done this . . .
 133&nbsp;   echo                  # Make a nice space after the command prompt.
 134&nbsp;   echo "Looks like you haven't set up your source of cookies yet."
 135&nbsp;   n=0                   #  Make sure the counter
 136&nbsp;                         #+ doesn't contain random values.
 137&nbsp;   while read; do
 138&nbsp;      Cookies[$n]=$REPLY # Put the cookie files we found into an array.
 139&nbsp;      echo "$n) ${Cookies[$n]}"  # Create a menu.
 140&nbsp;      n=$(( n + 1 ))     # Increment the counter.
 141&nbsp;   done &#60; $Cookie_List   # Feed the read statement.
 142&nbsp;   echo "Enter the number of the cookie file you want to use."
 143&nbsp;   echo "If you won't be using cookies, just press RETURN."
 144&nbsp;   echo
 145&nbsp;   echo "I won't be asking this again. Edit $Config"
 146&nbsp;   echo "If you decide to change at a later date"
 147&nbsp;   echo "or use the -${cook} option for per session changes."
 148&nbsp;   read
 149&nbsp;   if [ ! -z $REPLY ]; then   # User didn't just press return.
 150&nbsp;      Cookie=" --load-cookies ${Cookies[$REPLY]}"
 151&nbsp;      # Set the variable here as well as in the config file.
 152&nbsp;
 153&nbsp;      echo "Cookie=\" --load-cookies ${Cookies[$REPLY]}\"" &#62;&#62; $Config
 154&nbsp;   fi
 155&nbsp;   echo "cFlag=1" &#62;&#62; $Config  # So we know not to ask again.
 156&nbsp;fi
 157&nbsp;
 158&nbsp;# end added section end added section end added section end added section
 159&nbsp;# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 160&nbsp;
 161&nbsp;
 162&nbsp;
 163&nbsp;# Another variable.
 164&nbsp;# This one may or may not be subject to variation.
 165&nbsp;# A bit like the small print.
 166&nbsp;CookiesON=$Cookie
 167&nbsp;# echo "cookie file is $CookiesON" # For debugging.
 168&nbsp;# echo "home is ${home}"           # For debugging.
 169&nbsp;                                   # Got caught with this one!
 170&nbsp;
 171&nbsp;
 172&nbsp;wopts()
 173&nbsp;{
 174&nbsp;echo "Enter options to pass to wget."
 175&nbsp;echo "It is assumed you know what you're doing."
 176&nbsp;echo
 177&nbsp;echo "You can pass their arguments here too."
 178&nbsp;# That is to say, everything passed here is passed to wget.
 179&nbsp;
 180&nbsp;read Wopts
 181&nbsp;# Read in the options to be passed to wget.
 182&nbsp;
 183&nbsp;Woptions=" $Wopts"
 184&nbsp;#         ^  Why the leading space?
 185&nbsp;# Assign to another variable.
 186&nbsp;# Just for fun, or something . . .
 187&nbsp;
 188&nbsp;echo "passing options ${Wopts} to wget"
 189&nbsp;# Mainly for debugging.
 190&nbsp;# Is cute.
 191&nbsp;
 192&nbsp;return
 193&nbsp;}
 194&nbsp;
 195&nbsp;
 196&nbsp;save_func()
 197&nbsp;{
 198&nbsp;echo "Settings will be saved."
 199&nbsp;if [ ! -d $savePath ]; then  #  See if directory exists.
 200&nbsp;   mkdir $savePath           #  Create the directory to save things in
 201&nbsp;                             #+ if it isn't already there.
 202&nbsp;fi
 203&nbsp;
 204&nbsp;Flag=S
 205&nbsp;# Tell the final bit of code what to do.
 206&nbsp;# Set a flag since stuff is done in main.
 207&nbsp;
 208&nbsp;return
 209&nbsp;}
 210&nbsp;
 211&nbsp;
 212&nbsp;usage() # Tell them how it works.
 213&nbsp;{
 214&nbsp;    echo "Welcome to wgetter.  This is a front end to wget."
 215&nbsp;    echo "It will always run wget with these options:"
 216&nbsp;    echo "$CommandA"
 217&nbsp;    echo "and the pattern to match: $pattern \
 218&nbsp;(which you can change at the top of this script)."
 219&nbsp;    echo "It will also ask you for recursion depth, \
 220&nbsp;and if you want to use a referring page."
 221&nbsp;    echo "Wgetter accepts the following options:"
 222&nbsp;    echo ""
 223&nbsp;    echo "-$help : Display this help."
 224&nbsp;    echo "-$save : Save the command to a file $savePath/wget-($today) \
 225&nbsp;instead of running it."
 226&nbsp;    echo "-$runn : Run saved wget commands instead of starting a new one -"
 227&nbsp;    echo "Enter filename as argument to this option."
 228&nbsp;    echo "-$inpu : Run saved wget commands interactively --"
 229&nbsp;    echo "The script will ask you for the filename."
 230&nbsp;    echo "-$cook : Change the cookies file for this session."
 231&nbsp;    echo "-$list : Tell wget to use URL's from a list instead of \
 232&nbsp;from the command-line."
 233&nbsp;    echo "-$wopt : Pass any other options direct to wget."
 234&nbsp;    echo ""
 235&nbsp;    echo "See the wget man page for additional options \
 236&nbsp;you can pass to wget."
 237&nbsp;    echo ""
 238&nbsp;
 239&nbsp;    exit $E_USAGE  # End here. Don't process anything else.
 240&nbsp;}
 241&nbsp;
 242&nbsp;
 243&nbsp;
 244&nbsp;list_func() #  Gives the user the option to use the -i option to wget,
 245&nbsp;            #+ and a list of URLs.
 246&nbsp;{
 247&nbsp;while [ 1 ]; do
 248&nbsp;   echo "Enter the name of the file containing URL's (press q to change
 249&nbsp;your mind)."
 250&nbsp;   read urlfile
 251&nbsp;   if [ ! -e "$urlfile" ] &#38;&#38; [ "$urlfile" != q ]; then
 252&nbsp;       # Look for a file, or the quit option.
 253&nbsp;       echo "That file does not exist!"
 254&nbsp;   elif [ "$urlfile" = q ]; then # Check quit option.
 255&nbsp;       echo "Not using a url list."
 256&nbsp;       return
 257&nbsp;   else
 258&nbsp;      echo "using $urlfile."
 259&nbsp;      echo "If you gave url's on the command-line, I'll use those first."
 260&nbsp;                            # Report wget standard behaviour to the user.
 261&nbsp;      lister=" -i $urlfile" # This is what we want to pass to wget.
 262&nbsp;      return
 263&nbsp;   fi
 264&nbsp;done
 265&nbsp;}
 266&nbsp;
 267&nbsp;
 268&nbsp;cookie_func() # Give the user the option to use a different cookie file.
 269&nbsp;{
 270&nbsp;while [ 1 ]; do
 271&nbsp;   echo "Change the cookies file. Press return if you don't want to change 
 272&nbsp;it."
 273&nbsp;   read Cookies
 274&nbsp;   # NB: this is not the same as Cookie, earlier.
 275&nbsp;   # There is an 's' on the end.
 276&nbsp;   # Bit like chocolate chips.
 277&nbsp;   if [ -z "$Cookies" ]; then                 # Escape clause for wusses.
 278&nbsp;      return
 279&nbsp;   elif [ ! -e "$Cookies" ]; then
 280&nbsp;      echo "File does not exist.  Try again." # Keep em going . . .
 281&nbsp;   else
 282&nbsp;       CookiesON=" --load-cookies $Cookies"   # File is good -- use it!
 283&nbsp;       return
 284&nbsp;   fi
 285&nbsp;done
 286&nbsp;}
 287&nbsp;
 288&nbsp;
 289&nbsp;
 290&nbsp;run_func()
 291&nbsp;{
 292&nbsp;if [ -z "$OPTARG" ]; then
 293&nbsp;# Test to see if we used the in-line option or the query one.
 294&nbsp;   if [ ! -d "$savePath" ]; then      # If directory doesn't exist . . .
 295&nbsp;      echo "$savePath does not appear to exist."
 296&nbsp;      echo "Please supply path and filename of saved wget commands:"
 297&nbsp;      read newFile
 298&nbsp;         until [ -f "$newFile" ]; do  # Keep going till we get something.
 299&nbsp;            echo "Sorry, that file does not exist.  Please try again."
 300&nbsp;            # Try really hard to get something.
 301&nbsp;            read newFile
 302&nbsp;         done
 303&nbsp;
 304&nbsp;
 305&nbsp;# -----------------------------------------------------------------------
 306&nbsp;#       if [ -z ( grep wget ${newfile} ) ]; then
 307&nbsp;        # Assume they haven't got the right file and bail out.
 308&nbsp;#       echo "Sorry, that file does not contain wget commands.  Aborting."
 309&nbsp;#       exit
 310&nbsp;#       fi
 311&nbsp;#
 312&nbsp;# This is bogus code.
 313&nbsp;# It doesn't actually work.
 314&nbsp;# If anyone wants to fix it, feel free!
 315&nbsp;# -----------------------------------------------------------------------
 316&nbsp;
 317&nbsp;
 318&nbsp;      filePath="${newFile}"
 319&nbsp;   else
 320&nbsp;   echo "Save path is $savePath"
 321&nbsp;     echo "Please enter name of the file which you want to use."
 322&nbsp;     echo "You have a choice of:"
 323&nbsp;     ls $savePath                                    # Give them a choice.
 324&nbsp;     read inFile
 325&nbsp;       until [ -f "$savePath/$inFile" ]; do         #  Keep going till
 326&nbsp;                                                    #+ we get something.
 327&nbsp;          if [ ! -f "${savePath}/${inFile}" ]; then # If file doesn't exist.
 328&nbsp;             echo "Sorry, that file does not exist.  Please choose from:"
 329&nbsp;             ls $savePath                           # If a mistake is made.
 330&nbsp;             read inFile
 331&nbsp;          fi
 332&nbsp;         done
 333&nbsp;      filePath="${savePath}/${inFile}"  # Make one variable . . .
 334&nbsp;   fi
 335&nbsp;else filePath="${savePath}/${OPTARG}"   # Which can be many things . . .
 336&nbsp;fi
 337&nbsp;
 338&nbsp;if [ ! -f "$filePath" ]; then           # If a bogus file got through.
 339&nbsp;   echo "You did not specify a suitable file."
 340&nbsp;   echo "Run this script with the -${save} option first."
 341&nbsp;   echo "Aborting."
 342&nbsp;   exit $E_NO_SAVEFILE
 343&nbsp;fi
 344&nbsp;echo "Using: $filePath"
 345&nbsp;while read; do
 346&nbsp;    eval $REPLY
 347&nbsp;    echo "Completed: $REPLY"
 348&nbsp;done &#60; $filePath  # Feed the actual file we are using into a 'while' loop.
 349&nbsp;
 350&nbsp;exit
 351&nbsp;}
 352&nbsp;
 353&nbsp;
 354&nbsp;
 355&nbsp;# Fish out any options we are using for the script.
 356&nbsp;# This is based on the demo in "Learning The Bash Shell" (O'Reilly).
 357&nbsp;while getopts ":$save$cook$help$list$runn:$inpu$wopt" opt
 358&nbsp;do
 359&nbsp;  case $opt in
 360&nbsp;     $save) save_func;;   #  Save some wgetter sessions for later.
 361&nbsp;     $cook) cookie_func;; #  Change cookie file.
 362&nbsp;     $help) usage;;       #  Get help.
 363&nbsp;     $list) list_func;;   #  Allow wget to use a list of URLs.
 364&nbsp;     $runn) run_func;;    #  Useful if you are calling wgetter from,
 365&nbsp;                          #+ for example, a cron script.
 366&nbsp;     $inpu) run_func;;    #  When you don't know what your files are named.
 367&nbsp;     $wopt) wopts;;       #  Pass options directly to wget.
 368&nbsp;        \?) echo "Not a valid option."
 369&nbsp;            echo "Use -${wopt} to pass options directly to wget,"
 370&nbsp;            echo "or -${help} for help";;      # Catch anything else.
 371&nbsp;  esac
 372&nbsp;done
 373&nbsp;shift $((OPTIND - 1))     # Do funky magic stuff with $#.
 374&nbsp;
 375&nbsp;
 376&nbsp;if [ -z "$1" ] &#38;&#38; [ -z "$lister" ]; then
 377&nbsp;                          #  We should be left with at least one URL
 378&nbsp;                          #+ on the command-line, unless a list is 
 379&nbsp;			  #+ being used -- catch empty CL's.
 380&nbsp;   echo "No URL's given! You must enter them on the same line as wgetter2."
 381&nbsp;   echo "E.g.,  wgetter2 http://somesite http://anothersite."
 382&nbsp;   echo "Use $help option for more information."
 383&nbsp;   exit $E_NO_URLS        # Bail out, with appropriate error code.
 384&nbsp;fi
 385&nbsp;
 386&nbsp;URLS=" $@"
 387&nbsp;# Use this so that URL list can be changed if we stay in the option loop.
 388&nbsp;
 389&nbsp;while [ 1 ]; do
 390&nbsp;   # This is where we ask for the most used options.
 391&nbsp;   # (Mostly unchanged from version 1 of wgetter)
 392&nbsp;   if [ -z $curDepth ]; then
 393&nbsp;      Current=""
 394&nbsp;   else Current=" Current value is $curDepth"
 395&nbsp;   fi
 396&nbsp;       echo "How deep should I go? \
 397&nbsp;(integer: Default is $depthDefault.$Current)"
 398&nbsp;       read Depth   # Recursion -- how far should we go?
 399&nbsp;       inputB=""    # Reset this to blank on each pass of the loop.
 400&nbsp;       echo "Enter the name of the referring page (default is none)."
 401&nbsp;       read inputB  # Need this for some sites.
 402&nbsp;
 403&nbsp;       echo "Do you want to have the output logged to the terminal"
 404&nbsp;       echo "(y/n, default is yes)?"
 405&nbsp;       read noHide  # Otherwise wget will just log it to a file.
 406&nbsp;
 407&nbsp;       case $noHide in    # Now you see me, now you don't.
 408&nbsp;          y|Y ) hide="";;
 409&nbsp;          n|N ) hide=" -b";;
 410&nbsp;            * ) hide="";;
 411&nbsp;       esac
 412&nbsp;
 413&nbsp;       if [ -z ${Depth} ]; then
 414&nbsp;       #  User accepted either default or current depth,
 415&nbsp;       #+ in which case Depth is now empty.
 416&nbsp;          if [ -z ${curDepth} ]; then
 417&nbsp;          #  See if a depth was set on a previous iteration.
 418&nbsp;             Depth="$depthDefault"
 419&nbsp;             #  Set the default recursion depth if nothing
 420&nbsp;             #+ else to use.
 421&nbsp;          else Depth="$curDepth" #  Otherwise, set the one we used before.
 422&nbsp;          fi
 423&nbsp;       fi
 424&nbsp;   Recurse=" -l $Depth"          # Set how deep we want to go.
 425&nbsp;   curDepth=$Depth               # Remember setting for next time.
 426&nbsp;
 427&nbsp;       if [ ! -z $inputB ]; then
 428&nbsp;          RefA=" --referer=$inputB"   # Option to use referring page.
 429&nbsp;       fi
 430&nbsp;
 431&nbsp;   WGETTER="${CommandA}${pattern}${hide}${RefA}${Recurse}\
 432&nbsp;${CookiesON}${lister}${Woptions}${URLS}"
 433&nbsp;   #  Just string the whole lot together . . .
 434&nbsp;   #  NB: no embedded spaces.
 435&nbsp;   #  They are in the individual elements so that if any are empty,
 436&nbsp;   #+ we don't get an extra space.
 437&nbsp;
 438&nbsp;   if [ -z "${CookiesON}" ] &#38;&#38; [ "$cFlag" = "1" ] ; then
 439&nbsp;       echo "Warning -- can't find cookie file"
 440&nbsp;       #  This should be changed,
 441&nbsp;       #+ in case the user has opted to not use cookies.
 442&nbsp;   fi
 443&nbsp;
 444&nbsp;   if [ "$Flag" = "S" ]; then
 445&nbsp;      echo "$WGETTER" &#62;&#62; $savePath/wget-${today}
 446&nbsp;      #  Create a unique filename for today, or append to it if it exists.
 447&nbsp;      echo "$inputB" &#62;&#62; $savePath/site-list-${today}
 448&nbsp;      #  Make a list, so it's easy to refer back to,
 449&nbsp;      #+ since the whole command is a bit confusing to look at.
 450&nbsp;      echo "Command saved to the file $savePath/wget-${today}"
 451&nbsp;           # Tell the user.
 452&nbsp;      echo "Referring page URL saved to the file$ \
 453&nbsp;savePath/site-list-${today}"
 454&nbsp;           # Tell the user.
 455&nbsp;      Saver=" with save option"
 456&nbsp;      # Stick this somewhere, so it appears in the loop if set.
 457&nbsp;   else
 458&nbsp;       echo "*****************"
 459&nbsp;       echo "*****Getting*****"
 460&nbsp;       echo "*****************"
 461&nbsp;       echo ""
 462&nbsp;       echo "$WGETTER"
 463&nbsp;       echo ""
 464&nbsp;       echo "*****************"
 465&nbsp;       eval "$WGETTER"
 466&nbsp;   fi
 467&nbsp;
 468&nbsp;       echo ""
 469&nbsp;       echo "Starting over$Saver."
 470&nbsp;       echo "If you want to stop, press q."
 471&nbsp;       echo "Otherwise, enter some URL's:"
 472&nbsp;       # Let them go again. Tell about save option being set.
 473&nbsp;
 474&nbsp;       read
 475&nbsp;       case $REPLY in
 476&nbsp;       # Need to change this to a 'trap' clause.
 477&nbsp;          q|Q ) exit $E_USER_EXIT;;  # Exercise for the reader?
 478&nbsp;            * ) URLS=" $REPLY";;
 479&nbsp;       esac
 480&nbsp;
 481&nbsp;       echo ""
 482&nbsp;done
 483&nbsp;
 484&nbsp;
 485&nbsp;exit 0</PRE
></TD
></TR
></TABLE
><HR></DIV
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="BASHPODDER"
></A
><P
><B
>Example A-31. A <I
CLASS="FIRSTTERM"
>podcasting</I
> script</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#!/bin/bash
   2&nbsp;
   3&nbsp;#  bashpodder.sh:
   4&nbsp;#  By Linc 10/1/2004
   5&nbsp;#  Find the latest script at
   6&nbsp;#+ http://linc.homeunix.org:8080/scripts/bashpodder
   7&nbsp;#  Last revision 12/14/2004 - Many Contributors!
   8&nbsp;#  If you use this and have made improvements or have comments
   9&nbsp;#+ drop me an email at linc dot fessenden at gmail dot com
  10&nbsp;#  I'd appreciate it!
  11&nbsp;
  12&nbsp;# ==&#62;  ABS Guide extra comments.
  13&nbsp;
  14&nbsp;# ==&#62;  Author of this script has kindly granted permission
  15&nbsp;# ==&#62;+ for inclusion in ABS Guide.
  16&nbsp;
  17&nbsp;
  18&nbsp;# ==&#62; ################################################################
  19&nbsp;# 
  20&nbsp;# ==&#62; What is "podcasting"?
  21&nbsp;
  22&nbsp;# ==&#62; It's broadcasting "radio shows" over the Internet.
  23&nbsp;# ==&#62; These shows can be played on iPods and other music file players.
  24&nbsp;
  25&nbsp;# ==&#62; This script makes it possible.
  26&nbsp;# ==&#62; See documentation at the script author's site, above.
  27&nbsp;
  28&nbsp;# ==&#62; ################################################################
  29&nbsp;
  30&nbsp;
  31&nbsp;# Make script crontab friendly:
  32&nbsp;cd $(dirname $0)
  33&nbsp;# ==&#62; Change to directory where this script lives.
  34&nbsp;
  35&nbsp;# datadir is the directory you want podcasts saved to:
  36&nbsp;datadir=$(date +%Y-%m-%d)
  37&nbsp;# ==&#62; Will create a date-labeled directory, named: YYYY-MM-DD
  38&nbsp;
  39&nbsp;# Check for and create datadir if necessary:
  40&nbsp;if test ! -d $datadir
  41&nbsp;        then
  42&nbsp;        mkdir $datadir
  43&nbsp;fi
  44&nbsp;
  45&nbsp;# Delete any temp file:
  46&nbsp;rm -f temp.log
  47&nbsp;
  48&nbsp;#  Read the bp.conf file and wget any url not already
  49&nbsp;#+ in the podcast.log file:
  50&nbsp;while read podcast
  51&nbsp;  do # ==&#62; Main action follows.
  52&nbsp;  file=$(wget -q $podcast -O - | tr '\r' '\n' | tr \' \" | \
  53&nbsp;sed -n 's/.*url="\([^"]*\)".*/\1/p')
  54&nbsp;  for url in $file
  55&nbsp;                do
  56&nbsp;                echo $url &#62;&#62; temp.log
  57&nbsp;                if ! grep "$url" podcast.log &#62; /dev/null
  58&nbsp;                        then
  59&nbsp;                        wget -q -P $datadir "$url"
  60&nbsp;                fi
  61&nbsp;                done
  62&nbsp;    done &#60; bp.conf
  63&nbsp;
  64&nbsp;# Move dynamically created log file to permanent log file:
  65&nbsp;cat podcast.log &#62;&#62; temp.log
  66&nbsp;sort temp.log | uniq &#62; podcast.log
  67&nbsp;rm temp.log
  68&nbsp;# Create an m3u playlist:
  69&nbsp;ls $datadir | grep -v m3u &#62; $datadir/podcast.m3u
  70&nbsp;
  71&nbsp;
  72&nbsp;exit 0
  73&nbsp;
  74&nbsp;#################################################
  75&nbsp;For a different scripting approach to Podcasting,
  76&nbsp;see Phil Salkie's article, 
  77&nbsp;"Internet Radio to Podcast with Shell Tools"
  78&nbsp;in the September, 2005 issue of LINUX JOURNAL,
  79&nbsp;http://www.linuxjournal.com/article/8171
  80&nbsp;#################################################</PRE
></TD
></TR
></TABLE
><HR></DIV
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="NIGHTLYBACKUP"
></A
><P
><B
>Example A-32. Nightly backup to a firewire HD</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#!/bin/bash
   2&nbsp;# nightly-backup.sh
   3&nbsp;# http://www.richardneill.org/source.php#nightly-backup-rsync
   4&nbsp;# Copyright (c) 2005 Richard Neill &#60;backup@richardneill.org&#62;.
   5&nbsp;# This is Free Software licensed under the GNU GPL.
   6&nbsp;# ==&#62; Included in ABS Guide with script author's kind permission.
   7&nbsp;# ==&#62; (Thanks!)
   8&nbsp;
   9&nbsp;#  This does a backup from the host computer to a locally connected
  10&nbsp;#+ firewire HDD using rsync and ssh.
  11&nbsp;#  (Script should work with USB-connected device (see lines 40-43).
  12&nbsp;#  It then rotates the backups.
  13&nbsp;#  Run it via cron every night at 5am.
  14&nbsp;#  This only backs up the home directory.
  15&nbsp;#  If ownerships (other than the user's) should be preserved,
  16&nbsp;#+ then run the rsync process as root (and re-instate the -o).
  17&nbsp;#  We save every day for 7 days, then every week for 4 weeks,
  18&nbsp;#+ then every month for 3 months.
  19&nbsp;
  20&nbsp;#  See: http://www.mikerubel.org/computers/rsync_snapshots/
  21&nbsp;#+ for more explanation of the theory.
  22&nbsp;#  Save as: $HOME/bin/nightly-backup_firewire-hdd.sh
  23&nbsp;
  24&nbsp;#  Known bugs:
  25&nbsp;#  ----------
  26&nbsp;#  i)  Ideally, we want to exclude ~/.tmp and the browser caches.
  27&nbsp;
  28&nbsp;#  ii) If the user is sitting at the computer at 5am,
  29&nbsp;#+     and files are modified while the rsync is occurring,
  30&nbsp;#+     then the BACKUP_JUSTINCASE branch gets triggered.
  31&nbsp;#      To some extent, this is a 
  32&nbsp;#+     feature, but it also causes a "disk-space leak".
  33&nbsp;
  34&nbsp;
  35&nbsp;
  36&nbsp;
  37&nbsp;
  38&nbsp;##### BEGIN CONFIGURATION SECTION ############################################
  39&nbsp;LOCAL_USER=rjn                # User whose home directory should be backed up.
  40&nbsp;MOUNT_POINT=/backup           # Mountpoint of backup drive.
  41&nbsp;                              # NO trailing slash!
  42&nbsp;                              # This must be unique (eg using a udev symlink)
  43&nbsp;# MOUNT_POINT=/media/disk     # For USB-connected device.
  44&nbsp;SOURCE_DIR=/home/$LOCAL_USER  # NO trailing slash - it DOES matter to rsync.
  45&nbsp;BACKUP_DEST_DIR=$MOUNT_POINT/backup/`hostname -s`.${LOCAL_USER}.nightly_backup
  46&nbsp;DRY_RUN=false                 #If true, invoke rsync with -n, to do a dry run.
  47&nbsp;                              # Comment out or set to false for normal use.
  48&nbsp;VERBOSE=false                 # If true, make rsync verbose.
  49&nbsp;                              # Comment out or set to false otherwise.
  50&nbsp;COMPRESS=false                # If true, compress.
  51&nbsp;                              # Good for internet, bad on LAN.
  52&nbsp;                              # Comment out or set to false otherwise.
  53&nbsp;
  54&nbsp;### Exit Codes ###
  55&nbsp;E_VARS_NOT_SET=64
  56&nbsp;E_COMMANDLINE=65
  57&nbsp;E_MOUNT_FAIL=70
  58&nbsp;E_NOSOURCEDIR=71
  59&nbsp;E_UNMOUNTED=72
  60&nbsp;E_BACKUP=73
  61&nbsp;##### END CONFIGURATION SECTION ##############################################
  62&nbsp;
  63&nbsp;
  64&nbsp;# Check that all the important variables have been set:
  65&nbsp;if [ -z "$LOCAL_USER" ] ||
  66&nbsp;   [ -z "$SOURCE_DIR" ] ||
  67&nbsp;   [ -z "$MOUNT_POINT" ]  ||
  68&nbsp;   [ -z "$BACKUP_DEST_DIR" ]
  69&nbsp;then
  70&nbsp;   echo 'One of the variables is not set! Edit the file: $0. BACKUP FAILED.'
  71&nbsp;   exit $E_VARS_NOT_SET
  72&nbsp;fi
  73&nbsp;
  74&nbsp;if [ "$#" != 0 ]  # If command-line param(s) . . .
  75&nbsp;then              # Here document(ation).
  76&nbsp;  cat &#60;&#60;-ENDOFTEXT
  77&nbsp;    Automatic Nightly backup run from cron.
  78&nbsp;    Read the source for more details: $0
  79&nbsp;    The backup directory is $BACKUP_DEST_DIR .
  80&nbsp;    It will be created if necessary; initialisation is no longer required.
  81&nbsp;
  82&nbsp;    WARNING: Contents of $BACKUP_DEST_DIR are rotated.
  83&nbsp;    Directories named 'backup.\$i' will eventually be DELETED.
  84&nbsp;    We keep backups from every day for 7 days (1-8),
  85&nbsp;    then every week for 4 weeks (9-12),
  86&nbsp;    then every month for 3 months (13-15).
  87&nbsp;
  88&nbsp;    You may wish to add this to your crontab using 'crontab -e'
  89&nbsp;    #  Back up files: $SOURCE_DIR to $BACKUP_DEST_DIR
  90&nbsp;    #+ every night at 3:15 am
  91&nbsp;         15 03 * * * /home/$LOCAL_USER/bin/nightly-backup_firewire-hdd.sh
  92&nbsp;
  93&nbsp;    Don't forget to verify the backups are working,
  94&nbsp;    especially if you don't read cron's mail!"
  95&nbsp;	ENDOFTEXT
  96&nbsp;   exit $E_COMMANDLINE
  97&nbsp;fi
  98&nbsp;
  99&nbsp;
 100&nbsp;# Parse the options.
 101&nbsp;# ==================
 102&nbsp;
 103&nbsp;if [ "$DRY_RUN" == "true" ]; then
 104&nbsp;  DRY_RUN="-n"
 105&nbsp;  echo "WARNING:"
 106&nbsp;  echo "THIS IS A 'DRY RUN'!"
 107&nbsp;  echo "No data will actually be transferred!"
 108&nbsp;else
 109&nbsp;  DRY_RUN=""
 110&nbsp;fi
 111&nbsp;
 112&nbsp;if [ "$VERBOSE" == "true" ]; then
 113&nbsp;  VERBOSE="-v"
 114&nbsp;else
 115&nbsp;  VERBOSE=""
 116&nbsp;fi
 117&nbsp;
 118&nbsp;if [ "$COMPRESS" == "true" ]; then
 119&nbsp;  COMPRESS="-z"
 120&nbsp;else
 121&nbsp;  COMPRESS=""
 122&nbsp;fi
 123&nbsp;
 124&nbsp;
 125&nbsp;#  Every week (actually of 8 days) and every month,
 126&nbsp;#+ extra backups are preserved.
 127&nbsp;DAY_OF_MONTH=`date +%d`            # Day of month (01..31).
 128&nbsp;if [ $DAY_OF_MONTH = 01 ]; then    # First of month.
 129&nbsp;  MONTHSTART=true
 130&nbsp;elif [ $DAY_OF_MONTH = 08 \
 131&nbsp;    -o $DAY_OF_MONTH = 16 \
 132&nbsp;    -o $DAY_OF_MONTH = 24 ]; then
 133&nbsp;    # Day 8,16,24  (use 8, not 7 to better handle 31-day months)
 134&nbsp;      WEEKSTART=true
 135&nbsp;fi
 136&nbsp;
 137&nbsp;
 138&nbsp;
 139&nbsp;#  Check that the HDD is mounted.
 140&nbsp;#  At least, check that *something* is mounted here!
 141&nbsp;#  We can use something unique to the device, rather than just guessing
 142&nbsp;#+ the scsi-id by having an appropriate udev rule in
 143&nbsp;#+ /etc/udev/rules.d/10-rules.local
 144&nbsp;#+ and by putting a relevant entry in /etc/fstab.
 145&nbsp;#  Eg: this udev rule:
 146&nbsp;# BUS="scsi", KERNEL="sd*", SYSFS{vendor}="WDC WD16",
 147&nbsp;# SYSFS{model}="00JB-00GVA0     ", NAME="%k", SYMLINK="lacie_1394d%n"
 148&nbsp;
 149&nbsp;if mount | grep $MOUNT_POINT &#62;/dev/null; then
 150&nbsp;  echo "Mount point $MOUNT_POINT is indeed mounted. OK"
 151&nbsp;else
 152&nbsp;  echo -n "Attempting to mount $MOUNT_POINT..."	
 153&nbsp;           # If it isn't mounted, try to mount it.
 154&nbsp;  sudo mount $MOUNT_POINT 2&#62;/dev/null
 155&nbsp;
 156&nbsp;  if mount | grep $MOUNT_POINT &#62;/dev/null; then
 157&nbsp;    UNMOUNT_LATER=TRUE
 158&nbsp;    echo "OK"
 159&nbsp;    #  Note: Ensure that this is also unmounted
 160&nbsp;    #+ if we exit prematurely with failure.
 161&nbsp;  else
 162&nbsp;    echo "FAILED"
 163&nbsp;    echo -e "Nothing is mounted at $MOUNT_POINT. BACKUP FAILED!"
 164&nbsp;    exit $E_MOUNT_FAIL
 165&nbsp;  fi
 166&nbsp;fi
 167&nbsp;
 168&nbsp;
 169&nbsp;# Check that source dir exists and is readable.
 170&nbsp;if [ ! -r  $SOURCE_DIR ] ; then
 171&nbsp;  echo "$SOURCE_DIR does not exist, or cannot be read. BACKUP FAILED."
 172&nbsp;  exit $E_NOSOURCEDIR
 173&nbsp;fi
 174&nbsp;
 175&nbsp;
 176&nbsp;# Check that the backup directory structure is as it should be.
 177&nbsp;# If not, create it.
 178&nbsp;# Create the subdirectories.
 179&nbsp;# Note that backup.0 will be created as needed by rsync.
 180&nbsp;
 181&nbsp;for ((i=1;i&#60;=15;i++)); do
 182&nbsp;  if [ ! -d $BACKUP_DEST_DIR/backup.$i ]; then
 183&nbsp;    if /bin/mkdir -p $BACKUP_DEST_DIR/backup.$i ; then
 184&nbsp;    #  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^  No [ ] test brackets. Why?
 185&nbsp;      echo "Warning: directory $BACKUP_DEST_DIR/backup.$i is missing,"
 186&nbsp;      echo "or was not initialised. (Re-)creating it."
 187&nbsp;    else
 188&nbsp;      echo "ERROR: directory $BACKUP_DEST_DIR/backup.$i"
 189&nbsp;      echo "is missing and could not be created."
 190&nbsp;    if  [ "$UNMOUNT_LATER" == "TRUE" ]; then
 191&nbsp;        # Before we exit, unmount the mount point if necessary.
 192&nbsp;        cd
 193&nbsp;	sudo umount $MOUNT_POINT &#38;&#38;
 194&nbsp;	echo "Unmounted $MOUNT_POINT again. Giving up."
 195&nbsp;    fi
 196&nbsp;      exit $E_UNMOUNTED
 197&nbsp;  fi
 198&nbsp;fi
 199&nbsp;done
 200&nbsp;
 201&nbsp;
 202&nbsp;#  Set the permission to 700 for security
 203&nbsp;#+ on an otherwise permissive multi-user system.
 204&nbsp;if ! /bin/chmod 700 $BACKUP_DEST_DIR ; then
 205&nbsp;  echo "ERROR: Could not set permissions on $BACKUP_DEST_DIR to 700."
 206&nbsp;
 207&nbsp;  if  [ "$UNMOUNT_LATER" == "TRUE" ]; then
 208&nbsp;  # Before we exit, unmount the mount point if necessary.
 209&nbsp;     cd ; sudo umount $MOUNT_POINT \
 210&nbsp;     &#38;&#38; echo "Unmounted $MOUNT_POINT again. Giving up."
 211&nbsp;  fi
 212&nbsp;
 213&nbsp;  exit $E_UNMOUNTED
 214&nbsp;fi
 215&nbsp;
 216&nbsp;# Create the symlink: current -&#62; backup.1 if required.
 217&nbsp;# A failure here is not critical.
 218&nbsp;cd $BACKUP_DEST_DIR
 219&nbsp;if [ ! -h current ] ; then
 220&nbsp;  if ! /bin/ln -s backup.1 current ; then
 221&nbsp;    echo "WARNING: could not create symlink current -&#62; backup.1"
 222&nbsp;  fi
 223&nbsp;fi
 224&nbsp;
 225&nbsp;
 226&nbsp;# Now, do the rsync.
 227&nbsp;echo "Now doing backup with rsync..."
 228&nbsp;echo "Source dir: $SOURCE_DIR"
 229&nbsp;echo -e "Backup destination dir: $BACKUP_DEST_DIR\n"
 230&nbsp;
 231&nbsp;
 232&nbsp;/usr/bin/rsync $DRY_RUN $VERBOSE -a -S --delete --modify-window=60 \
 233&nbsp;--link-dest=../backup.1 $SOURCE_DIR $BACKUP_DEST_DIR/backup.0/
 234&nbsp;
 235&nbsp;#  Only warn, rather than exit if the rsync failed,
 236&nbsp;#+ since it may only be a minor problem.
 237&nbsp;#  E.g., if one file is not readable, rsync will fail.
 238&nbsp;#  This shouldn't prevent the rotation.
 239&nbsp;#  Not using, e.g., `date +%a`  since these directories
 240&nbsp;#+ are just full of links and don't consume *that much* space.
 241&nbsp;
 242&nbsp;if [ $? != 0 ]; then
 243&nbsp;  BACKUP_JUSTINCASE=backup.`date +%F_%T`.justincase
 244&nbsp;  echo "WARNING: the rsync process did not entirely succeed."
 245&nbsp;  echo "Something might be wrong."
 246&nbsp;  echo "Saving an extra copy at: $BACKUP_JUSTINCASE"
 247&nbsp;  echo "WARNING: if this occurs regularly, a LOT of space will be consumed,"
 248&nbsp;  echo "even though these are just hard-links!"
 249&nbsp;fi
 250&nbsp;
 251&nbsp;# Save a readme in the backup parent directory.
 252&nbsp;# Save another one in the recent subdirectory.
 253&nbsp;echo "Backup of $SOURCE_DIR on `hostname` was last run on \
 254&nbsp;`date`" &#62; $BACKUP_DEST_DIR/README.txt
 255&nbsp;echo "This backup of $SOURCE_DIR on `hostname` was created on \
 256&nbsp;`date`" &#62; $BACKUP_DEST_DIR/backup.0/README.txt
 257&nbsp;
 258&nbsp;# If we are not in a dry run, rotate the backups.
 259&nbsp;[ -z "$DRY_RUN" ] &#38;&#38;
 260&nbsp;
 261&nbsp;  #  Check how full the backup disk is.
 262&nbsp;  #  Warn if 90%. if 98% or more, we'll probably fail, so give up.
 263&nbsp;  #  (Note: df can output to more than one line.)
 264&nbsp;  #  We test this here, rather than before
 265&nbsp;  #+ so that rsync may possibly have a chance.
 266&nbsp;  DISK_FULL_PERCENT=`/bin/df $BACKUP_DEST_DIR |
 267&nbsp;  tr "\n" ' ' | awk '{print $12}' | grep -oE [0-9]+ `
 268&nbsp;  echo "Disk space check on backup partition \
 269&nbsp;  $MOUNT_POINT $DISK_FULL_PERCENT% full."
 270&nbsp;  if [ $DISK_FULL_PERCENT -gt 90 ]; then
 271&nbsp;    echo "Warning: Disk is greater than 90% full."
 272&nbsp;  fi
 273&nbsp;  if [ $DISK_FULL_PERCENT -gt 98 ]; then
 274&nbsp;    echo "Error: Disk is full! Giving up."
 275&nbsp;      if  [ "$UNMOUNT_LATER" == "TRUE" ]; then
 276&nbsp;        # Before we exit, unmount the mount point if necessary.
 277&nbsp;        cd; sudo umount $MOUNT_POINT &#38;&#38;
 278&nbsp;        echo "Unmounted $MOUNT_POINT again. Giving up."
 279&nbsp;      fi
 280&nbsp;    exit $E_UNMOUNTED
 281&nbsp;  fi
 282&nbsp;
 283&nbsp;
 284&nbsp; # Create an extra backup.
 285&nbsp; # If this copy fails, give up.
 286&nbsp; if [ -n "$BACKUP_JUSTINCASE" ]; then
 287&nbsp;   if ! /bin/cp -al $BACKUP_DEST_DIR/backup.0 \
 288&nbsp;      $BACKUP_DEST_DIR/$BACKUP_JUSTINCASE
 289&nbsp;   then
 290&nbsp;     echo "ERROR: Failed to create extra copy \
 291&nbsp;     $BACKUP_DEST_DIR/$BACKUP_JUSTINCASE"
 292&nbsp;     if  [ "$UNMOUNT_LATER" == "TRUE" ]; then
 293&nbsp;       # Before we exit, unmount the mount point if necessary.
 294&nbsp;       cd ;sudo umount $MOUNT_POINT &#38;&#38;
 295&nbsp;       echo "Unmounted $MOUNT_POINT again. Giving up."
 296&nbsp;     fi
 297&nbsp;     exit $E_UNMOUNTED
 298&nbsp;   fi
 299&nbsp; fi
 300&nbsp;
 301&nbsp;
 302&nbsp; # At start of month, rotate the oldest 8.
 303&nbsp; if [ "$MONTHSTART" == "true" ]; then
 304&nbsp;   echo -e "\nStart of month. \
 305&nbsp;   Removing oldest backup: $BACKUP_DEST_DIR/backup.15"  &#38;&#38;
 306&nbsp;   /bin/rm -rf  $BACKUP_DEST_DIR/backup.15  &#38;&#38;
 307&nbsp;   echo "Rotating monthly,weekly backups: \
 308&nbsp;   $BACKUP_DEST_DIR/backup.[8-14] -&#62; $BACKUP_DEST_DIR/backup.[9-15]"  &#38;&#38;
 309&nbsp;     /bin/mv $BACKUP_DEST_DIR/backup.14 $BACKUP_DEST_DIR/backup.15  &#38;&#38;
 310&nbsp;     /bin/mv $BACKUP_DEST_DIR/backup.13 $BACKUP_DEST_DIR/backup.14  &#38;&#38;
 311&nbsp;     /bin/mv $BACKUP_DEST_DIR/backup.12 $BACKUP_DEST_DIR/backup.13  &#38;&#38;
 312&nbsp;     /bin/mv $BACKUP_DEST_DIR/backup.11 $BACKUP_DEST_DIR/backup.12  &#38;&#38;
 313&nbsp;     /bin/mv $BACKUP_DEST_DIR/backup.10 $BACKUP_DEST_DIR/backup.11  &#38;&#38;
 314&nbsp;     /bin/mv $BACKUP_DEST_DIR/backup.9 $BACKUP_DEST_DIR/backup.10  &#38;&#38;
 315&nbsp;     /bin/mv $BACKUP_DEST_DIR/backup.8 $BACKUP_DEST_DIR/backup.9
 316&nbsp;
 317&nbsp; # At start of week, rotate the second-oldest 4.
 318&nbsp; elif [ "$WEEKSTART" == "true" ]; then
 319&nbsp;   echo -e "\nStart of week. \
 320&nbsp;   Removing oldest weekly backup: $BACKUP_DEST_DIR/backup.12"  &#38;&#38;
 321&nbsp;   /bin/rm -rf  $BACKUP_DEST_DIR/backup.12  &#38;&#38;
 322&nbsp;
 323&nbsp;   echo "Rotating weekly backups: \
 324&nbsp;   $BACKUP_DEST_DIR/backup.[8-11] -&#62; $BACKUP_DEST_DIR/backup.[9-12]"  &#38;&#38;
 325&nbsp;     /bin/mv $BACKUP_DEST_DIR/backup.11 $BACKUP_DEST_DIR/backup.12  &#38;&#38;
 326&nbsp;     /bin/mv $BACKUP_DEST_DIR/backup.10 $BACKUP_DEST_DIR/backup.11  &#38;&#38;
 327&nbsp;     /bin/mv $BACKUP_DEST_DIR/backup.9 $BACKUP_DEST_DIR/backup.10  &#38;&#38;
 328&nbsp;     /bin/mv $BACKUP_DEST_DIR/backup.8 $BACKUP_DEST_DIR/backup.9
 329&nbsp;
 330&nbsp; else
 331&nbsp;   echo -e "\nRemoving oldest daily backup: $BACKUP_DEST_DIR/backup.8"  &#38;&#38;
 332&nbsp;     /bin/rm -rf  $BACKUP_DEST_DIR/backup.8
 333&nbsp;
 334&nbsp; fi  &#38;&#38;
 335&nbsp;
 336&nbsp; # Every day, rotate the newest 8.
 337&nbsp; echo "Rotating daily backups: \
 338&nbsp; $BACKUP_DEST_DIR/backup.[1-7] -&#62; $BACKUP_DEST_DIR/backup.[2-8]"  &#38;&#38;
 339&nbsp;     /bin/mv $BACKUP_DEST_DIR/backup.7 $BACKUP_DEST_DIR/backup.8  &#38;&#38;
 340&nbsp;     /bin/mv $BACKUP_DEST_DIR/backup.6 $BACKUP_DEST_DIR/backup.7  &#38;&#38;
 341&nbsp;     /bin/mv $BACKUP_DEST_DIR/backup.5 $BACKUP_DEST_DIR/backup.6  &#38;&#38;
 342&nbsp;     /bin/mv $BACKUP_DEST_DIR/backup.4 $BACKUP_DEST_DIR/backup.5  &#38;&#38;
 343&nbsp;     /bin/mv $BACKUP_DEST_DIR/backup.3 $BACKUP_DEST_DIR/backup.4  &#38;&#38;
 344&nbsp;     /bin/mv $BACKUP_DEST_DIR/backup.2 $BACKUP_DEST_DIR/backup.3  &#38;&#38;
 345&nbsp;     /bin/mv $BACKUP_DEST_DIR/backup.1 $BACKUP_DEST_DIR/backup.2  &#38;&#38;
 346&nbsp;     /bin/mv $BACKUP_DEST_DIR/backup.0 $BACKUP_DEST_DIR/backup.1  &#38;&#38;
 347&nbsp;
 348&nbsp; SUCCESS=true
 349&nbsp;
 350&nbsp;
 351&nbsp;if  [ "$UNMOUNT_LATER" == "TRUE" ]; then
 352&nbsp;  # Unmount the mount point if it wasn't mounted to begin with.
 353&nbsp;  cd ; sudo umount $MOUNT_POINT &#38;&#38; echo "Unmounted $MOUNT_POINT again."
 354&nbsp;fi
 355&nbsp;
 356&nbsp;
 357&nbsp;if [ "$SUCCESS" == "true" ]; then
 358&nbsp;  echo 'SUCCESS!'
 359&nbsp;  exit 0
 360&nbsp;fi
 361&nbsp;
 362&nbsp;# Should have already exited if backup worked.
 363&nbsp;echo 'BACKUP FAILED! Is this just a dry run? Is the disk full?) '
 364&nbsp;exit $E_BACKUP</PRE
></TD
></TR
></TABLE
><HR></DIV
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="CDLL"
></A
><P
><B
>Example A-33. An expanded <I
CLASS="FIRSTTERM"
>cd</I
> command</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;###########################################################################
   2&nbsp;#
   3&nbsp;#       cdll
   4&nbsp;#       by Phil Braham
   5&nbsp;#
   6&nbsp;#       ############################################
   7&nbsp;#       Latest version of this script available from
   8&nbsp;#       http://freshmeat.net/projects/cd/
   9&nbsp;#       ############################################
  10&nbsp;#
  11&nbsp;#       .cd_new
  12&nbsp;#
  13&nbsp;#       An enhancement of the Unix cd command
  14&nbsp;#
  15&nbsp;#       There are unlimited stack entries and special entries. The stack
  16&nbsp;#       entries keep the last cd_maxhistory
  17&nbsp;#       directories that have been used. The special entries can be
  18&nbsp;#       assigned to commonly used directories.
  19&nbsp;#
  20&nbsp;#       The special entries may be pre-assigned by setting the environment
  21&nbsp;#       variables CDSn or by using the -u or -U command.
  22&nbsp;#
  23&nbsp;#       The following is a suggestion for the .profile file:
  24&nbsp;#
  25&nbsp;#               . cdll              #  Set up the cd command
  26&nbsp;#       alias cd='cd_new'           #  Replace the cd command
  27&nbsp;#               cd -U               #  Upload pre-assigned entries for
  28&nbsp;#                                   #+ the stack and special entries
  29&nbsp;#               cd -D               #  Set non-default mode
  30&nbsp;#               alias @="cd_new @"  #  Allow @ to be used to get history
  31&nbsp;#
  32&nbsp;#       For help type:
  33&nbsp;#
  34&nbsp;#               cd -h or
  35&nbsp;#               cd -H
  36&nbsp;#
  37&nbsp;#
  38&nbsp;###########################################################################
  39&nbsp;#
  40&nbsp;#       Version 1.2.1
  41&nbsp;#
  42&nbsp;#       Written by Phil Braham - Realtime Software Pty Ltd
  43&nbsp;#       (realtime@mpx.com.au)
  44&nbsp;#       Please send any suggestions or enhancements to the author (also at
  45&nbsp;#       phil@braham.net)
  46&nbsp;#
  47&nbsp;############################################################################
  48&nbsp;
  49&nbsp;cd_hm ()
  50&nbsp;{
  51&nbsp;        ${PRINTF} "%s" "cd [dir] [0-9] [@[s|h] [-g [&#60;dir&#62;]] [-d] \
  52&nbsp;[-D] [-r&#60;n&#62;] [dir|0-9] [-R&#60;n&#62;] [&#60;dir&#62;|0-9]
  53&nbsp;   [-s&#60;n&#62;] [-S&#60;n&#62;] [-u] [-U] [-f] [-F] [-h] [-H] [-v]
  54&nbsp;    &#60;dir&#62; Go to directory
  55&nbsp;    0-n         Go to previous directory (0 is previous, 1 is last but 1 etc)
  56&nbsp;                n is up to max history (default is 50)
  57&nbsp;    @           List history and special entries
  58&nbsp;    @h          List history entries
  59&nbsp;    @s          List special entries
  60&nbsp;    -g [&#60;dir&#62;]  Go to literal name (bypass special names)
  61&nbsp;                This is to allow access to dirs called '0','1','-h' etc
  62&nbsp;    -d          Change default action - verbose. (See note)
  63&nbsp;    -D          Change default action - silent. (See note)
  64&nbsp;    -s&#60;n&#62; Go to the special entry &#60;n&#62;*
  65&nbsp;    -S&#60;n&#62; Go to the special entry &#60;n&#62;
  66&nbsp;                and replace it with the current dir*
  67&nbsp;    -r&#60;n&#62; [&#60;dir&#62;] Go to directory &#60;dir&#62;
  68&nbsp;                              and then put it on special entry &#60;n&#62;*
  69&nbsp;    -R&#60;n&#62; [&#60;dir&#62;] Go to directory &#60;dir&#62;
  70&nbsp;                              and put current dir on special entry &#60;n&#62;*
  71&nbsp;    -a&#60;n&#62;       Alternative suggested directory. See note below.
  72&nbsp;    -f [&#60;file&#62;] File entries to &#60;file&#62;.
  73&nbsp;    -u [&#60;file&#62;] Update entries from &#60;file&#62;.
  74&nbsp;                If no filename supplied then default file
  75&nbsp;                (${CDPath}${2:-"$CDFile"}) is used
  76&nbsp;                -F and -U are silent versions
  77&nbsp;    -v          Print version number
  78&nbsp;    -h          Help
  79&nbsp;    -H          Detailed help
  80&nbsp;
  81&nbsp;    *The special entries (0 - 9) are held until log off, replaced by another
  82&nbsp;     entry or updated with the -u command
  83&nbsp;
  84&nbsp;    Alternative suggested directories:
  85&nbsp;    If a directory is not found then CD will suggest any
  86&nbsp;    possibilities. These are directories starting with the same letters
  87&nbsp;    and if any are found they are listed prefixed with -a&#60;n&#62;
  88&nbsp;    where &#60;n&#62; is a number.
  89&nbsp;    It's possible to go to the directory by entering cd -a&#60;n&#62;
  90&nbsp;    on the command line.
  91&nbsp;    
  92&nbsp;    The directory for -r&#60;n&#62; or -R&#60;n&#62; may be a number.
  93&nbsp;    For example:
  94&nbsp;        $ cd -r3 4  Go to history entry 4 and put it on special entry 3
  95&nbsp;        $ cd -R3 4  Put current dir on the special entry 3
  96&nbsp;                    and go to history entry 4
  97&nbsp;        $ cd -s3    Go to special entry 3
  98&nbsp;    
  99&nbsp;    Note that commands R,r,S and s may be used without a number
 100&nbsp;    and refer to 0:
 101&nbsp;        $ cd -s     Go to special entry 0
 102&nbsp;        $ cd -S     Go to special entry 0 and make special
 103&nbsp;                    entry 0 current dir
 104&nbsp;        $ cd -r 1   Go to history entry 1 and put it on special entry 0
 105&nbsp;        $ cd -r     Go to history entry 0 and put it on special entry 0
 106&nbsp;    "
 107&nbsp;        if ${TEST} "$CD_MODE" = "PREV"
 108&nbsp;        then
 109&nbsp;                ${PRINTF} "$cd_mnset"
 110&nbsp;        else
 111&nbsp;                ${PRINTF} "$cd_mset"
 112&nbsp;        fi
 113&nbsp;}
 114&nbsp;
 115&nbsp;cd_Hm ()
 116&nbsp;{
 117&nbsp;        cd_hm
 118&nbsp;        ${PRINTF} "%s" "
 119&nbsp;        The previous directories (0-$cd_maxhistory) are stored in the
 120&nbsp;        environment variables CD[0] - CD[$cd_maxhistory]
 121&nbsp;        Similarly the special directories S0 - $cd_maxspecial are in
 122&nbsp;        the environment variable CDS[0] - CDS[$cd_maxspecial]
 123&nbsp;        and may be accessed from the command line
 124&nbsp;
 125&nbsp;        The default pathname for the -f and -u commands is $CDPath
 126&nbsp;        The default filename for the -f and -u commands is $CDFile
 127&nbsp;
 128&nbsp;        Set the following environment variables:
 129&nbsp;            CDL_PROMPTLEN  - Set to the length of prompt you require.
 130&nbsp;                Prompt string is set to the right characters of the
 131&nbsp;                current directory.
 132&nbsp;                If not set then prompt is left unchanged
 133&nbsp;            CDL_PROMPT_PRE - Set to the string to prefix the prompt.
 134&nbsp;                Default is:
 135&nbsp;                    non-root:  \"\\[\\e[01;34m\\]\"  (sets colour to blue).
 136&nbsp;                    root:      \"\\[\\e[01;31m\\]\"  (sets colour to red).
 137&nbsp;            CDL_PROMPT_POST    - Set to the string to suffix the prompt.
 138&nbsp;                Default is:
 139&nbsp;                    non-root:  \"\\[\\e[00m\\]$\"
 140&nbsp;                                (resets colour and displays $).
 141&nbsp;                    root:      \"\\[\\e[00m\\]#\"
 142&nbsp;                                (resets colour and displays #).
 143&nbsp;            CDPath - Set the default path for the -f &#38; -u options.
 144&nbsp;                     Default is home directory
 145&nbsp;            CDFile - Set the default filename for the -f &#38; -u options.
 146&nbsp;                     Default is cdfile
 147&nbsp;        
 148&nbsp;"
 149&nbsp;    cd_version
 150&nbsp;
 151&nbsp;}
 152&nbsp;
 153&nbsp;cd_version ()
 154&nbsp;{
 155&nbsp; printf "Version: ${VERSION_MAJOR}.${VERSION_MINOR} Date: ${VERSION_DATE}\n"
 156&nbsp;}
 157&nbsp;
 158&nbsp;#
 159&nbsp;# Truncate right.
 160&nbsp;#
 161&nbsp;# params:
 162&nbsp;#   p1 - string
 163&nbsp;#   p2 - length to truncate to
 164&nbsp;#
 165&nbsp;# returns string in tcd
 166&nbsp;#
 167&nbsp;cd_right_trunc ()
 168&nbsp;{
 169&nbsp;    local tlen=${2}
 170&nbsp;    local plen=${#1}
 171&nbsp;    local str="${1}"
 172&nbsp;    local diff
 173&nbsp;    local filler="&#60;--"
 174&nbsp;    if ${TEST} ${plen} -le ${tlen}
 175&nbsp;    then
 176&nbsp;        tcd="${str}"
 177&nbsp;    else
 178&nbsp;        let diff=${plen}-${tlen}
 179&nbsp;        elen=3
 180&nbsp;        if ${TEST} ${diff} -le 2
 181&nbsp;        then
 182&nbsp;            let elen=${diff}
 183&nbsp;        fi
 184&nbsp;        tlen=-${tlen}
 185&nbsp;        let tlen=${tlen}+${elen}
 186&nbsp;        tcd=${filler:0:elen}${str:tlen}
 187&nbsp;    fi
 188&nbsp;}
 189&nbsp;
 190&nbsp;#
 191&nbsp;# Three versions of do history:
 192&nbsp;#    cd_dohistory  - packs history and specials side by side
 193&nbsp;#    cd_dohistoryH - Shows only hstory
 194&nbsp;#    cd_dohistoryS - Shows only specials
 195&nbsp;#
 196&nbsp;cd_dohistory ()
 197&nbsp;{
 198&nbsp;    cd_getrc
 199&nbsp;        ${PRINTF} "History:\n"
 200&nbsp;    local -i count=${cd_histcount}
 201&nbsp;    while ${TEST} ${count} -ge 0
 202&nbsp;    do
 203&nbsp;        cd_right_trunc "${CD[count]}" ${cd_lchar}
 204&nbsp;            ${PRINTF} "%2d %-${cd_lchar}.${cd_lchar}s " ${count} "${tcd}"
 205&nbsp;
 206&nbsp;        cd_right_trunc "${CDS[count]}" ${cd_rchar}
 207&nbsp;            ${PRINTF} "S%d %-${cd_rchar}.${cd_rchar}s\n" ${count} "${tcd}"
 208&nbsp;        count=${count}-1
 209&nbsp;    done
 210&nbsp;}
 211&nbsp;
 212&nbsp;cd_dohistoryH ()
 213&nbsp;{
 214&nbsp;    cd_getrc
 215&nbsp;        ${PRINTF} "History:\n"
 216&nbsp;        local -i count=${cd_maxhistory}
 217&nbsp;        while ${TEST} ${count} -ge 0
 218&nbsp;        do
 219&nbsp;          ${PRINTF} "${count} %-${cd_flchar}.${cd_flchar}s\n" ${CD[$count]}
 220&nbsp;          count=${count}-1
 221&nbsp;        done
 222&nbsp;}
 223&nbsp;
 224&nbsp;cd_dohistoryS ()
 225&nbsp;{
 226&nbsp;    cd_getrc
 227&nbsp;        ${PRINTF} "Specials:\n"
 228&nbsp;        local -i count=${cd_maxspecial}
 229&nbsp;        while ${TEST} ${count} -ge 0
 230&nbsp;        do
 231&nbsp;          ${PRINTF} "S${count} %-${cd_flchar}.${cd_flchar}s\n" ${CDS[$count]}
 232&nbsp;          count=${count}-1
 233&nbsp;        done
 234&nbsp;}
 235&nbsp;
 236&nbsp;cd_getrc ()
 237&nbsp;{
 238&nbsp;    cd_flchar=$(stty -a | awk -F \;
 239&nbsp;    '/rows/ { print $2 $3 }' | awk -F \  '{ print $4 }')
 240&nbsp;    if ${TEST} ${cd_flchar} -ne 0
 241&nbsp;    then
 242&nbsp;        cd_lchar=${cd_flchar}/2-5
 243&nbsp;        cd_rchar=${cd_flchar}/2-5
 244&nbsp;            cd_flchar=${cd_flchar}-5
 245&nbsp;    else
 246&nbsp;            cd_flchar=${FLCHAR:=75}
 247&nbsp;	    # cd_flchar is used for for the @s &#38; @h history
 248&nbsp;            cd_lchar=${LCHAR:=35}
 249&nbsp;            cd_rchar=${RCHAR:=35}
 250&nbsp;    fi
 251&nbsp;}
 252&nbsp;
 253&nbsp;cd_doselection ()
 254&nbsp;{
 255&nbsp;        local -i nm=0
 256&nbsp;        cd_doflag="TRUE"
 257&nbsp;        if ${TEST} "${CD_MODE}" = "PREV"
 258&nbsp;        then
 259&nbsp;                if ${TEST} -z "$cd_npwd"
 260&nbsp;                then
 261&nbsp;                        cd_npwd=0
 262&nbsp;                fi
 263&nbsp;        fi
 264&nbsp;        tm=$(echo "${cd_npwd}" | cut -b 1)
 265&nbsp;    if ${TEST} "${tm}" = "-"
 266&nbsp;    then
 267&nbsp;        pm=$(echo "${cd_npwd}" | cut -b 2)
 268&nbsp;        nm=$(echo "${cd_npwd}" | cut -d $pm -f2)
 269&nbsp;        case "${pm}" in
 270&nbsp;             a) cd_npwd=${cd_sugg[$nm]} ;;
 271&nbsp;             s) cd_npwd="${CDS[$nm]}" ;;
 272&nbsp;             S) cd_npwd="${CDS[$nm]}" ; CDS[$nm]=`pwd` ;;
 273&nbsp;             r) cd_npwd="$2" ; cd_specDir=$nm ; cd_doselection "$1" "$2";;
 274&nbsp;             R) cd_npwd="$2" ; CDS[$nm]=`pwd` ; cd_doselection "$1" "$2";;
 275&nbsp;        esac
 276&nbsp;    fi
 277&nbsp;
 278&nbsp;    if ${TEST} "${cd_npwd}" != "." -a "${cd_npwd}" \
 279&nbsp;!= ".." -a "${cd_npwd}" -le ${cd_maxhistory} &#62;&#62;/dev/null 2&#62;&#38;1
 280&nbsp;    then
 281&nbsp;      cd_npwd=${CD[$cd_npwd]}
 282&nbsp;     else
 283&nbsp;       case "$cd_npwd" in
 284&nbsp;                @)  cd_dohistory ; cd_doflag="FALSE" ;;
 285&nbsp;               @h) cd_dohistoryH ; cd_doflag="FALSE" ;;
 286&nbsp;               @s) cd_dohistoryS ; cd_doflag="FALSE" ;;
 287&nbsp;               -h) cd_hm ; cd_doflag="FALSE" ;;
 288&nbsp;               -H) cd_Hm ; cd_doflag="FALSE" ;;
 289&nbsp;               -f) cd_fsave "SHOW" $2 ; cd_doflag="FALSE" ;;
 290&nbsp;               -u) cd_upload "SHOW" $2 ; cd_doflag="FALSE" ;;
 291&nbsp;               -F) cd_fsave "NOSHOW" $2 ; cd_doflag="FALSE" ;;
 292&nbsp;               -U) cd_upload "NOSHOW" $2 ; cd_doflag="FALSE" ;;
 293&nbsp;               -g) cd_npwd="$2" ;;
 294&nbsp;               -d) cd_chdefm 1; cd_doflag="FALSE" ;;
 295&nbsp;               -D) cd_chdefm 0; cd_doflag="FALSE" ;;
 296&nbsp;               -r) cd_npwd="$2" ; cd_specDir=0 ; cd_doselection "$1" "$2";;
 297&nbsp;               -R) cd_npwd="$2" ; CDS[0]=`pwd` ; cd_doselection "$1" "$2";;
 298&nbsp;               -s) cd_npwd="${CDS[0]}" ;;
 299&nbsp;               -S) cd_npwd="${CDS[0]}"  ; CDS[0]=`pwd` ;;
 300&nbsp;               -v) cd_version ; cd_doflag="FALSE";;
 301&nbsp;       esac
 302&nbsp;    fi
 303&nbsp;}
 304&nbsp;
 305&nbsp;cd_chdefm ()
 306&nbsp;{
 307&nbsp;        if ${TEST} "${CD_MODE}" = "PREV"
 308&nbsp;        then
 309&nbsp;                CD_MODE=""
 310&nbsp;                if ${TEST} $1 -eq 1
 311&nbsp;                then
 312&nbsp;                        ${PRINTF} "${cd_mset}"
 313&nbsp;                fi
 314&nbsp;        else
 315&nbsp;                CD_MODE="PREV"
 316&nbsp;                if ${TEST} $1 -eq 1
 317&nbsp;                then
 318&nbsp;                        ${PRINTF} "${cd_mnset}"
 319&nbsp;                fi
 320&nbsp;        fi
 321&nbsp;}
 322&nbsp;
 323&nbsp;cd_fsave ()
 324&nbsp;{
 325&nbsp;        local sfile=${CDPath}${2:-"$CDFile"}
 326&nbsp;        if ${TEST} "$1" = "SHOW"
 327&nbsp;        then
 328&nbsp;                ${PRINTF} "Saved to %s\n" $sfile
 329&nbsp;        fi
 330&nbsp;        ${RM} -f ${sfile}
 331&nbsp;        local -i count=0
 332&nbsp;        while ${TEST} ${count} -le ${cd_maxhistory}
 333&nbsp;        do
 334&nbsp;                echo "CD[$count]=\"${CD[$count]}\"" &#62;&#62; ${sfile}
 335&nbsp;                count=${count}+1
 336&nbsp;        done
 337&nbsp;        count=0
 338&nbsp;        while ${TEST} ${count} -le ${cd_maxspecial}
 339&nbsp;        do
 340&nbsp;                echo "CDS[$count]=\"${CDS[$count]}\"" &#62;&#62; ${sfile}
 341&nbsp;                count=${count}+1
 342&nbsp;        done
 343&nbsp;}
 344&nbsp;
 345&nbsp;cd_upload ()
 346&nbsp;{
 347&nbsp;        local sfile=${CDPath}${2:-"$CDFile"}
 348&nbsp;        if ${TEST} "${1}" = "SHOW"
 349&nbsp;        then
 350&nbsp;                ${PRINTF} "Loading from %s\n" ${sfile}
 351&nbsp;        fi
 352&nbsp;        . ${sfile}
 353&nbsp;}
 354&nbsp;
 355&nbsp;cd_new ()
 356&nbsp;{
 357&nbsp;    local -i count
 358&nbsp;    local -i choose=0
 359&nbsp;
 360&nbsp;        cd_npwd="${1}"
 361&nbsp;        cd_specDir=-1
 362&nbsp;        cd_doselection "${1}" "${2}"
 363&nbsp;
 364&nbsp;        if ${TEST} ${cd_doflag} = "TRUE"
 365&nbsp;        then
 366&nbsp;                if ${TEST} "${CD[0]}" != "`pwd`"
 367&nbsp;                then
 368&nbsp;                        count=$cd_maxhistory
 369&nbsp;                        while ${TEST} $count -gt 0
 370&nbsp;                        do
 371&nbsp;                                CD[$count]=${CD[$count-1]}
 372&nbsp;                                count=${count}-1
 373&nbsp;                        done
 374&nbsp;                        CD[0]=`pwd`
 375&nbsp;                fi
 376&nbsp;                command cd "${cd_npwd}" 2&#62;/dev/null
 377&nbsp;        if ${TEST} $? -eq 1
 378&nbsp;        then
 379&nbsp;            ${PRINTF} "Unknown dir: %s\n" "${cd_npwd}"
 380&nbsp;            local -i ftflag=0
 381&nbsp;            for i in "${cd_npwd}"*
 382&nbsp;            do
 383&nbsp;                if ${TEST} -d "${i}"
 384&nbsp;                then
 385&nbsp;                    if ${TEST} ${ftflag} -eq 0
 386&nbsp;                    then
 387&nbsp;                        ${PRINTF} "Suggest:\n"
 388&nbsp;                        ftflag=1
 389&nbsp;                fi
 390&nbsp;                    ${PRINTF} "\t-a${choose} %s\n" "$i"
 391&nbsp;                                        cd_sugg[$choose]="${i}"
 392&nbsp;                    choose=${choose}+1
 393&nbsp;        fi
 394&nbsp;            done
 395&nbsp;        fi
 396&nbsp;        fi
 397&nbsp;
 398&nbsp;        if ${TEST} ${cd_specDir} -ne -1
 399&nbsp;        then
 400&nbsp;                CDS[${cd_specDir}]=`pwd`
 401&nbsp;        fi
 402&nbsp;
 403&nbsp;        if ${TEST} ! -z "${CDL_PROMPTLEN}"
 404&nbsp;        then
 405&nbsp;        cd_right_trunc "${PWD}" ${CDL_PROMPTLEN}
 406&nbsp;            cd_rp=${CDL_PROMPT_PRE}${tcd}${CDL_PROMPT_POST}
 407&nbsp;                export PS1="$(echo -ne ${cd_rp})"
 408&nbsp;        fi
 409&nbsp;}
 410&nbsp;#########################################################################
 411&nbsp;#                                                                       #
 412&nbsp;#                        Initialisation here                            #
 413&nbsp;#                                                                       #
 414&nbsp;#########################################################################
 415&nbsp;#
 416&nbsp;VERSION_MAJOR="1"
 417&nbsp;VERSION_MINOR="2.1"
 418&nbsp;VERSION_DATE="24-MAY-2003"
 419&nbsp;#
 420&nbsp;alias cd=cd_new
 421&nbsp;#
 422&nbsp;# Set up commands
 423&nbsp;RM=/bin/rm
 424&nbsp;TEST=test
 425&nbsp;PRINTF=printf              # Use builtin printf
 426&nbsp;
 427&nbsp;#########################################################################
 428&nbsp;#                                                                       #
 429&nbsp;# Change this to modify the default pre- and post prompt strings.       #
 430&nbsp;# These only come into effect if CDL_PROMPTLEN is set.                  #
 431&nbsp;#                                                                       #
 432&nbsp;#########################################################################
 433&nbsp;if ${TEST} ${EUID} -eq 0
 434&nbsp;then
 435&nbsp;#   CDL_PROMPT_PRE=${CDL_PROMPT_PRE:="$HOSTNAME@"}
 436&nbsp;    CDL_PROMPT_PRE=${CDL_PROMPT_PRE:="\\[\\e[01;31m\\]"}  # Root is in red
 437&nbsp;    CDL_PROMPT_POST=${CDL_PROMPT_POST:="\\[\\e[00m\\]#"}
 438&nbsp;else
 439&nbsp;    CDL_PROMPT_PRE=${CDL_PROMPT_PRE:="\\[\\e[01;34m\\]"}  # Users in blue
 440&nbsp;    CDL_PROMPT_POST=${CDL_PROMPT_POST:="\\[\\e[00m\\]$"}
 441&nbsp;fi
 442&nbsp;#########################################################################
 443&nbsp;#
 444&nbsp;# cd_maxhistory defines the max number of history entries allowed.
 445&nbsp;typeset -i cd_maxhistory=50
 446&nbsp;
 447&nbsp;#########################################################################
 448&nbsp;#
 449&nbsp;# cd_maxspecial defines the number of special entries.
 450&nbsp;typeset -i cd_maxspecial=9
 451&nbsp;#
 452&nbsp;#
 453&nbsp;#########################################################################
 454&nbsp;#
 455&nbsp;#  cd_histcount defines the number of entries displayed in
 456&nbsp;#+ the history command.
 457&nbsp;typeset -i cd_histcount=9
 458&nbsp;#
 459&nbsp;#########################################################################
 460&nbsp;export CDPath=${HOME}/
 461&nbsp;#  Change these to use a different                                      #
 462&nbsp;#+ default path and filename                                            #
 463&nbsp;export CDFile=${CDFILE:=cdfile}           # for the -u and -f commands  #
 464&nbsp;#
 465&nbsp;#########################################################################
 466&nbsp;                                                                        #
 467&nbsp;typeset -i cd_lchar cd_rchar cd_flchar
 468&nbsp;                        #  This is the number of chars to allow for the #
 469&nbsp;cd_flchar=${FLCHAR:=75} #+ cd_flchar is used for for the @s &#38; @h history#
 470&nbsp;
 471&nbsp;typeset -ax CD CDS
 472&nbsp;#
 473&nbsp;cd_mset="\n\tDefault mode is now set - entering cd with no parameters \
 474&nbsp;has the default action\n\tUse cd -d or -D for cd to go to \
 475&nbsp;previous directory with no parameters\n"
 476&nbsp;cd_mnset="\n\tNon-default mode is now set - entering cd with no \
 477&nbsp;parameters is the same as entering cd 0\n\tUse cd -d or \
 478&nbsp;-D to change default cd action\n"
 479&nbsp;
 480&nbsp;# ==================================================================== #
 481&nbsp;
 482&nbsp;
 483&nbsp;
 484&nbsp;: &#60;&#60;DOCUMENTATION
 485&nbsp;
 486&nbsp;Written by Phil Braham. Realtime Software Pty Ltd.
 487&nbsp;Released under GNU license. Free to use. Please pass any modifications
 488&nbsp;or comments to the author Phil Braham:
 489&nbsp;
 490&nbsp;realtime@mpx.com.au
 491&nbsp;=======================================================================
 492&nbsp;
 493&nbsp;cdll is a replacement for cd and incorporates similar functionality to
 494&nbsp;the bash pushd and popd commands but is independent of them.
 495&nbsp;
 496&nbsp;This version of cdll has been tested on Linux using Bash. It will work
 497&nbsp;on most Linux versions but will probably not work on other shells without
 498&nbsp;modification.
 499&nbsp;
 500&nbsp;Introduction
 501&nbsp;============
 502&nbsp;
 503&nbsp;cdll allows easy moving about between directories. When changing to a new
 504&nbsp;directory the current one is automatically put onto a stack. By default
 505&nbsp;50 entries are kept, but this is configurable. Special directories can be
 506&nbsp;kept for easy access - by default up to 10, but this is configurable. The
 507&nbsp;most recent stack entries and the special entries can be easily viewed.
 508&nbsp;
 509&nbsp;The directory stack and special entries can be saved to, and loaded from,
 510&nbsp;a file. This allows them to be set up on login, saved before logging out
 511&nbsp;or changed when moving project to project.
 512&nbsp;
 513&nbsp;In addition, cdll provides a flexible command prompt facility that allows,
 514&nbsp;for example, a directory name in colour that is truncated from the left
 515&nbsp;if it gets too long.
 516&nbsp;
 517&nbsp;
 518&nbsp;Setting up cdll
 519&nbsp;===============
 520&nbsp;
 521&nbsp;Copy cdll to either your local home directory or a central directory
 522&nbsp;such as /usr/bin (this will require root access).
 523&nbsp;
 524&nbsp;Copy the file cdfile to your home directory. It will require read and
 525&nbsp;write access. This a default file that contains a directory stack and
 526&nbsp;special entries.
 527&nbsp;
 528&nbsp;To replace the cd command you must add commands to your login script.
 529&nbsp;The login script is one or more of:
 530&nbsp;
 531&nbsp;    /etc/profile
 532&nbsp;    ~/.bash_profile
 533&nbsp;    ~/.bash_login
 534&nbsp;    ~/.profile
 535&nbsp;    ~/.bashrc
 536&nbsp;    /etc/bash.bashrc.local
 537&nbsp;    
 538&nbsp;To setup your login, ~/.bashrc is recommended, for global (and root) setup
 539&nbsp;add the commands to /etc/bash.bashrc.local
 540&nbsp;    
 541&nbsp;To set up on login, add the command:
 542&nbsp;    . &#60;dir&#62;/cdll
 543&nbsp;For example if cdll is in your local home directory:
 544&nbsp;    . ~/cdll
 545&nbsp;If in /usr/bin then:
 546&nbsp;    . /usr/bin/cdll
 547&nbsp;
 548&nbsp;If you want to use this instead of the buitin cd command then add:
 549&nbsp;    alias cd='cd_new'
 550&nbsp;We would also recommend the following commands:
 551&nbsp;    alias @='cd_new @'
 552&nbsp;    cd -U
 553&nbsp;    cd -D
 554&nbsp;
 555&nbsp;If you want to use cdll's prompt facilty then add the following:
 556&nbsp;    CDL_PROMPTLEN=nn
 557&nbsp;Where nn is a number described below. Initially 99 would be suitable
 558&nbsp;number.
 559&nbsp;
 560&nbsp;Thus the script looks something like this:
 561&nbsp;
 562&nbsp;    ######################################################################
 563&nbsp;    # CD Setup
 564&nbsp;    ######################################################################
 565&nbsp;    CDL_PROMPTLEN=21        # Allow a prompt length of up to 21 characters
 566&nbsp;    . /usr/bin/cdll         # Initialise cdll
 567&nbsp;    alias cd='cd_new'       # Replace the built in cd command
 568&nbsp;    alias @='cd_new @'      # Allow @ at the prompt to display history
 569&nbsp;    cd -U                   # Upload directories
 570&nbsp;    cd -D                   # Set default action to non-posix
 571&nbsp;    ######################################################################
 572&nbsp;
 573&nbsp;The full meaning of these commands will become clear later.
 574&nbsp;
 575&nbsp;There are a couple of caveats. If another program changes the directory
 576&nbsp;without calling cdll, then the directory won't be put on the stack and
 577&nbsp;also if the prompt facility is used then this will not be updated. Two
 578&nbsp;programs that can do this are pushd and popd. To update the prompt and
 579&nbsp;stack simply enter:
 580&nbsp;
 581&nbsp;    cd .
 582&nbsp;    
 583&nbsp;Note that if the previous entry on the stack is the current directory
 584&nbsp;then the stack is not updated.
 585&nbsp;
 586&nbsp;Usage
 587&nbsp;=====  
 588&nbsp;cd [dir] [0-9] [@[s|h] [-g &#60;dir&#62;] [-d] [-D] [-r&#60;n&#62;]
 589&nbsp;   [dir|0-9] [-R&#60;n&#62;] [&#60;dir&#62;|0-9] [-s&#60;n&#62;] [-S&#60;n&#62;]
 590&nbsp;   [-u] [-U] [-f] [-F] [-h] [-H] [-v]
 591&nbsp;
 592&nbsp;    &#60;dir&#62;       Go to directory
 593&nbsp;    0-n         Goto previous directory (0 is previous,
 594&nbsp;                1 is last but 1, etc.)
 595&nbsp;                n is up to max history (default is 50)
 596&nbsp;    @           List history and special entries (Usually available as $ @)
 597&nbsp;    @h          List history entries
 598&nbsp;    @s          List special entries
 599&nbsp;    -g [&#60;dir&#62;]  Go to literal name (bypass special names)
 600&nbsp;                This is to allow access to dirs called '0','1','-h' etc
 601&nbsp;    -d          Change default action - verbose. (See note)
 602&nbsp;    -D          Change default action - silent. (See note)
 603&nbsp;    -s&#60;n&#62;       Go to the special entry &#60;n&#62;
 604&nbsp;    -S&#60;n&#62;       Go to the special entry &#60;n&#62;
 605&nbsp;                      and replace it with the current dir
 606&nbsp;    -r&#60;n&#62; [&#60;dir&#62;] Go to directory &#60;dir&#62;
 607&nbsp;                              and then put it on special entry &#60;n&#62;
 608&nbsp;    -R&#60;n&#62; [&#60;dir&#62;] Go to directory &#60;dir&#62;
 609&nbsp;                              and put current dir on special entry &#60;n&#62;
 610&nbsp;    -a&#60;n&#62;       Alternative suggested directory. See note below.
 611&nbsp;    -f [&#60;file&#62;] File entries to &#60;file&#62;.
 612&nbsp;    -u [&#60;file&#62;] Update entries from &#60;file&#62;.
 613&nbsp;                If no filename supplied then default file (~/cdfile) is used
 614&nbsp;                -F and -U are silent versions
 615&nbsp;    -v          Print version number
 616&nbsp;    -h          Help
 617&nbsp;    -H          Detailed help
 618&nbsp;
 619&nbsp;
 620&nbsp;
 621&nbsp;Examples
 622&nbsp;========
 623&nbsp;
 624&nbsp;These examples assume non-default mode is set (that is, cd with no
 625&nbsp;parameters will go to the most recent stack directory), that aliases
 626&nbsp;have been set up for cd and @ as described above and that cd's prompt
 627&nbsp;facility is active and the prompt length is 21 characters.
 628&nbsp;
 629&nbsp;    /home/phil$ @
 630&nbsp;    # List the entries with the @
 631&nbsp;    History:
 632&nbsp;    # Output of the @ command
 633&nbsp;    .....
 634&nbsp;    # Skipped these entries for brevity
 635&nbsp;    1 /home/phil/ummdev               S1 /home/phil/perl
 636&nbsp;    # Most recent two history entries
 637&nbsp;    0 /home/phil/perl/eg              S0 /home/phil/umm/ummdev
 638&nbsp;    # and two special entries are shown
 639&nbsp;    
 640&nbsp;    /home/phil$ cd /home/phil/utils/Cdll
 641&nbsp;    # Now change directories
 642&nbsp;    /home/phil/utils/Cdll$ @
 643&nbsp;    # Prompt reflects the directory.
 644&nbsp;    History:
 645&nbsp;    # New history
 646&nbsp;    .....   
 647&nbsp;    1 /home/phil/perl/eg              S1 /home/phil/perl
 648&nbsp;    # History entry 0 has moved to 1
 649&nbsp;    0 /home/phil                      S0 /home/phil/umm/ummdev
 650&nbsp;    # and the most recent has entered
 651&nbsp;       
 652&nbsp;To go to a history entry:
 653&nbsp;
 654&nbsp;    /home/phil/utils/Cdll$ cd 1
 655&nbsp;    # Go to history entry 1.
 656&nbsp;    /home/phil/perl/eg$
 657&nbsp;    # Current directory is now what was 1
 658&nbsp;    
 659&nbsp;To go to a special entry:
 660&nbsp;
 661&nbsp;    /home/phil/perl/eg$ cd -s1
 662&nbsp;    # Go to special entry 1
 663&nbsp;    /home/phil/umm/ummdev$
 664&nbsp;    # Current directory is S1
 665&nbsp;
 666&nbsp;To go to a directory called, for example, 1:
 667&nbsp;
 668&nbsp;    /home/phil$ cd -g 1
 669&nbsp;    # -g ignores the special meaning of 1
 670&nbsp;    /home/phil/1$
 671&nbsp;    
 672&nbsp;To put current directory on the special list as S1:
 673&nbsp;    cd -r1 .        #  OR
 674&nbsp;    cd -R1 .        #  These have the same effect if the directory is
 675&nbsp;                    #+ . (the current directory)
 676&nbsp;
 677&nbsp;To go to a directory and add it as a special  
 678&nbsp;  The directory for -r&#60;n&#62; or -R&#60;n&#62; may be a number.
 679&nbsp;  For example:
 680&nbsp;        $ cd -r3 4  Go to history entry 4 and put it on special entry 3
 681&nbsp;        $ cd -R3 4  Put current dir on the special entry 3 and go to
 682&nbsp;                    history entry 4
 683&nbsp;        $ cd -s3    Go to special entry 3
 684&nbsp;
 685&nbsp;    Note that commands R,r,S and s may be used without a number and
 686&nbsp;    refer to 0:
 687&nbsp;        $ cd -s     Go to special entry 0
 688&nbsp;        $ cd -S     Go to special entry 0 and make special entry 0
 689&nbsp;                    current dir
 690&nbsp;        $ cd -r 1   Go to history entry 1 and put it on special entry 0
 691&nbsp;        $ cd -r     Go to history entry 0 and put it on special entry 0
 692&nbsp;
 693&nbsp;
 694&nbsp;    Alternative suggested directories:
 695&nbsp;
 696&nbsp;    If a directory is not found, then CD will suggest any
 697&nbsp;    possibilities. These are directories starting with the same letters
 698&nbsp;    and if any are found they are listed prefixed with -a&#60;n&#62;
 699&nbsp;    where &#60;n&#62; is a number. It's possible to go to the directory
 700&nbsp;    by entering cd -a&#60;n&#62; on the command line.
 701&nbsp;
 702&nbsp;        Use cd -d or -D to change default cd action. cd -H will show
 703&nbsp;        current action.
 704&nbsp;
 705&nbsp;        The history entries (0-n) are stored in the environment variables
 706&nbsp;        CD[0] - CD[n]
 707&nbsp;        Similarly the special directories S0 - 9 are in the environment
 708&nbsp;        variable CDS[0] - CDS[9]
 709&nbsp;        and may be accessed from the command line, for example:
 710&nbsp;        
 711&nbsp;            ls -l ${CDS[3]}
 712&nbsp;            cat ${CD[8]}/file.txt
 713&nbsp;
 714&nbsp;        The default pathname for the -f and -u commands is ~
 715&nbsp;        The default filename for the -f and -u commands is cdfile
 716&nbsp;
 717&nbsp;
 718&nbsp;Configuration
 719&nbsp;=============
 720&nbsp;
 721&nbsp;    The following environment variables can be set:
 722&nbsp;    
 723&nbsp;        CDL_PROMPTLEN  - Set to the length of prompt you require.
 724&nbsp;            Prompt string is set to the right characters of the current
 725&nbsp;            directory. If not set, then prompt is left unchanged. Note
 726&nbsp;            that this is the number of characters that the directory is
 727&nbsp;            shortened to, not the total characters in the prompt.
 728&nbsp;
 729&nbsp;            CDL_PROMPT_PRE - Set to the string to prefix the prompt.
 730&nbsp;                Default is:
 731&nbsp;                    non-root:  "\\[\\e[01;34m\\]"  (sets colour to blue).
 732&nbsp;                    root:      "\\[\\e[01;31m\\]"  (sets colour to red).
 733&nbsp;
 734&nbsp;            CDL_PROMPT_POST    - Set to the string to suffix the prompt.
 735&nbsp;                Default is:
 736&nbsp;                    non-root:  "\\[\\e[00m\\]$"
 737&nbsp;                               (resets colour and displays $).
 738&nbsp;                    root:      "\\[\\e[00m\\]#"
 739&nbsp;                               (resets colour and displays #).
 740&nbsp;
 741&nbsp;        Note:
 742&nbsp;            CDL_PROMPT_PRE &#38; _POST only t
 743&nbsp;
 744&nbsp;        CDPath - Set the default path for the -f &#38; -u options.
 745&nbsp;                 Default is home directory
 746&nbsp;        CDFile - Set the default filename for the -f &#38; -u options.
 747&nbsp;                 Default is cdfile
 748&nbsp;
 749&nbsp;
 750&nbsp;    There are three variables defined in the file cdll which control the
 751&nbsp;    number of entries stored or displayed. They are in the section labeled
 752&nbsp;    'Initialisation here' towards the end of the file.
 753&nbsp;
 754&nbsp;        cd_maxhistory       - The number of history entries stored.
 755&nbsp;                              Default is 50.
 756&nbsp;        cd_maxspecial       - The number of special entries allowed.
 757&nbsp;                              Default is 9.
 758&nbsp;        cd_histcount        - The number of history and special entries
 759&nbsp;                              displayed. Default is 9.
 760&nbsp;
 761&nbsp;    Note that cd_maxspecial should be &#62;= cd_histcount to avoid displaying
 762&nbsp;    special entries that can't be set.
 763&nbsp;
 764&nbsp;
 765&nbsp;Version: 1.2.1 Date: 24-MAY-2003
 766&nbsp;
 767&nbsp;DOCUMENTATION</PRE
></TD
></TR
></TABLE
><HR></DIV
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="SOUNDCARDON"
></A
><P
><B
>Example A-34. A soundcard setup script</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#!/bin/bash
   2&nbsp;# soundcard-on.sh
   3&nbsp;
   4&nbsp;#  Script author: Mkarcher
   5&nbsp;#  http://www.thinkwiki.org/wiki  ...
   6&nbsp;#  /Script_for_configuring_the_CS4239_sound_chip_in_PnP_mode
   7&nbsp;#  ABS Guide author made minor changes and added comments.
   8&nbsp;#  Couldn't contact script author to ask for permission to use, but ...
   9&nbsp;#+ the script was released under the FDL,
  10&nbsp;#+ so its use here should be both legal and ethical.
  11&nbsp;
  12&nbsp;#  Sound-via-pnp-script for Thinkpad 600E
  13&nbsp;#+ and possibly other computers with onboard CS4239/CS4610
  14&nbsp;#+ that do not work with the PCI driver
  15&nbsp;#+ and are not recognized by the PnP code of snd-cs4236.
  16&nbsp;#  Also for some 770-series Thinkpads, such as the 770x.
  17&nbsp;#  Run as root user, of course.
  18&nbsp;#
  19&nbsp;#  These are old and very obsolete laptop computers,
  20&nbsp;#+ but this particular script is very instructive,
  21&nbsp;#+ as it shows how to set up and hack device files.
  22&nbsp;
  23&nbsp;
  24&nbsp;
  25&nbsp;#  Search for sound card pnp device:
  26&nbsp;
  27&nbsp;for dev in /sys/bus/pnp/devices/*
  28&nbsp;do
  29&nbsp;  grep CSC0100 $dev/id &#62; /dev/null &#38;&#38; WSSDEV=$dev
  30&nbsp;  grep CSC0110 $dev/id &#62; /dev/null &#38;&#38; CTLDEV=$dev
  31&nbsp;done
  32&nbsp;# On 770x:
  33&nbsp;# WSSDEV = /sys/bus/pnp/devices/00:07
  34&nbsp;# CTLDEV = /sys/bus/pnp/devices/00:06
  35&nbsp;# These are symbolic links to /sys/devices/pnp0/ ...
  36&nbsp;
  37&nbsp;
  38&nbsp;#  Activate devices:
  39&nbsp;#  Thinkpad boots with devices disabled unless "fast boot" is turned off
  40&nbsp;#+ (in BIOS).
  41&nbsp;
  42&nbsp;echo activate &#62; $WSSDEV/resources
  43&nbsp;echo activate &#62; $CTLDEV/resources
  44&nbsp;
  45&nbsp;
  46&nbsp;# Parse resource settings.
  47&nbsp;
  48&nbsp;{ read # Discard "state = active" (see below).
  49&nbsp;  read bla port1
  50&nbsp;  read bla port2
  51&nbsp;  read bla port3
  52&nbsp;  read bla irq
  53&nbsp;  read bla dma1
  54&nbsp;  read bla dma2
  55&nbsp; # The "bla's" are labels in the first field: "io," "state," etc.
  56&nbsp; # These are discarded.
  57&nbsp;
  58&nbsp; #  Hack: with PnPBIOS: ports are: port1: WSS, port2:
  59&nbsp; #+ OPL, port3: sb (unneeded)
  60&nbsp; #       with ACPI-PnP:ports are: port1: OPL, port2: sb, port3: WSS
  61&nbsp; #  (ACPI bios seems to be wrong here, the PnP-card-code in snd-cs4236.c
  62&nbsp; #+  uses the PnPBIOS port order)
  63&nbsp; #  Detect port order using the fixed OPL port as reference.
  64&nbsp;  if [ ${port2%%-*} = 0x388 ]
  65&nbsp; #            ^^^^  Strip out everything following hyphen in port address.
  66&nbsp; #                  So, if port1 is 0x530-0x537
  67&nbsp; #+                 we're left with 0x530 -- the start address of the port.
  68&nbsp; then
  69&nbsp;   # PnPBIOS: usual order
  70&nbsp;   port=${port1%%-*}
  71&nbsp;   oplport=${port2%%-*}
  72&nbsp; else
  73&nbsp;   # ACPI: mixed-up order
  74&nbsp;   port=${port3%%-*}
  75&nbsp;   oplport=${port1%%-*}
  76&nbsp; fi
  77&nbsp; } &#60; $WSSDEV/resources
  78&nbsp;# To see what's going on here:
  79&nbsp;# ---------------------------
  80&nbsp;#   cat /sys/devices/pnp0/00:07/resources
  81&nbsp;#
  82&nbsp;#   state = active
  83&nbsp;#   io 0x530-0x537
  84&nbsp;#   io 0x388-0x38b
  85&nbsp;#   io 0x220-0x233
  86&nbsp;#   irq 5
  87&nbsp;#   dma 1
  88&nbsp;#   dma 0
  89&nbsp;#   ^^^   "bla" labels in first field (discarded). 
  90&nbsp;
  91&nbsp;
  92&nbsp;{ read # Discard first line, as above.
  93&nbsp;  read bla port1
  94&nbsp;  cport=${port1%%-*}
  95&nbsp;  #            ^^^^
  96&nbsp;  # Just want _start_ address of port.
  97&nbsp;} &#60; $CTLDEV/resources
  98&nbsp;
  99&nbsp;
 100&nbsp;# Load the module:
 101&nbsp;
 102&nbsp;modprobe --ignore-install snd-cs4236 port=$port cport=$cport\
 103&nbsp;fm_port=$oplport irq=$irq dma1=$dma1 dma2=$dma2 isapnp=0 index=0
 104&nbsp;# See the modprobe manpage.
 105&nbsp;
 106&nbsp;exit $?</PRE
></TD
></TR
></TABLE
><HR></DIV
><P
><A
NAME="FINDSPLIT0"
></A
></P
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="FINDSPLIT"
></A
><P
><B
>Example A-35. Locating split paragraphs in a text file</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#!/bin/bash
   2&nbsp;# find-splitpara.sh
   3&nbsp;#  Finds split paragraphs in a text file,
   4&nbsp;#+ and tags the line numbers.
   5&nbsp;
   6&nbsp;
   7&nbsp;ARGCOUNT=1       # Expect one arg.
   8&nbsp;OFF=0            # Flag states.
   9&nbsp;ON=1
  10&nbsp;E_WRONGARGS=85
  11&nbsp;
  12&nbsp;file="$1"        # Target filename.
  13&nbsp;lineno=1         # Line number. Start at 1.
  14&nbsp;Flag=$OFF        # Blank line flag.
  15&nbsp;
  16&nbsp;if [ $# -ne "$ARGCOUNT" ]
  17&nbsp;then
  18&nbsp;  echo "Usage: `basename $0` FILENAME"
  19&nbsp;  exit $E_WRONGARGS
  20&nbsp;fi  
  21&nbsp;
  22&nbsp;file_read ()     # Scan file for pattern, then print line.
  23&nbsp;{
  24&nbsp;while read line
  25&nbsp;do
  26&nbsp;
  27&nbsp;  if [[ "$line" =~ ^[a-z] &#38;&#38; $Flag -eq $ON ]]
  28&nbsp;     then  # Line begins with lowercase character, following blank line.
  29&nbsp;     echo -n "$lineno::   "
  30&nbsp;     echo "$line"
  31&nbsp;  fi
  32&nbsp;
  33&nbsp;
  34&nbsp;  if [[ "$line" =~ ^$ ]]
  35&nbsp;     then       #  If blank line,
  36&nbsp;     Flag=$ON   #+ set flag.
  37&nbsp;  else
  38&nbsp;     Flag=$OFF
  39&nbsp;  fi
  40&nbsp;
  41&nbsp;  ((lineno++))
  42&nbsp;
  43&nbsp;done
  44&nbsp;} &#60; $file  # Redirect file into function's stdin.
  45&nbsp;
  46&nbsp;file_read
  47&nbsp;
  48&nbsp;
  49&nbsp;exit $?
  50&nbsp;
  51&nbsp;
  52&nbsp;# ----------------------------------------------------------------
  53&nbsp;This is line one of an example paragraph, bla, bla, bla.
  54&nbsp;This is line two, and line three should follow on next line, but
  55&nbsp;
  56&nbsp;there is a blank line separating the two parts of the paragraph.
  57&nbsp;# ----------------------------------------------------------------
  58&nbsp;
  59&nbsp;Running this script on a file containing the above paragraph
  60&nbsp;yields:
  61&nbsp;
  62&nbsp;4::   there is a blank line separating the two parts of the paragraph.
  63&nbsp;
  64&nbsp;
  65&nbsp;There will be additional output for all the other split paragraphs
  66&nbsp;in the target file.</PRE
></TD
></TR
></TABLE
><HR></DIV
><P
><A
NAME="INSERTIONSORT0"
></A
></P
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="INSERTIONSORT"
></A
><P
><B
>Example A-36. Insertion sort</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#!/bin/bash
   2&nbsp;# insertion-sort.bash: Insertion sort implementation in Bash
   3&nbsp;#                      Heavy use of Bash array features:
   4&nbsp;#+                     (string) slicing, merging, etc
   5&nbsp;# URL: http://www.lugmen.org.ar/~jjo/jjotip/insertion-sort.bash.d
   6&nbsp;#+          /insertion-sort.bash.sh
   7&nbsp;#
   8&nbsp;# Author: JuanJo Ciarlante &#60;jjo@irrigacion.gov.ar&#62;
   9&nbsp;# Lightly reformatted by ABS Guide author.
  10&nbsp;# License: GPLv2
  11&nbsp;# Used in ABS Guide with author's permission (thanks!).
  12&nbsp;#
  13&nbsp;# Test with:   ./insertion-sort.bash -t
  14&nbsp;# Or:          bash insertion-sort.bash -t
  15&nbsp;# The following *doesn't* work:
  16&nbsp;#              sh insertion-sort.bash -t
  17&nbsp;#  Why not? Hint: which Bash-specific features are disabled
  18&nbsp;#+ when running a script by 'sh script.sh'?
  19&nbsp;#
  20&nbsp;: ${DEBUG:=0}  # Debug, override with:  DEBUG=1 ./scriptname . . .
  21&nbsp;# Parameter substitution -- set DEBUG to 0 if not previously set.
  22&nbsp;
  23&nbsp;# Global array: "list"
  24&nbsp;typeset -a list
  25&nbsp;# Load whitespace-separated numbers from stdin.
  26&nbsp;if [ "$1" = "-t" ]; then
  27&nbsp;DEBUG=1
  28&nbsp;        read -a list &#60; &#60;( od -Ad -w24 -t u2 /dev/urandom ) # Random list.
  29&nbsp;#                    ^ ^  process substition
  30&nbsp;else
  31&nbsp;        read -a list
  32&nbsp;fi
  33&nbsp;numelem=${#list[*]}
  34&nbsp;
  35&nbsp;#  Shows the list, marking the element whose index is $1
  36&nbsp;#+ by surrounding it with the two chars passed as $2.
  37&nbsp;#  Whole line prefixed with $3.
  38&nbsp;showlist()
  39&nbsp;  {
  40&nbsp;  echo "$3"${list[@]:0:$1} ${2:0:1}${list[$1]}${2:1:1} ${list[@]:$1+1};
  41&nbsp;  }
  42&nbsp;
  43&nbsp;# Loop _pivot_ -- from second element to end of list.
  44&nbsp;for(( i=1; i&#60;numelem; i++ )) do
  45&nbsp;        ((DEBUG))&#38;&#38;showlist i "[]" " "
  46&nbsp;        # From current _pivot_, back to first element.
  47&nbsp;        for(( j=i; j; j-- )) do
  48&nbsp;                # Search for the 1st elem. less than current "pivot" . . .
  49&nbsp;                [[ "${list[j-1]}" -le "${list[i]}" ]] &#38;&#38; break
  50&nbsp;        done
  51&nbsp;	(( i==j )) &#38;&#38; continue ## No insertion was needed for this element.
  52&nbsp;	# . . . Move list[i] (pivot) to the left of list[j]:
  53&nbsp;        list=(${list[@]:0:j} ${list[i]} ${list[j]}\
  54&nbsp;	#         {0,j-1}        {i}       {j}
  55&nbsp;              ${list[@]:j+1:i-(j+1)} ${list[@]:i+1})
  56&nbsp;	#         {j+1,i-1}              {i+1,last}
  57&nbsp;	((DEBUG))&#38;&#38;showlist j "&#60;&#62;" "*"
  58&nbsp;done
  59&nbsp;
  60&nbsp;
  61&nbsp;echo
  62&nbsp;echo  "------"
  63&nbsp;echo $'Result:\n'${list[@]}
  64&nbsp;
  65&nbsp;exit $?</PRE
></TD
></TR
></TABLE
><HR></DIV
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="STDDEV"
></A
><P
><B
>Example A-37. Standard Deviation</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#!/bin/bash
   2&nbsp;# sd.sh: Standard Deviation
   3&nbsp;
   4&nbsp;#  The Standard Deviation indicates how consistent a set of data is.
   5&nbsp;#  It shows to what extent the individual data points deviate from the
   6&nbsp;#+ arithmetic mean, i.e., how much they "bounce around" (or cluster).
   7&nbsp;#  It is essentially the average deviation-distance of the
   8&nbsp;#+ data points from the mean.
   9&nbsp;
  10&nbsp;# =========================================================== #
  11&nbsp;#    To calculate the Standard Deviation:
  12&nbsp;#
  13&nbsp;# 1  Find the arithmetic mean (average) of all the data points.
  14&nbsp;# 2  Subtract each data point from the arithmetic mean,
  15&nbsp;#    and square that difference.
  16&nbsp;# 3  Add all of the individual difference-squares in # 2.
  17&nbsp;# 4  Divide the sum in # 3 by the number of data points.
  18&nbsp;#    This is known as the "variance."
  19&nbsp;# 5  The square root of # 4 gives the Standard Deviation.
  20&nbsp;# =========================================================== #
  21&nbsp;
  22&nbsp;count=0         # Number of data points; global.
  23&nbsp;SC=9            # Scale to be used by bc. Nine decimal places.
  24&nbsp;E_DATAFILE=90   # Data file error.
  25&nbsp;
  26&nbsp;# ----------------- Set data file ---------------------
  27&nbsp;if [ ! -z "$1" ]  # Specify filename as cmd-line arg?
  28&nbsp;then
  29&nbsp;  datafile="$1" #  ASCII text file,
  30&nbsp;else            #+ one (numerical) data point per line!
  31&nbsp;  datafile=sample.dat
  32&nbsp;fi              #  See example data file, below.
  33&nbsp;
  34&nbsp;if [ ! -e "$datafile" ]
  35&nbsp;then
  36&nbsp;  echo "\""$datafile"\" does not exist!"
  37&nbsp;  exit $E_DATAFILE
  38&nbsp;fi
  39&nbsp;# -----------------------------------------------------
  40&nbsp;
  41&nbsp;
  42&nbsp;arith_mean ()
  43&nbsp;{
  44&nbsp;  local rt=0         # Running total.
  45&nbsp;  local am=0         # Arithmetic mean.
  46&nbsp;  local ct=0         # Number of data points.
  47&nbsp;
  48&nbsp;  while read value   # Read one data point at a time.
  49&nbsp;  do
  50&nbsp;    rt=$(echo "scale=$SC; $rt + $value" | bc)
  51&nbsp;    (( ct++ ))
  52&nbsp;  done
  53&nbsp;
  54&nbsp;  am=$(echo "scale=$SC; $rt / $ct" | bc)
  55&nbsp;
  56&nbsp;  echo $am; return $ct   # This function "returns" TWO values!
  57&nbsp;  #  Caution: This little trick will not work if $ct &#62; 255!
  58&nbsp;  #  To handle a larger number of data points,
  59&nbsp;  #+ simply comment out the "return $ct" above.
  60&nbsp;} &#60;"$datafile"   # Feed in data file.
  61&nbsp;
  62&nbsp;sd ()
  63&nbsp;{
  64&nbsp;  mean1=$1  # Arithmetic mean (passed to function).
  65&nbsp;  n=$2      # How many data points.
  66&nbsp;  sum2=0    # Sum of squared differences ("variance").
  67&nbsp;  avg2=0    # Average of $sum2.
  68&nbsp;  sdev=0    # Standard Deviation.
  69&nbsp;
  70&nbsp;  while read value   # Read one line at a time.
  71&nbsp;  do
  72&nbsp;    diff=$(echo "scale=$SC; $mean1 - $value" | bc)
  73&nbsp;    # Difference between arith. mean and data point.
  74&nbsp;    dif2=$(echo "scale=$SC; $diff * $diff" | bc) # Squared.
  75&nbsp;    sum2=$(echo "scale=$SC; $sum2 + $dif2" | bc) # Sum of squares.
  76&nbsp;  done
  77&nbsp;
  78&nbsp;    avg2=$(echo "scale=$SC; $sum2 / $n" | bc)  # Avg. of sum of squares.
  79&nbsp;    sdev=$(echo "scale=$SC; sqrt($avg2)" | bc) # Square root =
  80&nbsp;    echo $sdev                                 # Standard Deviation.
  81&nbsp;
  82&nbsp;} &#60;"$datafile"   # Rewinds data file.
  83&nbsp;
  84&nbsp;
  85&nbsp;# ======================================================= #
  86&nbsp;mean=$(arith_mean); count=$?   # Two returns from function!
  87&nbsp;std_dev=$(sd $mean $count)
  88&nbsp;
  89&nbsp;echo
  90&nbsp;echo "Number of data points in \""$datafile"\" = $count"
  91&nbsp;echo "Arithmetic mean (average) = $mean"
  92&nbsp;echo "Standard Deviation = $std_dev"
  93&nbsp;echo
  94&nbsp;# ======================================================= #
  95&nbsp;
  96&nbsp;exit
  97&nbsp;
  98&nbsp;#  This script could stand some drastic streamlining,
  99&nbsp;#+ but not at the cost of reduced legibility, please.
 100&nbsp;
 101&nbsp;
 102&nbsp;# ++++++++++++++++++++++++++++++++++++++++ #
 103&nbsp;# A sample data file (sample1.dat):
 104&nbsp;
 105&nbsp;# 18.35
 106&nbsp;# 19.0
 107&nbsp;# 18.88
 108&nbsp;# 18.91
 109&nbsp;# 18.64
 110&nbsp;
 111&nbsp;
 112&nbsp;# $ sh sd.sh sample1.dat
 113&nbsp;
 114&nbsp;# Number of data points in "sample1.dat" = 5
 115&nbsp;# Arithmetic mean (average) = 18.756000000
 116&nbsp;# Standard Deviation = .235338054
 117&nbsp;# ++++++++++++++++++++++++++++++++++++++++ #</PRE
></TD
></TR
></TABLE
><HR></DIV
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="PADSW"
></A
><P
><B
>Example A-38. A <I
CLASS="FIRSTTERM"
>pad</I
> file generator for shareware
        authors</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#!/bin/bash
   2&nbsp;# pad.sh
   3&nbsp;
   4&nbsp;#######################################################
   5&nbsp;#               PAD (xml) file creator
   6&nbsp;#+ Written by Mendel Cooper &#60;thegrendel.abs@gmail.com&#62;.
   7&nbsp;#+ Released to the Public Domain.
   8&nbsp;#
   9&nbsp;#  Generates a "PAD" descriptor file for shareware
  10&nbsp;#+ packages, according to the specifications
  11&nbsp;#+ of the ASP.
  12&nbsp;#  http://www.asp-shareware.org/pad
  13&nbsp;#######################################################
  14&nbsp;
  15&nbsp;
  16&nbsp;# Accepts (optional) save filename as a command-line argument.
  17&nbsp;if [ -n "$1" ]
  18&nbsp;then
  19&nbsp;  savefile=$1
  20&nbsp;else
  21&nbsp;  savefile=save_file.xml               # Default save_file name.
  22&nbsp;fi  
  23&nbsp;
  24&nbsp;
  25&nbsp;# ===== PAD file headers =====
  26&nbsp;HDR1="&#60;?xml version=\"1.0\" encoding=\"Windows-1252\" ?&#62;"
  27&nbsp;HDR2="&#60;XML_DIZ_INFO&#62;"
  28&nbsp;HDR3="&#60;MASTER_PAD_VERSION_INFO&#62;"
  29&nbsp;HDR4="\t&#60;MASTER_PAD_VERSION&#62;1.15&#60;/MASTER_PAD_VERSION&#62;"
  30&nbsp;HDR5="\t&#60;MASTER_PAD_INFO&#62;Portable Application Description, or PAD
  31&nbsp;for short, is a data set that is used by shareware authors to
  32&nbsp;disseminate information to anyone interested in their software products.
  33&nbsp;To find out more go to http://www.asp-shareware.org/pad&#60;/MASTER_PAD_INFO&#62;"
  34&nbsp;HDR6="&#60;/MASTER_PAD_VERSION_INFO&#62;"
  35&nbsp;# ============================
  36&nbsp;
  37&nbsp;
  38&nbsp;fill_in ()
  39&nbsp;{
  40&nbsp;  if [ -z "$2" ]
  41&nbsp;  then
  42&nbsp;    echo -n "$1? "     # Get user input.
  43&nbsp;  else
  44&nbsp;    echo -n "$1 $2? "  # Additional query?
  45&nbsp;  fi  
  46&nbsp;
  47&nbsp;  read var             # May paste to fill in field.
  48&nbsp;                       # This shows how flexible "read" can be.
  49&nbsp;
  50&nbsp;  if [ -z "$var" ]
  51&nbsp;  then
  52&nbsp;    echo -e "\t\t&#60;$1 /&#62;" &#62;&#62;$savefile    # Indent with 2 tabs.
  53&nbsp;    return
  54&nbsp;  else
  55&nbsp;    echo -e "\t\t&#60;$1&#62;$var&#60;/$1&#62;" &#62;&#62;$savefile
  56&nbsp;    return ${#var}     # Return length of input string.
  57&nbsp;  fi
  58&nbsp;}    
  59&nbsp;
  60&nbsp;check_field_length ()  # Check length of program description fields.
  61&nbsp;{
  62&nbsp;  # $1 = maximum field length
  63&nbsp;  # $2 = actual field length
  64&nbsp;  if [ "$2" -gt "$1" ]
  65&nbsp;  then
  66&nbsp;    echo "Warning: Maximum field length of $1 characters exceeded!"
  67&nbsp;  fi
  68&nbsp;}  
  69&nbsp;
  70&nbsp;clear                  # Clear screen.
  71&nbsp;echo "PAD File Creator"
  72&nbsp;echo "--- ---- -------"
  73&nbsp;echo
  74&nbsp;
  75&nbsp;# Write File Headers to file.
  76&nbsp;echo $HDR1 &#62;$savefile
  77&nbsp;echo $HDR2 &#62;&#62;$savefile
  78&nbsp;echo $HDR3 &#62;&#62;$savefile
  79&nbsp;echo -e $HDR4 &#62;&#62;$savefile
  80&nbsp;echo -e $HDR5 &#62;&#62;$savefile
  81&nbsp;echo $HDR6 &#62;&#62;$savefile
  82&nbsp;
  83&nbsp;
  84&nbsp;# Company_Info
  85&nbsp;echo "COMPANY INFO"
  86&nbsp;CO_HDR="Company_Info"
  87&nbsp;echo "&#60;$CO_HDR&#62;" &#62;&#62;$savefile
  88&nbsp;
  89&nbsp;fill_in Company_Name
  90&nbsp;fill_in Address_1
  91&nbsp;fill_in Address_2
  92&nbsp;fill_in City_Town 
  93&nbsp;fill_in State_Province
  94&nbsp;fill_in Zip_Postal_Code
  95&nbsp;fill_in Country
  96&nbsp;
  97&nbsp;# If applicable:
  98&nbsp;# fill_in ASP_Member "[Y/N]"
  99&nbsp;# fill_in ASP_Member_Number
 100&nbsp;# fill_in ESC_Member "[Y/N]"
 101&nbsp;
 102&nbsp;fill_in Company_WebSite_URL
 103&nbsp;
 104&nbsp;clear   # Clear screen between sections.
 105&nbsp;
 106&nbsp;   # Contact_Info
 107&nbsp;echo "CONTACT INFO"
 108&nbsp;CONTACT_HDR="Contact_Info"
 109&nbsp;echo "&#60;$CONTACT_HDR&#62;" &#62;&#62;$savefile
 110&nbsp;fill_in Author_First_Name
 111&nbsp;fill_in Author_Last_Name
 112&nbsp;fill_in Author_Email
 113&nbsp;fill_in Contact_First_Name
 114&nbsp;fill_in Contact_Last_Name
 115&nbsp;fill_in Contact_Email
 116&nbsp;echo -e "\t&#60;/$CONTACT_HDR&#62;" &#62;&#62;$savefile
 117&nbsp;   # END Contact_Info
 118&nbsp;
 119&nbsp;clear
 120&nbsp;
 121&nbsp;   # Support_Info
 122&nbsp;echo "SUPPORT INFO"
 123&nbsp;SUPPORT_HDR="Support_Info"
 124&nbsp;echo "&#60;$SUPPORT_HDR&#62;" &#62;&#62;$savefile
 125&nbsp;fill_in Sales_Email
 126&nbsp;fill_in Support_Email
 127&nbsp;fill_in General_Email
 128&nbsp;fill_in Sales_Phone
 129&nbsp;fill_in Support_Phone
 130&nbsp;fill_in General_Phone
 131&nbsp;fill_in Fax_Phone
 132&nbsp;echo -e "\t&#60;/$SUPPORT_HDR&#62;" &#62;&#62;$savefile
 133&nbsp;   # END Support_Info
 134&nbsp;
 135&nbsp;echo "&#60;/$CO_HDR&#62;" &#62;&#62;$savefile
 136&nbsp;# END Company_Info
 137&nbsp;
 138&nbsp;clear
 139&nbsp;
 140&nbsp;# Program_Info 
 141&nbsp;echo "PROGRAM INFO"
 142&nbsp;PROGRAM_HDR="Program_Info"
 143&nbsp;echo "&#60;$PROGRAM_HDR&#62;" &#62;&#62;$savefile
 144&nbsp;fill_in Program_Name
 145&nbsp;fill_in Program_Version
 146&nbsp;fill_in Program_Release_Month
 147&nbsp;fill_in Program_Release_Day
 148&nbsp;fill_in Program_Release_Year
 149&nbsp;fill_in Program_Cost_Dollars
 150&nbsp;fill_in Program_Cost_Other
 151&nbsp;fill_in Program_Type "[Shareware/Freeware/GPL]"
 152&nbsp;fill_in Program_Release_Status "[Beta, Major Upgrade, etc.]"
 153&nbsp;fill_in Program_Install_Support
 154&nbsp;fill_in Program_OS_Support "[Win9x/Win2k/Linux/etc.]"
 155&nbsp;fill_in Program_Language "[English/Spanish/etc.]"
 156&nbsp;
 157&nbsp;echo; echo
 158&nbsp;
 159&nbsp;  # File_Info 
 160&nbsp;echo "FILE INFO"
 161&nbsp;FILEINFO_HDR="File_Info"
 162&nbsp;echo "&#60;$FILEINFO_HDR&#62;" &#62;&#62;$savefile
 163&nbsp;fill_in Filename_Versioned
 164&nbsp;fill_in Filename_Previous
 165&nbsp;fill_in Filename_Generic
 166&nbsp;fill_in Filename_Long
 167&nbsp;fill_in File_Size_Bytes
 168&nbsp;fill_in File_Size_K
 169&nbsp;fill_in File_Size_MB
 170&nbsp;echo -e "\t&#60;/$FILEINFO_HDR&#62;" &#62;&#62;$savefile
 171&nbsp;  # END File_Info 
 172&nbsp;
 173&nbsp;clear
 174&nbsp;
 175&nbsp;  # Expire_Info 
 176&nbsp;echo "EXPIRE INFO"
 177&nbsp;EXPIRE_HDR="Expire_Info"
 178&nbsp;echo "&#60;$EXPIRE_HDR&#62;" &#62;&#62;$savefile
 179&nbsp;fill_in Has_Expire_Info "Y/N"
 180&nbsp;fill_in Expire_Count
 181&nbsp;fill_in Expire_Based_On
 182&nbsp;fill_in Expire_Other_Info
 183&nbsp;fill_in Expire_Month
 184&nbsp;fill_in Expire_Day
 185&nbsp;fill_in Expire_Year
 186&nbsp;echo -e "\t&#60;/$EXPIRE_HDR&#62;" &#62;&#62;$savefile
 187&nbsp;  # END Expire_Info 
 188&nbsp;
 189&nbsp;clear
 190&nbsp;
 191&nbsp;  # More Program_Info
 192&nbsp;echo "ADDITIONAL PROGRAM INFO"
 193&nbsp;fill_in Program_Change_Info
 194&nbsp;fill_in Program_Specific_Category
 195&nbsp;fill_in Program_Categories
 196&nbsp;fill_in Includes_JAVA_VM "[Y/N]"
 197&nbsp;fill_in Includes_VB_Runtime "[Y/N]"
 198&nbsp;fill_in Includes_DirectX "[Y/N]"
 199&nbsp;  # END More Program_Info
 200&nbsp;
 201&nbsp;echo "&#60;/$PROGRAM_HDR&#62;" &#62;&#62;$savefile
 202&nbsp;# END Program_Info 
 203&nbsp;
 204&nbsp;clear
 205&nbsp;
 206&nbsp;# Program Description
 207&nbsp;echo "PROGRAM DESCRIPTIONS"
 208&nbsp;PROGDESC_HDR="Program_Descriptions"
 209&nbsp;echo "&#60;$PROGDESC_HDR&#62;" &#62;&#62;$savefile
 210&nbsp;
 211&nbsp;LANG="English"
 212&nbsp;echo "&#60;$LANG&#62;" &#62;&#62;$savefile
 213&nbsp;
 214&nbsp;fill_in Keywords "[comma + space separated]"
 215&nbsp;echo
 216&nbsp;echo "45, 80, 250, 450, 2000 word program descriptions"
 217&nbsp;echo "(may cut and paste into field)"
 218&nbsp;#  It would be highly appropriate to compose the following
 219&nbsp;#+ "Char_Desc" fields with a text editor,
 220&nbsp;#+ then cut-and-paste the text into the answer fields.
 221&nbsp;echo
 222&nbsp;echo "              |---------------45 characters---------------|"
 223&nbsp;fill_in Char_Desc_45
 224&nbsp;check_field_length 45 "$?"
 225&nbsp;echo
 226&nbsp;fill_in Char_Desc_80
 227&nbsp;check_field_length 80 "$?"
 228&nbsp;
 229&nbsp;fill_in Char_Desc_250
 230&nbsp;check_field_length 250 "$?"
 231&nbsp;
 232&nbsp;fill_in Char_Desc_450
 233&nbsp;fill_in Char_Desc_2000
 234&nbsp;
 235&nbsp;echo "&#60;/$LANG&#62;" &#62;&#62;$savefile
 236&nbsp;echo "&#60;/$PROGDESC_HDR&#62;" &#62;&#62;$savefile
 237&nbsp;# END Program Description
 238&nbsp;
 239&nbsp;clear
 240&nbsp;echo "Done."; echo; echo
 241&nbsp;echo "Save file is:  \""$savefile"\""
 242&nbsp;
 243&nbsp;exit 0</PRE
></TD
></TR
></TABLE
><HR></DIV
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="MANED"
></A
><P
><B
>Example A-39. A <I
CLASS="FIRSTTERM"
>man page</I
> editor</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#!/bin/bash
   2&nbsp;# maned.sh
   3&nbsp;# A rudimentary man page editor
   4&nbsp;
   5&nbsp;# Version: 0.1 (Alpha, probably buggy)
   6&nbsp;# Author: Mendel Cooper &#60;thegrendel.abs@gmail.com&#62;
   7&nbsp;# Reldate: 16 June 2008
   8&nbsp;# License: GPL3
   9&nbsp;
  10&nbsp;
  11&nbsp;savefile=      # Global, used in multiple functions.
  12&nbsp;E_NOINPUT=90   # User input missing (error). May or may not be critical.
  13&nbsp;
  14&nbsp;# =========== Markup Tags ============ #
  15&nbsp;TopHeader=".TH"
  16&nbsp;NameHeader=".SH NAME"
  17&nbsp;SyntaxHeader=".SH SYNTAX"
  18&nbsp;SynopsisHeader=".SH SYNOPSIS"
  19&nbsp;InstallationHeader=".SH INSTALLATION"
  20&nbsp;DescHeader=".SH DESCRIPTION"
  21&nbsp;OptHeader=".SH OPTIONS"
  22&nbsp;FilesHeader=".SH FILES"
  23&nbsp;EnvHeader=".SH ENVIRONMENT"
  24&nbsp;AuthHeader=".SH AUTHOR"
  25&nbsp;BugsHeader=".SH BUGS"
  26&nbsp;SeeAlsoHeader=".SH SEE ALSO"
  27&nbsp;BOLD=".B"
  28&nbsp;# Add more tags, as needed.
  29&nbsp;# See groff docs for markup meanings.
  30&nbsp;# ==================================== #
  31&nbsp;
  32&nbsp;start ()
  33&nbsp;{
  34&nbsp;clear                  # Clear screen.
  35&nbsp;echo "ManEd"
  36&nbsp;echo "-----"
  37&nbsp;echo
  38&nbsp;echo "Simple man page creator"
  39&nbsp;echo "Author: Mendel Cooper"
  40&nbsp;echo "License: GPL3"
  41&nbsp;echo; echo; echo
  42&nbsp;}
  43&nbsp;
  44&nbsp;progname ()
  45&nbsp;{
  46&nbsp;  echo -n "Program name? "
  47&nbsp;  read name
  48&nbsp;
  49&nbsp;  echo -n "Manpage section? [Hit RETURN for default (\"1\") ]  "
  50&nbsp;  read section
  51&nbsp;  if [ -z "$section" ]
  52&nbsp;  then
  53&nbsp;    section=1   # Most man pages are in section 1.
  54&nbsp;  fi
  55&nbsp;
  56&nbsp;  if [ -n "$name" ]
  57&nbsp;  then
  58&nbsp;    savefile=""$name"."$section""       #  Filename suffix = section.
  59&nbsp;    echo -n "$1 " &#62;&#62;$savefile
  60&nbsp;    name1=$(echo "$name" | tr a-z A-Z)  #  Change to uppercase,
  61&nbsp;                                        #+ per man page convention.
  62&nbsp;    echo -n "$name1" &#62;&#62;$savefile
  63&nbsp;  else
  64&nbsp;    echo "Error! No input."             # Mandatory input.
  65&nbsp;    exit $E_NOINPUT                     # Critical!
  66&nbsp;    #  Exercise: The script-abort if no filename input is a bit clumsy.
  67&nbsp;    #            Rewrite this section so a default filename is used
  68&nbsp;    #+           if no input.
  69&nbsp;  fi
  70&nbsp;
  71&nbsp;  echo -n "  \"$section\""&#62;&#62;$savefile   # Append, always append.
  72&nbsp;
  73&nbsp;  echo -n "Version? "
  74&nbsp;  read ver
  75&nbsp;  echo -n " \"Version $ver \""&#62;&#62;$savefile
  76&nbsp;  echo &#62;&#62;$savefile
  77&nbsp;
  78&nbsp;  echo -n "Short description [0 - 5 words]? "
  79&nbsp;  read sdesc
  80&nbsp;  echo "$NameHeader"&#62;&#62;$savefile
  81&nbsp;  echo ""$BOLD" "$name""&#62;&#62;$savefile
  82&nbsp;  echo "\- "$sdesc""&#62;&#62;$savefile
  83&nbsp;
  84&nbsp;}
  85&nbsp;
  86&nbsp;fill_in ()
  87&nbsp;{ # This function more or less copied from "pad.sh" script.
  88&nbsp;  echo -n "$2? "       # Get user input.
  89&nbsp;  read var             # May paste (a single line only!) to fill in field.
  90&nbsp;
  91&nbsp;  if [ -n "$var" ]
  92&nbsp;  then
  93&nbsp;    echo "$1 " &#62;&#62;$savefile
  94&nbsp;    echo -n "$var" &#62;&#62;$savefile
  95&nbsp;  else                 # Don't append empty field to file.
  96&nbsp;    return $E_NOINPUT  # Not critical here.
  97&nbsp;  fi
  98&nbsp;
  99&nbsp;  echo &#62;&#62;$savefile
 100&nbsp;
 101&nbsp;}    
 102&nbsp;
 103&nbsp;
 104&nbsp;end ()
 105&nbsp;{
 106&nbsp;clear
 107&nbsp;echo -n "Would you like to view the saved man page (y/n)? "
 108&nbsp;read ans
 109&nbsp;if [ "$ans" = "n" -o "$ans" = "N" ]; then exit; fi
 110&nbsp;exec less "$savefile"  #  Exit script and hand off control to "less" ...
 111&nbsp;                       #+ ... which formats for viewing man page source.
 112&nbsp;}
 113&nbsp;
 114&nbsp;
 115&nbsp;# ---------------------------------------- #
 116&nbsp;start
 117&nbsp;progname "$TopHeader"
 118&nbsp;fill_in "$SynopsisHeader" "Synopsis"
 119&nbsp;fill_in "$DescHeader" "Long description"
 120&nbsp;# May paste in *single line* of text.
 121&nbsp;fill_in "$OptHeader" "Options"
 122&nbsp;fill_in "$FilesHeader" "Files"
 123&nbsp;fill_in "$AuthHeader" "Author"
 124&nbsp;fill_in "$BugsHeader" "Bugs"
 125&nbsp;fill_in "$SeeAlsoHeader" "See also"
 126&nbsp;# fill_in "$OtherHeader" ... as necessary.
 127&nbsp;end    # ... exit not needed.
 128&nbsp;# ---------------------------------------- #
 129&nbsp;
 130&nbsp;#  Note that the generated man page will usually
 131&nbsp;#+ require manual fine-tuning with a text editor.
 132&nbsp;#  However, it's a distinct improvement upon
 133&nbsp;#+ writing man source from scratch
 134&nbsp;#+ or even editing a blank man page template.
 135&nbsp;
 136&nbsp;#  The main deficiency of the script is that it permits
 137&nbsp;#+ pasting only a single text line into the input fields.
 138&nbsp;#  This may be a long, cobbled-together line, which groff
 139&nbsp;#  will automatically wrap and hyphenate.
 140&nbsp;#  However, if you want multiple (newline-separated) paragraphs,
 141&nbsp;#+ these must be inserted by manual text editing on the
 142&nbsp;#+ script-generated man page.
 143&nbsp;#  Exercise (difficult): Fix this!
 144&nbsp;
 145&nbsp;#  This script is not nearly as elaborate as the
 146&nbsp;#+ full-featured "manedit" package
 147&nbsp;#+ http://freshmeat.net/projects/manedit/
 148&nbsp;#+ but it's much easier to use.</PRE
></TD
></TR
></TABLE
><HR></DIV
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="PETALS"
></A
><P
><B
>Example A-40. Petals Around the Rose</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#!/bin/bash -i
   2&nbsp;# petals.sh
   3&nbsp;
   4&nbsp;#########################################################################
   5&nbsp;# Petals Around the Rose                                                #
   6&nbsp;#                                                                       #
   7&nbsp;# Version 0.1 Created by Serghey Rodin                                  #
   8&nbsp;# Version 0.2 Modded by ABS Guide Author                                #
   9&nbsp;#                                                                       #
  10&nbsp;# License: GPL3                                                         #
  11&nbsp;# Used in ABS Guide with permission.                                    #
  12&nbsp;# ##################################################################### #
  13&nbsp;
  14&nbsp;hits=0      # Correct guesses.
  15&nbsp;WIN=6       # Mastered the game.
  16&nbsp;ALMOST=5    # One short of mastery.
  17&nbsp;EXIT=exit   # Give up early?
  18&nbsp;
  19&nbsp;RANDOM=$$   # Seeds the random number generator from PID of script.
  20&nbsp;
  21&nbsp;
  22&nbsp;# Bones (ASCII graphics for dice)
  23&nbsp;bone1[1]="|         |"
  24&nbsp;bone1[2]="|       o |"
  25&nbsp;bone1[3]="|       o |"
  26&nbsp;bone1[4]="| o     o |"
  27&nbsp;bone1[5]="| o     o |"
  28&nbsp;bone1[6]="| o     o |"
  29&nbsp;bone2[1]="|    o    |"
  30&nbsp;bone2[2]="|         |"
  31&nbsp;bone2[3]="|    o    |"
  32&nbsp;bone2[4]="|         |"
  33&nbsp;bone2[5]="|    o    |"
  34&nbsp;bone2[6]="| o     o |"
  35&nbsp;bone3[1]="|         |"
  36&nbsp;bone3[2]="| o       |"
  37&nbsp;bone3[3]="| o       |"
  38&nbsp;bone3[4]="| o     o |"
  39&nbsp;bone3[5]="| o     o |"
  40&nbsp;bone3[6]="| o     o |"
  41&nbsp;bone="+---------+"
  42&nbsp;
  43&nbsp;
  44&nbsp;
  45&nbsp;# Functions
  46&nbsp;
  47&nbsp;instructions () {
  48&nbsp;
  49&nbsp;  clear
  50&nbsp;  echo -n "Do you need instructions? (y/n) "; read ans
  51&nbsp;  if [ "$ans" = "y" -o "$ans" = "Y" ]; then
  52&nbsp;    clear
  53&nbsp;    echo -e '\E[34;47m'  # Blue type.
  54&nbsp;
  55&nbsp;#  "cat document"
  56&nbsp;    cat &#60;&#60;INSTRUCTIONSZZZ
  57&nbsp;The name of the game is Petals Around the Rose,
  58&nbsp;and that name is significant.
  59&nbsp;Five dice will roll and you must guess the "answer" for each roll.
  60&nbsp;It will be zero or an even number.
  61&nbsp;After your guess, you will be told the answer for the roll, but . . .
  62&nbsp;that's ALL the information you will get.
  63&nbsp;
  64&nbsp;Six consecutive correct guesses admits you to the
  65&nbsp;Fellowship of the Rose.
  66&nbsp;INSTRUCTIONSZZZ
  67&nbsp;
  68&nbsp;    echo -e "\033[0m"    # Turn off blue.
  69&nbsp;    else clear
  70&nbsp;  fi
  71&nbsp;
  72&nbsp;}
  73&nbsp;
  74&nbsp;
  75&nbsp;fortune ()
  76&nbsp;{
  77&nbsp;  RANGE=7
  78&nbsp;  FLOOR=0
  79&nbsp;  number=0
  80&nbsp;  while [ "$number" -le $FLOOR ]
  81&nbsp;  do
  82&nbsp;    number=$RANDOM
  83&nbsp;    let "number %= $RANGE"   # 1 - 6.
  84&nbsp;  done
  85&nbsp;
  86&nbsp;  return $number
  87&nbsp;}
  88&nbsp;
  89&nbsp;
  90&nbsp;
  91&nbsp;throw () { # Calculate each individual die.
  92&nbsp;  fortune; B1=$?
  93&nbsp;  fortune; B2=$?
  94&nbsp;  fortune; B3=$?
  95&nbsp;  fortune; B4=$?
  96&nbsp;  fortune; B5=$?
  97&nbsp;
  98&nbsp;  calc () { # Function embedded within a function!
  99&nbsp;    case "$1" in
 100&nbsp;       3   ) rose=2;;
 101&nbsp;       5   ) rose=4;;
 102&nbsp;       *   ) rose=0;;
 103&nbsp;    esac    # Simplified algorithm.
 104&nbsp;            # Doesn't really get to the heart of the matter.
 105&nbsp;    return $rose
 106&nbsp;  }
 107&nbsp;
 108&nbsp;  answer=0
 109&nbsp;  calc "$B1"; answer=$(expr $answer + $(echo $?))
 110&nbsp;  calc "$B2"; answer=$(expr $answer + $(echo $?))
 111&nbsp;  calc "$B3"; answer=$(expr $answer + $(echo $?))
 112&nbsp;  calc "$B4"; answer=$(expr $answer + $(echo $?))
 113&nbsp;  calc "$B5"; answer=$(expr $answer + $(echo $?))
 114&nbsp;}
 115&nbsp;
 116&nbsp;
 117&nbsp;
 118&nbsp;game ()
 119&nbsp;{ # Generate graphic display of dice throw.
 120&nbsp;  throw
 121&nbsp;    echo -e "\033[1m"    # Bold.
 122&nbsp;  echo -e "\n"
 123&nbsp;  echo -e "$bone\t$bone\t$bone\t$bone\t$bone"
 124&nbsp;  echo -e \
 125&nbsp; "${bone1[$B1]}\t${bone1[$B2]}\t${bone1[$B3]}\t${bone1[$B4]}\t${bone1[$B5]}"
 126&nbsp;  echo -e \
 127&nbsp; "${bone2[$B1]}\t${bone2[$B2]}\t${bone2[$B3]}\t${bone2[$B4]}\t${bone2[$B5]}"
 128&nbsp;  echo -e \
 129&nbsp; "${bone3[$B1]}\t${bone3[$B2]}\t${bone3[$B3]}\t${bone3[$B4]}\t${bone3[$B5]}"
 130&nbsp;  echo -e "$bone\t$bone\t$bone\t$bone\t$bone"
 131&nbsp;  echo -e "\n\n\t\t"
 132&nbsp;    echo -e "\033[0m"    # Turn off bold.
 133&nbsp;  echo -n "There are how many petals around the rose? "
 134&nbsp;}
 135&nbsp;
 136&nbsp;
 137&nbsp;
 138&nbsp;# ============================================================== #
 139&nbsp;
 140&nbsp;instructions
 141&nbsp;
 142&nbsp;while [ "$petal" != "$EXIT" ]    # Main loop.
 143&nbsp;do
 144&nbsp;  game
 145&nbsp;  read petal
 146&nbsp;  echo "$petal" | grep [0-9] &#62;/dev/null  # Filter response for digit.
 147&nbsp;                                         # Otherwise just roll dice again.
 148&nbsp;  if [ "$?" -eq 0 ]   # If-loop #1.
 149&nbsp;  then
 150&nbsp;    if [ "$petal" == "$answer" ]; then    # If-loop #2.
 151&nbsp;    	echo -e "\nCorrect. There are $petal petals around the rose.\n"
 152&nbsp;        (( hits++ ))
 153&nbsp;
 154&nbsp;        if [ "$hits" -eq "$WIN" ]; then   # If-loop #3.
 155&nbsp;          echo -e '\E[31;47m'  # Red type.
 156&nbsp;          echo -e "\033[1m"    # Bold.
 157&nbsp;          echo "You have unraveled the mystery of the Rose Petals!"
 158&nbsp;          echo "Welcome to the Fellowship of the Rose!!!"
 159&nbsp;          echo "(You are herewith sworn to secrecy.)"; echo
 160&nbsp;          echo -e "\033[0m"    # Turn off red &#38; bold.
 161&nbsp;          break                # Exit!
 162&nbsp;        else echo "You have $hits correct so far."; echo
 163&nbsp;
 164&nbsp;        if [ "$hits" -eq "$ALMOST" ]; then
 165&nbsp;          echo "Just one more gets you to the heart of the mystery!"; echo
 166&nbsp;        fi
 167&nbsp;
 168&nbsp;      fi                                  # Close if-loop #3.
 169&nbsp;
 170&nbsp;    else
 171&nbsp;      echo -e "\nWrong. There are $answer petals around the rose.\n"
 172&nbsp;      hits=0   # Reset number of correct guesses.
 173&nbsp;    fi                                    # Close if-loop #2.
 174&nbsp;
 175&nbsp;    echo -n "Hit ENTER for the next roll, or type \"exit\" to end. "
 176&nbsp;    read
 177&nbsp;    if [ "$REPLY" = "$EXIT" ]; then exit
 178&nbsp;    fi
 179&nbsp;
 180&nbsp;  fi                  # Close if-loop #1.
 181&nbsp;
 182&nbsp;  clear
 183&nbsp;done                  # End of main (while) loop.
 184&nbsp;
 185&nbsp;###
 186&nbsp;
 187&nbsp;exit $?
 188&nbsp;
 189&nbsp;# Resources:
 190&nbsp;# ---------
 191&nbsp;# 1) http://en.wikipedia.org/wiki/Petals_Around_the_Rose
 192&nbsp;#    (Wikipedia entry.)
 193&nbsp;# 2) http://www.borrett.id.au/computing/petals-bg.htm
 194&nbsp;#    (How Bill Gates coped with the Petals Around the Rose challenge.)</PRE
></TD
></TR
></TABLE
><HR></DIV
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="QKY"
></A
><P
><B
>Example A-41. Quacky: a Perquackey-type word game</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#!/bin/bash
   2&nbsp;# qky.sh
   3&nbsp;
   4&nbsp;##############################################################
   5&nbsp;# QUACKEY: a somewhat simplified version of Perquackey [TM]. #
   6&nbsp;#                                                            #
   7&nbsp;# Author: Mendel Cooper  &#60;thegrendel.abs@gmail.com&#62;          #
   8&nbsp;# version 0.1.02      03 May, 2008                           #
   9&nbsp;# License: GPL3                                              #
  10&nbsp;##############################################################
  11&nbsp;
  12&nbsp;WLIST=/usr/share/dict/word.lst
  13&nbsp;#                     ^^^^^^^^  Word list file found here.
  14&nbsp;#  ASCII word list, one word per line, UNIX format.
  15&nbsp;#  A suggested list is the script author's "yawl" word list package.
  16&nbsp;#  http://bash.deta.in/yawl-0.3.2.tar.gz
  17&nbsp;#    or
  18&nbsp;#  http://ibiblio.org/pub/Linux/libs/yawl-0.3.2.tar.gz
  19&nbsp;
  20&nbsp;NONCONS=0     # Word not constructable from letter set.
  21&nbsp;CONS=1        # Constructable.
  22&nbsp;SUCCESS=0
  23&nbsp;NG=1
  24&nbsp;FAILURE=''
  25&nbsp;NULL=0        # Zero out value of letter (if found).
  26&nbsp;MINWLEN=3     # Minimum word length.
  27&nbsp;MAXCAT=5      # Maximum number of words in a given category.
  28&nbsp;PENALTY=200   # General-purpose penalty for unacceptable words.
  29&nbsp;total=
  30&nbsp;E_DUP=70      # Duplicate word error.
  31&nbsp;
  32&nbsp;TIMEOUT=10    # Time for word input.
  33&nbsp;
  34&nbsp;NVLET=10      # 10 letters for non-vulnerable.
  35&nbsp;VULET=13      # 13 letters for vulnerable (not yet implemented!).
  36&nbsp;
  37&nbsp;declare -a Words
  38&nbsp;declare -a Status
  39&nbsp;declare -a Score=( 0 0 0 0 0 0 0 0 0 0 0 )
  40&nbsp;
  41&nbsp;
  42&nbsp;letters=( a n s r t m l k p r b c i d s i d z e w u e t f
  43&nbsp;e y e r e f e g t g h h i t r s c i t i d i j a t a o l a
  44&nbsp;m n a n o v n w o s e l n o s p a q e e r a b r s a o d s
  45&nbsp;t g t i t l u e u v n e o x y m r k )
  46&nbsp;#  Letter distribution table shamelessly borrowed from "Wordy" game,
  47&nbsp;#+ ca. 1992, written by a certain fine fellow named Mendel Cooper.
  48&nbsp;
  49&nbsp;declare -a LS
  50&nbsp;
  51&nbsp;numelements=${#letters[@]}
  52&nbsp;randseed="$1"
  53&nbsp;
  54&nbsp;instructions ()
  55&nbsp;{
  56&nbsp;  clear
  57&nbsp;  echo "Welcome to QUACKEY, the anagramming word construction game."; echo
  58&nbsp;  echo -n "Do you need instructions? (y/n) "; read ans
  59&nbsp;
  60&nbsp;   if [ "$ans" = "y" -o "$ans" = "Y" ]; then
  61&nbsp;     clear
  62&nbsp;     echo -e '\E[31;47m'  # Red foreground. '\E[34;47m' for blue.
  63&nbsp;     cat &#60;&#60;INSTRUCTION1
  64&nbsp;
  65&nbsp;QUACKEY is a variant of Perquackey [TM].
  66&nbsp;The rules are the same, but the scoring is simplified
  67&nbsp;and plurals of previously played words are allowed.
  68&nbsp;"Vulnerable" play is not yet implemented,
  69&nbsp;but it is otherwise feature-complete.
  70&nbsp;
  71&nbsp;As the game begins, the player gets 10 letters.
  72&nbsp;The object is to construct valid dictionary words
  73&nbsp;of at least 3-letter length from the letterset.
  74&nbsp;Each word-length category
  75&nbsp;-- 3-letter, 4-letter, 5-letter, ... --
  76&nbsp;fills up with the fifth word entered,
  77&nbsp;and no further words in that category are accepted.
  78&nbsp;
  79&nbsp;The penalty for too-short (two-letter), duplicate, unconstructable,
  80&nbsp;and invalid (not in dictionary) words is -200. The same penalty applies
  81&nbsp;to attempts to enter a word in a filled-up category.
  82&nbsp;
  83&nbsp;INSTRUCTION1
  84&nbsp;
  85&nbsp;  echo -n "Hit ENTER for next page of instructions. "; read az1
  86&nbsp;
  87&nbsp;     cat &#60;&#60;INSTRUCTION2
  88&nbsp;
  89&nbsp;The scoring mostly corresponds to classic Perquackey:
  90&nbsp;The first 3-letter word scores    60, plus   10 for each additional one.
  91&nbsp;The first 4-letter word scores   120, plus   20 for each additional one.
  92&nbsp;The first 5-letter word scores   200, plus   50 for each additional one.
  93&nbsp;The first 6-letter word scores   300, plus  100 for each additional one.
  94&nbsp;The first 7-letter word scores   500, plus  150 for each additional one.
  95&nbsp;The first 8-letter word scores   750, plus  250 for each additional one.
  96&nbsp;The first 9-letter word scores  1000, plus  500 for each additional one.
  97&nbsp;The first 10-letter word scores 2000, plus 2000 for each additional one.
  98&nbsp;
  99&nbsp;Category completion bonuses are:
 100&nbsp;3-letter words   100
 101&nbsp;4-letter words   200
 102&nbsp;5-letter words   400
 103&nbsp;6-letter words   800
 104&nbsp;7-letter words  2000
 105&nbsp;8-letter words 10000
 106&nbsp;This is a simplification of the absurdly baroque Perquackey bonus
 107&nbsp;scoring system.
 108&nbsp;
 109&nbsp;INSTRUCTION2
 110&nbsp;
 111&nbsp;  echo -n "Hit ENTER for final page of instructions. "; read az1
 112&nbsp;
 113&nbsp;     cat &#60;&#60;INSTRUCTION3
 114&nbsp;
 115&nbsp;
 116&nbsp;Hitting just ENTER for a word entry ends the game.
 117&nbsp;
 118&nbsp;Individual word entry is timed to a maximum of 10 seconds.
 119&nbsp;*** Timing out on an entry ends the game. ***
 120&nbsp;Aside from that, the game is untimed.
 121&nbsp;
 122&nbsp;--------------------------------------------------
 123&nbsp;Game statistics are automatically saved to a file.
 124&nbsp;--------------------------------------------------
 125&nbsp;
 126&nbsp;For competitive ("duplicate") play, a previous letterset
 127&nbsp;may be duplicated by repeating the script's random seed,
 128&nbsp;command-line parameter \$1.
 129&nbsp;For example, "qky 7633" specifies the letterset 
 130&nbsp;c a d i f r h u s k ...
 131&nbsp;INSTRUCTION3
 132&nbsp;
 133&nbsp;  echo; echo -n "Hit ENTER to begin game. "; read az1
 134&nbsp;
 135&nbsp;       echo -e "\033[0m"    # Turn off red.
 136&nbsp;     else clear
 137&nbsp;  fi
 138&nbsp;
 139&nbsp;  clear
 140&nbsp;
 141&nbsp;}
 142&nbsp;
 143&nbsp;
 144&nbsp;
 145&nbsp;seed_random ()
 146&nbsp;{                         #  Seed random number generator.
 147&nbsp;  if [ -n "$randseed" ]   #  Can specify random seed.
 148&nbsp;  then                    #+ for play in competitive mode.
 149&nbsp;#   RANDOM="$randseed"
 150&nbsp;    echo "RANDOM seed set to "$randseed""
 151&nbsp;  else
 152&nbsp;    randseed="$$"         # Or get random seed from process ID.
 153&nbsp;    echo "RANDOM seed not specified, set to Process ID of script ($$)."
 154&nbsp;  fi
 155&nbsp;
 156&nbsp;  RANDOM="$randseed"
 157&nbsp;
 158&nbsp;  echo
 159&nbsp;}
 160&nbsp;
 161&nbsp;
 162&nbsp;get_letset ()
 163&nbsp;{
 164&nbsp;  element=0
 165&nbsp;  echo -n "Letterset:"
 166&nbsp;
 167&nbsp;  for lset in $(seq $NVLET)
 168&nbsp;  do  # Pick random letters to fill out letterset.
 169&nbsp;    LS[element]="${letters[$((RANDOM%numelements))]}"
 170&nbsp;    ((element++))
 171&nbsp;  done
 172&nbsp;
 173&nbsp;  echo
 174&nbsp;  echo "${LS[@]}"
 175&nbsp;
 176&nbsp;}
 177&nbsp;
 178&nbsp;
 179&nbsp;add_word ()
 180&nbsp;{
 181&nbsp;  wrd="$1"
 182&nbsp;  local idx=0
 183&nbsp;
 184&nbsp;  Status[0]=""
 185&nbsp;  Status[3]=""
 186&nbsp;  Status[4]=""
 187&nbsp;
 188&nbsp;  while [ "${Words[idx]}" != '' ]
 189&nbsp;  do
 190&nbsp;    if [ "${Words[idx]}" = "$wrd" ]
 191&nbsp;    then
 192&nbsp;      Status[3]="Duplicate-word-PENALTY"
 193&nbsp;      let "Score[0]= 0 - $PENALTY"
 194&nbsp;      let "Score[1]-=$PENALTY"
 195&nbsp;      return $E_DUP
 196&nbsp;    fi
 197&nbsp;
 198&nbsp;    ((idx++))
 199&nbsp;  done
 200&nbsp;
 201&nbsp;  Words[idx]="$wrd"
 202&nbsp;  get_score
 203&nbsp;
 204&nbsp;}
 205&nbsp;
 206&nbsp;get_score()
 207&nbsp;{
 208&nbsp;  local wlen=0
 209&nbsp;  local score=0
 210&nbsp;  local bonus=0
 211&nbsp;  local first_word=0
 212&nbsp;  local add_word=0
 213&nbsp;  local numwords=0
 214&nbsp;
 215&nbsp;  wlen=${#wrd}
 216&nbsp;  numwords=${Score[wlen]}
 217&nbsp;  Score[2]=0
 218&nbsp;  Status[4]=""   # Initialize "bonus" to 0.
 219&nbsp;
 220&nbsp;  case "$wlen" in
 221&nbsp;    3) first_word=60
 222&nbsp;       add_word=10;;
 223&nbsp;    4) first_word=120
 224&nbsp;       add_word=20;;
 225&nbsp;    5) first_word=200
 226&nbsp;       add_word=50;;
 227&nbsp;    6) first_word=300
 228&nbsp;       add_word=100;;
 229&nbsp;    7) first_word=500
 230&nbsp;       add_word=150;;
 231&nbsp;    8) first_word=750
 232&nbsp;       add_word=250;;
 233&nbsp;    9) first_word=1000
 234&nbsp;       add_word=500;;
 235&nbsp;   10) first_word=2000
 236&nbsp;       add_word=2000;;   # This category modified from original rules!
 237&nbsp;      esac
 238&nbsp;
 239&nbsp;  ((Score[wlen]++))
 240&nbsp;  if [ ${Score[wlen]} -eq $MAXCAT ]
 241&nbsp;  then   # Category completion bonus scoring simplified!
 242&nbsp;    case $wlen in
 243&nbsp;      3 ) bonus=100;;
 244&nbsp;      4 ) bonus=200;;
 245&nbsp;      5 ) bonus=400;;
 246&nbsp;      6 ) bonus=800;;
 247&nbsp;      7 ) bonus=2000;;
 248&nbsp;      8 ) bonus=10000;;
 249&nbsp;    esac  # Needn't worry about 9's and 10's.
 250&nbsp;    Status[4]="Category-$wlen-completion***BONUS***"
 251&nbsp;    Score[2]=$bonus
 252&nbsp;  else
 253&nbsp;    Status[4]=""   # Erase it.
 254&nbsp;  fi
 255&nbsp;
 256&nbsp;
 257&nbsp;    let "score =  $first_word +   $add_word * $numwords"
 258&nbsp;    if [ "$numwords" -eq 0 ]
 259&nbsp;    then
 260&nbsp;      Score[0]=$score
 261&nbsp;    else
 262&nbsp;      Score[0]=$add_word
 263&nbsp;    fi   #  All this to distinguish last-word score
 264&nbsp;         #+ from total running score.
 265&nbsp;  let "Score[1] += ${Score[0]}"
 266&nbsp;  let "Score[1] += ${Score[2]}"
 267&nbsp;
 268&nbsp;}
 269&nbsp;
 270&nbsp;
 271&nbsp;
 272&nbsp;get_word ()
 273&nbsp;{
 274&nbsp;  local wrd=''
 275&nbsp;  read -t $TIMEOUT wrd   # Timed read.
 276&nbsp;  echo $wrd
 277&nbsp;}
 278&nbsp;
 279&nbsp;is_constructable ()
 280&nbsp;{ # This is the most complex and difficult-to-write function.
 281&nbsp;  local -a local_LS=( "${LS[@]}" )  # Local copy of letter set.
 282&nbsp;  local is_found=0
 283&nbsp;  local idx=0
 284&nbsp;  local pos
 285&nbsp;  local strlen
 286&nbsp;  local local_word=( "$1" )
 287&nbsp;  strlen=${#local_word}
 288&nbsp;
 289&nbsp;  while [ "$idx" -lt "$strlen" ]
 290&nbsp;  do
 291&nbsp;    is_found=$(expr index "${local_LS[*]}" "${local_word:idx:1}")
 292&nbsp;    if [ "$is_found" -eq "$NONCONS" ] # Not constructable!
 293&nbsp;    then
 294&nbsp;      echo "$FAILURE"; return
 295&nbsp;    else
 296&nbsp;      ((pos = ($is_found - 1) / 2))   # Compensate for spaces betw. letters!
 297&nbsp;      local_LS[pos]=$NULL             # Zero out used letters.
 298&nbsp;      ((idx++))                       # Bump index.
 299&nbsp;    fi
 300&nbsp;  done
 301&nbsp;
 302&nbsp;  echo "$SUCCESS"
 303&nbsp;  return
 304&nbsp;}
 305&nbsp;
 306&nbsp;is_valid ()
 307&nbsp;{ # Surprisingly easy to check if word in dictionary ...
 308&nbsp;  fgrep -qw "$1" "$WLIST"   # ... courtesy of 'grep' ...
 309&nbsp;  echo $?
 310&nbsp;}
 311&nbsp;
 312&nbsp;check_word ()
 313&nbsp;{
 314&nbsp;  if [ -z "$1" ]
 315&nbsp;  then
 316&nbsp;    return
 317&nbsp;  fi
 318&nbsp;
 319&nbsp;  Status[1]=""
 320&nbsp;  Status[2]=""
 321&nbsp;  Status[3]=""
 322&nbsp;  Status[4]=""
 323&nbsp;
 324&nbsp;  iscons=$(is_constructable "$1")
 325&nbsp;  if [ "$iscons" ]
 326&nbsp;  then
 327&nbsp;    Status[1]="constructable" 
 328&nbsp;    v=$(is_valid "$1")
 329&nbsp;    if [ "$v" -eq "$SUCCESS" ]
 330&nbsp;    then
 331&nbsp;      Status[2]="valid" 
 332&nbsp;      strlen=${#1}
 333&nbsp;
 334&nbsp;      if [ ${Score[strlen]} -eq "$MAXCAT" ]   # Category full!
 335&nbsp;      then
 336&nbsp;        Status[3]="Category-$strlen-overflow-PENALTY"
 337&nbsp;        return $NG
 338&nbsp;      fi
 339&nbsp;
 340&nbsp;      case "$strlen" in
 341&nbsp;        1 | 2 )
 342&nbsp;        Status[3]="Two-letter-word-PENALTY"
 343&nbsp;        return $NG;;
 344&nbsp;        * ) 
 345&nbsp;	Status[3]=""
 346&nbsp;	return $SUCCESS;;
 347&nbsp;      esac
 348&nbsp;    else
 349&nbsp;      Status[3]="Not-valid-PENALTY"
 350&nbsp;      return $NG
 351&nbsp;    fi
 352&nbsp;  else
 353&nbsp;    Status[3]="Not-constructable-PENALTY" 
 354&nbsp;      return $NG
 355&nbsp;  fi
 356&nbsp;
 357&nbsp;  ### FIXME: Streamline the above code block.
 358&nbsp;
 359&nbsp;}
 360&nbsp;
 361&nbsp;
 362&nbsp;display_words ()
 363&nbsp;{
 364&nbsp;  local idx=0
 365&nbsp;  local wlen0
 366&nbsp;
 367&nbsp;  clear
 368&nbsp;  echo "Letterset:   ${LS[@]}"
 369&nbsp;  echo "Threes:    Fours:    Fives:     Sixes:    Sevens:    Eights:"
 370&nbsp;  echo "------------------------------------------------------------"
 371&nbsp;
 372&nbsp;
 373&nbsp;   
 374&nbsp;  while [ "${Words[idx]}" != '' ]
 375&nbsp;  do
 376&nbsp;   wlen0=${#Words[idx]}
 377&nbsp;   case "$wlen0" in
 378&nbsp;     3) ;;
 379&nbsp;     4) echo -n "           " ;;
 380&nbsp;     5) echo -n "                     " ;;
 381&nbsp;     6) echo -n "                                " ;;
 382&nbsp;     7) echo -n "                                          " ;;
 383&nbsp;     8) echo -n "                                                     " ;;
 384&nbsp;   esac
 385&nbsp;   echo "${Words[idx]}"
 386&nbsp;   ((idx++))
 387&nbsp;  done
 388&nbsp;
 389&nbsp;  ### FIXME: The word display is pretty crude.
 390&nbsp;}
 391&nbsp;
 392&nbsp;
 393&nbsp;play ()
 394&nbsp;{
 395&nbsp;  word="Start game"   # Dummy word, to start ...
 396&nbsp;
 397&nbsp;  while [ "$word" ]   #  If player just hits return (null word),
 398&nbsp;  do                  #+ then game ends.
 399&nbsp;    echo "$word: "${Status[@]}""
 400&nbsp;    echo -n "Last score: [${Score[0]}]   TOTAL score: [${Score[1]}]:     Next word: "
 401&nbsp;    total=${Score[1]}
 402&nbsp;    word=$(get_word)
 403&nbsp;    check_word "$word"
 404&nbsp;
 405&nbsp;    if [ "$?" -eq "$SUCCESS" ]
 406&nbsp;    then
 407&nbsp;      add_word "$word"
 408&nbsp;    else
 409&nbsp;      let "Score[0]= 0 - $PENALTY"
 410&nbsp;      let "Score[1]-=$PENALTY"
 411&nbsp;    fi
 412&nbsp;
 413&nbsp;  display_words
 414&nbsp;  done   # Exit game.
 415&nbsp;
 416&nbsp;  ### FIXME: The play () function calls too many other functions.
 417&nbsp;  ### This verges on "spaghetti code" !!!
 418&nbsp;}
 419&nbsp;
 420&nbsp;end_of_game ()
 421&nbsp;{ # Save and display stats.
 422&nbsp;
 423&nbsp;  #######################Autosave##########################
 424&nbsp;  savefile=qky.save.$$
 425&nbsp;  #                 ^^ PID of script
 426&nbsp;  echo `date` &#62;&#62; $savefile
 427&nbsp;  echo "Letterset # $randseed  (random seed) "&#62;&#62; $savefile
 428&nbsp;  echo -n "Letterset: " &#62;&#62; $savefile
 429&nbsp;  echo "${LS[@]}" &#62;&#62; $savefile
 430&nbsp;  echo "---------" &#62;&#62; $savefile
 431&nbsp;  echo "Words constructed:" &#62;&#62; $savefile
 432&nbsp;  echo "${Words[@]}" &#62;&#62; $savefile
 433&nbsp;  echo &#62;&#62; $savefile
 434&nbsp;  echo "Score: $total" &#62;&#62; $savefile
 435&nbsp;
 436&nbsp;  echo "Statistics for this round saved in \""$savefile"\""
 437&nbsp;  #########################################################
 438&nbsp;
 439&nbsp;  echo "Score for this round: $total"
 440&nbsp;  echo "Words:  ${Words[@]}"
 441&nbsp;}
 442&nbsp;
 443&nbsp;# ---------#
 444&nbsp;instructions
 445&nbsp;seed_random
 446&nbsp;get_letset
 447&nbsp;play
 448&nbsp;end_of_game
 449&nbsp;# ---------#
 450&nbsp;
 451&nbsp;exit $?
 452&nbsp;
 453&nbsp;# TODO:
 454&nbsp;#
 455&nbsp;# 1) Clean up code!
 456&nbsp;# 2) Prettify the display_words () function (maybe with widgets?).
 457&nbsp;# 3) Improve the time-out ... maybe change to untimed entry,
 458&nbsp;#+   but with a time limit for the overall round.   
 459&nbsp;# 4) An on-screen countdown timer would be nice.
 460&nbsp;# 5) Implement "vulnerable" mode of play for compatibility with classic
 461&nbsp;#+   version of the game.
 462&nbsp;# 6) Improve save-to-file capability (and maybe make it optional).
 463&nbsp;# 7) Fix bugs!!!
 464&nbsp;
 465&nbsp;# For more info, reference:
 466&nbsp;# http://bash.deta.in/qky.README.html</PRE
></TD
></TR
></TABLE
><HR></DIV
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="NIM"
></A
><P
><B
>Example A-42. Nim</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#!/bin/bash
   2&nbsp;# nim.sh: Game of Nim
   3&nbsp;
   4&nbsp;# Author: Mendel Cooper
   5&nbsp;# Reldate: 15 July 2008
   6&nbsp;# License: GPL3
   7&nbsp;
   8&nbsp;ROWS=5     # Five rows of pegs (or matchsticks).
   9&nbsp;WON=91     # Exit codes to keep track of wins/losses.
  10&nbsp;LOST=92    # Possibly useful if running in batch mode.  
  11&nbsp;QUIT=99
  12&nbsp;peg_msg=   # Peg/Pegs?
  13&nbsp;Rows=( 0 5 4 3 2 1 )   # Array holding play info.
  14&nbsp;# ${Rows[0]} holds total number of pegs, updated after each turn.
  15&nbsp;# Other array elements hold number of pegs in corresponding row.
  16&nbsp;
  17&nbsp;instructions ()
  18&nbsp;{
  19&nbsp;  clear
  20&nbsp;  tput bold
  21&nbsp;  echo "Welcome to the game of Nim."; echo
  22&nbsp;  echo -n "Do you need instructions? (y/n) "; read ans
  23&nbsp;
  24&nbsp;   if [ "$ans" = "y" -o "$ans" = "Y" ]; then
  25&nbsp;     clear
  26&nbsp;     echo -e '\E[33;41m'  # Yellow fg., over red bg.; bold.
  27&nbsp;     cat &#60;&#60;INSTRUCTIONS
  28&nbsp;
  29&nbsp;Nim is a game with roots in the distant past.
  30&nbsp;This particular variant starts with five rows of pegs.
  31&nbsp;
  32&nbsp;1:    | | | | | 
  33&nbsp;2:     | | | | 
  34&nbsp;3:      | | | 
  35&nbsp;4:       | | 
  36&nbsp;5:        | 
  37&nbsp;
  38&nbsp;The number at the left identifies the row.
  39&nbsp;
  40&nbsp;The human player moves first, and alternates turns with the bot.
  41&nbsp;A turn consists of removing at least one peg from a single row.
  42&nbsp;It is permissable to remove ALL the pegs from a row.
  43&nbsp;For example, in row 2, above, the player can remove 1, 2, 3, or 4 pegs.
  44&nbsp;The player who removes the last peg loses.
  45&nbsp;
  46&nbsp;The strategy consists of trying to be the one who removes
  47&nbsp;the next-to-last peg(s), leaving the loser with the final peg.
  48&nbsp;
  49&nbsp;To exit the game early, hit ENTER during your turn.
  50&nbsp;INSTRUCTIONS
  51&nbsp;
  52&nbsp;echo; echo -n "Hit ENTER to begin game. "; read azx
  53&nbsp;
  54&nbsp;      echo -e "\033[0m"    # Restore display.
  55&nbsp;      else tput sgr0; clear
  56&nbsp;  fi
  57&nbsp;
  58&nbsp;clear
  59&nbsp;
  60&nbsp;}
  61&nbsp;
  62&nbsp;
  63&nbsp;tally_up ()
  64&nbsp;{
  65&nbsp;  let "Rows[0] = ${Rows[1]} + ${Rows[2]} + ${Rows[3]} + ${Rows[4]} + \
  66&nbsp;  ${Rows[5]}"    # Add up how many pegs remaining.
  67&nbsp;}
  68&nbsp;
  69&nbsp;
  70&nbsp;display ()
  71&nbsp;{
  72&nbsp;  index=1   # Start with top row.
  73&nbsp;  echo
  74&nbsp;
  75&nbsp;  while [ "$index" -le "$ROWS" ]
  76&nbsp;  do
  77&nbsp;    p=${Rows[index]}
  78&nbsp;    echo -n "$index:   "          # Show row number.
  79&nbsp;
  80&nbsp;  # ------------------------------------------------
  81&nbsp;  # Two concurrent inner loops.
  82&nbsp;
  83&nbsp;      indent=$index
  84&nbsp;      while [ "$indent" -gt 0 ]
  85&nbsp;      do
  86&nbsp;        echo -n " "               # Staggered rows.
  87&nbsp;        ((indent--))              # Spacing between pegs.
  88&nbsp;      done
  89&nbsp;
  90&nbsp;    while [ "$p" -gt 0 ]
  91&nbsp;    do
  92&nbsp;      echo -n "| "
  93&nbsp;      ((p--))
  94&nbsp;    done
  95&nbsp;  # -----------------------------------------------
  96&nbsp;
  97&nbsp;  echo
  98&nbsp;  ((index++))
  99&nbsp;  done  
 100&nbsp;
 101&nbsp;  tally_up
 102&nbsp;
 103&nbsp;  rp=${Rows[0]}
 104&nbsp;
 105&nbsp;  if [ "$rp" -eq 1 ]
 106&nbsp;  then
 107&nbsp;    peg_msg=peg
 108&nbsp;    final_msg="Game over."
 109&nbsp;  else             # Game not yet over . . .
 110&nbsp;    peg_msg=pegs
 111&nbsp;    final_msg=""   # . . . So "final message" is blank.
 112&nbsp;  fi
 113&nbsp;
 114&nbsp;  echo "      $rp $peg_msg remaining."
 115&nbsp;  echo "      "$final_msg""
 116&nbsp;
 117&nbsp;
 118&nbsp;  echo
 119&nbsp;}
 120&nbsp;
 121&nbsp;player_move ()
 122&nbsp;{
 123&nbsp;
 124&nbsp;  echo "Your move:"
 125&nbsp;
 126&nbsp;  echo -n "Which row? "
 127&nbsp;  while read idx
 128&nbsp;  do                   # Validity check, etc.
 129&nbsp;
 130&nbsp;    if [ -z "$idx" ]   # Hitting return quits.
 131&nbsp;    then
 132&nbsp;        echo "Premature exit."; echo
 133&nbsp;        tput sgr0      # Restore display.
 134&nbsp;        exit $QUIT
 135&nbsp;    fi
 136&nbsp;
 137&nbsp;    if [ "$idx" -gt "$ROWS" -o "$idx" -lt 1 ]   # Bounds check.
 138&nbsp;    then
 139&nbsp;      echo "Invalid row number!"
 140&nbsp;      echo -n "Which row? "
 141&nbsp;    else
 142&nbsp;      break
 143&nbsp;    fi
 144&nbsp;    # TODO:
 145&nbsp;    # Add check for non-numeric input.
 146&nbsp;    # Also, script crashes on input outside of range of long double.
 147&nbsp;    # Fix this.
 148&nbsp;
 149&nbsp;  done
 150&nbsp;
 151&nbsp;  echo -n "Remove how many? "
 152&nbsp;  while read num
 153&nbsp;  do                   # Validity check.
 154&nbsp;
 155&nbsp;  if [ -z "$num" ]
 156&nbsp;  then
 157&nbsp;    echo "Premature exit."; echo
 158&nbsp;    tput sgr0          # Restore display.
 159&nbsp;    exit $QUIT
 160&nbsp;  fi
 161&nbsp;
 162&nbsp;    if [ "$num" -gt ${Rows[idx]} -o "$num" -lt 1 ]
 163&nbsp;    then
 164&nbsp;      echo "Cannot remove $num!"
 165&nbsp;      echo -n "Remove how many? "
 166&nbsp;    else
 167&nbsp;      break
 168&nbsp;    fi
 169&nbsp;  done
 170&nbsp;  # TODO:
 171&nbsp;  # Add check for non-numeric input.
 172&nbsp;  # Also, script crashes on input outside of range of long double.
 173&nbsp;  # Fix this.
 174&nbsp;
 175&nbsp;  let "Rows[idx] -= $num"
 176&nbsp;
 177&nbsp;  display
 178&nbsp;  tally_up
 179&nbsp;
 180&nbsp;  if [ ${Rows[0]} -eq 1 ]
 181&nbsp;  then
 182&nbsp;   echo "      Human wins!"
 183&nbsp;   echo "      Congratulations!"
 184&nbsp;   tput sgr0   # Restore display.
 185&nbsp;   echo
 186&nbsp;   exit $WON
 187&nbsp;  fi
 188&nbsp;
 189&nbsp;  if [ ${Rows[0]} -eq 0 ]
 190&nbsp;  then          # Snatching defeat from the jaws of victory . . .
 191&nbsp;    echo "      Fool!"
 192&nbsp;    echo "      You just removed the last peg!"
 193&nbsp;    echo "      Bot wins!"
 194&nbsp;    tput sgr0   # Restore display.
 195&nbsp;    echo
 196&nbsp;    exit $LOST
 197&nbsp;  fi
 198&nbsp;}
 199&nbsp;
 200&nbsp;
 201&nbsp;bot_move ()
 202&nbsp;{
 203&nbsp;
 204&nbsp;  row_b=0
 205&nbsp;  while [[ $row_b -eq 0 || ${Rows[row_b]} -eq 0 ]]
 206&nbsp;  do
 207&nbsp;    row_b=$RANDOM          # Choose random row.
 208&nbsp;    let "row_b %= $ROWS"
 209&nbsp;  done
 210&nbsp;
 211&nbsp;
 212&nbsp;  num_b=0
 213&nbsp;  r0=${Rows[row_b]}
 214&nbsp;
 215&nbsp;  if [ "$r0" -eq 1 ]
 216&nbsp;  then
 217&nbsp;    num_b=1
 218&nbsp;  else
 219&nbsp;    let "num_b = $r0 - 1"
 220&nbsp;         #  Leave only a single peg in the row.
 221&nbsp;  fi     #  Not a very strong strategy,
 222&nbsp;         #+ but probably a bit better than totally random.
 223&nbsp;
 224&nbsp;  let "Rows[row_b] -= $num_b"
 225&nbsp;  echo -n "Bot:  "
 226&nbsp;  echo "Removing from row $row_b ... "
 227&nbsp;
 228&nbsp;  if [ "$num_b" -eq 1 ]
 229&nbsp;  then
 230&nbsp;    peg_msg=peg
 231&nbsp;  else
 232&nbsp;    peg_msg=pegs
 233&nbsp;  fi
 234&nbsp;
 235&nbsp;  echo "      $num_b $peg_msg."
 236&nbsp;
 237&nbsp;  display
 238&nbsp;  tally_up
 239&nbsp;
 240&nbsp;  if [ ${Rows[0]} -eq 1 ]
 241&nbsp;  then
 242&nbsp;   echo "      Bot wins!"
 243&nbsp;   tput sgr0   # Restore display.
 244&nbsp;   exit $WON
 245&nbsp;  fi
 246&nbsp;
 247&nbsp;}
 248&nbsp;
 249&nbsp;
 250&nbsp;# ================================================== #
 251&nbsp;instructions     # If human player needs them . . .
 252&nbsp;tput bold        # Bold characters for easier viewing.
 253&nbsp;display          # Show game board.
 254&nbsp;
 255&nbsp;while [ true ]   # Main loop.
 256&nbsp;do               # Alternate human and bot turns.
 257&nbsp;  player_move
 258&nbsp;  bot_move
 259&nbsp;done
 260&nbsp;# ================================================== #
 261&nbsp;
 262&nbsp;# Exercise:
 263&nbsp;# --------
 264&nbsp;# Improve the bot's strategy.
 265&nbsp;# There is, in fact, a Nim strategy that can force a win.
 266&nbsp;# See the Wikipedia article on Nim:  http://en.wikipedia.org/wiki/Nim
 267&nbsp;# Recode the bot to use this strategy (rather difficult).
 268&nbsp;
 269&nbsp;#  Curiosities:
 270&nbsp;#  -----------
 271&nbsp;#  Nim played a prominent role in Alain Resnais' 1961 New Wave film,
 272&nbsp;#+ Last Year at Marienbad.
 273&nbsp;#
 274&nbsp;#  In 1978, Leo Christopherson wrote an animated version of Nim,
 275&nbsp;#+ Android Nim, for the TRS-80 Model I.</PRE
></TD
></TR
></TABLE
><HR></DIV
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="STOPWATCH"
></A
><P
><B
>Example A-43. A command-line stopwatch</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#!/bin/sh
   2&nbsp;# sw.sh
   3&nbsp;# A command-line Stopwatch
   4&nbsp;
   5&nbsp;# Author: Pdraig Brady
   6&nbsp;#    http://www.pixelbeat.org/scripts/sw
   7&nbsp;#    (Minor reformatting by ABS Guide author.)
   8&nbsp;#    Used in ABS Guide with script author's permission.
   9&nbsp;# Notes:
  10&nbsp;#    This script starts a few processes per lap, in addition to
  11&nbsp;#    the shell loop processing, so the assumption is made that
  12&nbsp;#    this takes an insignificant amount of time compared to
  13&nbsp;#    the response time of humans (~.1s) (or the keyboard
  14&nbsp;#    interrupt rate (~.05s)).
  15&nbsp;#    '?' for splits must be entered twice if characters
  16&nbsp;#    (erroneously) entered before it (on the same line).
  17&nbsp;#    '?' since not generating a signal may be slightly delayed
  18&nbsp;#    on heavily loaded systems.
  19&nbsp;#    Lap timings on ubuntu may be slightly delayed due to:
  20&nbsp;#    https://bugs.launchpad.net/bugs/62511
  21&nbsp;# Changes:
  22&nbsp;#    V1.0, 23 Aug 2005, Initial release
  23&nbsp;#    V1.1, 26 Jul 2007, Allow both splits and laps from single invocation.
  24&nbsp;#                       Only start timer after a key is pressed.
  25&nbsp;#                       Indicate lap number
  26&nbsp;#                       Cache programs at startup so there is less error
  27&nbsp;#                       due to startup delays.
  28&nbsp;#    V1.2, 01 Aug 2007, Work around `date` commands that don't have
  29&nbsp;#                       nanoseconds.
  30&nbsp;#                       Use stty to change interrupt keys to space for
  31&nbsp;#                       laps etc.
  32&nbsp;#                       Ignore other input as it causes problems.
  33&nbsp;#    V1.3, 01 Aug 2007, Testing release.
  34&nbsp;#    V1.4, 02 Aug 2007, Various tweaks to get working under ubuntu
  35&nbsp;#                       and Mac OS X.
  36&nbsp;#    V1.5, 27 Jun 2008, set LANG=C as got vague bug report about it.
  37&nbsp;
  38&nbsp;export LANG=C
  39&nbsp;
  40&nbsp;ulimit -c 0   # No coredumps from SIGQUIT.
  41&nbsp;trap '' TSTP  # Ignore Ctrl-Z just in case.
  42&nbsp;save_tty=`stty -g` &#38;&#38; trap "stty $save_tty" EXIT  # Restore tty on exit.
  43&nbsp;stty quit ' ' # Space for laps rather than Ctrl-\.
  44&nbsp;stty eof  '?' # ? for splits rather than Ctrl-D.
  45&nbsp;stty -echo    # Don't echo input.
  46&nbsp;
  47&nbsp;cache_progs() {
  48&nbsp;    stty &#62; /dev/null
  49&nbsp;    date &#62; /dev/null
  50&nbsp;    grep . &#60; /dev/null
  51&nbsp;    (echo "import time" | python) 2&#62; /dev/null
  52&nbsp;    bc &#60; /dev/null
  53&nbsp;    sed '' &#60; /dev/null
  54&nbsp;    printf '1' &#62; /dev/null
  55&nbsp;    /usr/bin/time false 2&#62; /dev/null
  56&nbsp;    cat &#60; /dev/null
  57&nbsp;}
  58&nbsp;cache_progs   # To minimise startup delay.
  59&nbsp;
  60&nbsp;date +%s.%N | grep -qF 'N' &#38;&#38; use_python=1 # If `date` lacks nanoseconds.
  61&nbsp;now() {
  62&nbsp;    if [ "$use_python" ]; then
  63&nbsp;        echo "import time; print time.time()" 2&#62;/dev/null | python
  64&nbsp;    else
  65&nbsp;        printf "%.2f" `date +%s.%N`
  66&nbsp;    fi
  67&nbsp;}
  68&nbsp;
  69&nbsp;fmt_seconds() {
  70&nbsp;    seconds=$1
  71&nbsp;    mins=`echo $seconds/60 | bc`
  72&nbsp;    if [ "$mins" != "0" ]; then
  73&nbsp;        seconds=`echo "$seconds - ($mins*60)" | bc`
  74&nbsp;        echo "$mins:$seconds"
  75&nbsp;    else
  76&nbsp;        echo "$seconds"
  77&nbsp;    fi
  78&nbsp;}
  79&nbsp;
  80&nbsp;total() {
  81&nbsp;    end=`now`
  82&nbsp;    total=`echo "$end - $start" | bc`
  83&nbsp;    fmt_seconds $total
  84&nbsp;}
  85&nbsp;
  86&nbsp;stop() {
  87&nbsp;    [ "$lapped" ] &#38;&#38; lap "$laptime" "display"
  88&nbsp;    total
  89&nbsp;    exit
  90&nbsp;}
  91&nbsp;
  92&nbsp;lap() {
  93&nbsp;    laptime=`echo "$1" | sed -n 's/.*real[^0-9.]*\(.*\)/\1/p'`
  94&nbsp;    [ ! "$laptime" -o "$laptime" = "0.00" ] &#38;&#38; return
  95&nbsp;    # Signals too frequent.
  96&nbsp;    laptotal=`echo $laptime+0$laptotal | bc`
  97&nbsp;    if [ "$2" = "display" ]; then
  98&nbsp;        lapcount=`echo 0$lapcount+1 | bc`
  99&nbsp;        laptime=`fmt_seconds $laptotal`
 100&nbsp;        echo $laptime "($lapcount)"
 101&nbsp;        lapped="true"
 102&nbsp;        laptotal="0"
 103&nbsp;    fi
 104&nbsp;}
 105&nbsp;
 106&nbsp;echo -n "Space for lap | ? for split | Ctrl-C to stop | Space to start..."&#62;&#38;2
 107&nbsp;
 108&nbsp;while true; do
 109&nbsp;    trap true INT QUIT  # Set signal handlers.
 110&nbsp;    laptime=`/usr/bin/time -p 2&#62;&#38;1 cat &#62;/dev/null`
 111&nbsp;    ret=$?
 112&nbsp;    trap '' INT QUIT    # Ignore signals within this script.
 113&nbsp;    if [ $ret -eq 1 -o $ret -eq 2 -o $ret -eq 130 ]; then # SIGINT = stop
 114&nbsp;        [ ! "$start" ] &#38;&#38; { echo &#62;&#38;2; exit; }
 115&nbsp;        stop
 116&nbsp;    elif [ $ret -eq 3 -o $ret -eq 131 ]; then             # SIGQUIT = lap
 117&nbsp;        if [ ! "$start" ]; then
 118&nbsp;            start=`now` || exit 1
 119&nbsp;            echo &#62;&#38;2
 120&nbsp;            continue
 121&nbsp;        fi
 122&nbsp;        lap "$laptime" "display"
 123&nbsp;    else                # eof = split
 124&nbsp;        [ ! "$start" ] &#38;&#38; continue
 125&nbsp;        total
 126&nbsp;        lap "$laptime"  # Update laptotal.
 127&nbsp;    fi
 128&nbsp;done
 129&nbsp;
 130&nbsp;exit $?</PRE
></TD
></TR
></TABLE
><HR></DIV
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="HOMEWORK"
></A
><P
><B
>Example A-44. An all-purpose shell scripting homework assignment solution</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#!/bin/bash
   2&nbsp;#  homework.sh: All-purpose homework assignment solution.
   3&nbsp;#  Author: M. Leo Cooper
   4&nbsp;#  If you substitute your own name as author, then it is plagiarism,
   5&nbsp;#+ possibly a lesser sin than cheating on your homework!
   6&nbsp;#  License: Public Domain
   7&nbsp;
   8&nbsp;#  This script may be turned in to your instructor
   9&nbsp;#+ in fulfillment of ALL shell scripting homework assignments.
  10&nbsp;#  It's sparsely commented, but you, the student, can easily remedy that.
  11&nbsp;#  The script author repudiates all responsibility!
  12&nbsp;
  13&nbsp;DLA=1
  14&nbsp;P1=2
  15&nbsp;P2=4
  16&nbsp;P3=7
  17&nbsp;PP1=0
  18&nbsp;PP2=8
  19&nbsp;MAXL=9
  20&nbsp;E_LZY=99
  21&nbsp;
  22&nbsp;declare -a L
  23&nbsp;L[0]="3 4 0 17 29 8 13 18 19 17 20 2 19 14 17 28"
  24&nbsp;L[1]="8 29 12 14 18 19 29 4 12 15 7 0 19 8 2 0 11 11 24 29 17 4 6 17 4 19"
  25&nbsp;L[2]="29 19 7 0 19 29 8 29 7 0 21 4 29 13 4 6 11 4 2 19 4 3"
  26&nbsp;L[3]="19 14 29 2 14 12 15 11 4 19 4 29 19 7 8 18 29"
  27&nbsp;L[4]="18 2 7 14 14 11 22 14 17 10 29 0 18 18 8 6 13 12 4 13 19 26"
  28&nbsp;L[5]="15 11 4 0 18 4 29 0 2 2 4 15 19 29 12 24 29 7 20 12 1 11 4 29"
  29&nbsp;L[6]="4 23 2 20 18 4 29 14 5 29 4 6 17 4 6 8 14 20 18 29"
  30&nbsp;L[7]="11 0 25 8 13 4 18 18 27"
  31&nbsp;L[8]="0 13 3 29 6 17 0 3 4 29 12 4 29 0 2 2 14 17 3 8 13 6 11 24 26"
  32&nbsp;L[9]="19 7 0 13 10 29 24 14 20 26"
  33&nbsp;
  34&nbsp;declare -a \
  35&nbsp;alph=( 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 Z . , : ' ' )
  36&nbsp;
  37&nbsp;
  38&nbsp;pt_lt ()
  39&nbsp;{
  40&nbsp;  echo -n "${alph[$1]}"
  41&nbsp;  echo -n -e "\a"
  42&nbsp;  sleep $DLA
  43&nbsp;}
  44&nbsp;
  45&nbsp;b_r ()
  46&nbsp;{
  47&nbsp; echo -e '\E[31;48m\033[1m'
  48&nbsp;}
  49&nbsp;
  50&nbsp;cr ()
  51&nbsp;{
  52&nbsp; echo -e "\a"
  53&nbsp; sleep $DLA
  54&nbsp;}
  55&nbsp;
  56&nbsp;restore ()
  57&nbsp;{
  58&nbsp;  echo -e '\033[0m'            # Bold off.
  59&nbsp;  tput sgr0                    # Normal.
  60&nbsp;}
  61&nbsp;
  62&nbsp;
  63&nbsp;p_l ()
  64&nbsp;{
  65&nbsp;  for ltr in $1
  66&nbsp;  do
  67&nbsp;    pt_lt "$ltr"
  68&nbsp;  done
  69&nbsp;}
  70&nbsp;
  71&nbsp;# ----------------------
  72&nbsp;b_r
  73&nbsp;
  74&nbsp;for i in $(seq 0 $MAXL)
  75&nbsp;do
  76&nbsp;  p_l "${L[i]}"
  77&nbsp;  if [[ "$i" -eq "$P1" || "$i" -eq "$P2" || "$i" -eq "$P3" ]]
  78&nbsp;  then
  79&nbsp;    cr
  80&nbsp;  elif [[ "$i" -eq "$PP1" || "$i" -eq "$PP2" ]]
  81&nbsp;  then
  82&nbsp;    cr; cr
  83&nbsp;  fi
  84&nbsp;done
  85&nbsp;
  86&nbsp;restore
  87&nbsp;# ----------------------
  88&nbsp;
  89&nbsp;echo
  90&nbsp;
  91&nbsp;exit $E_LZY
  92&nbsp;
  93&nbsp;#  A typical example of an obfuscated script that is difficult
  94&nbsp;#+ to understand, and frustrating to maintain.
  95&nbsp;#  In your career as a sysadmin, you'll run into these critters
  96&nbsp;#+ all too often.</PRE
></TD
></TR
></TABLE
><HR></DIV
><P
><A
NAME="KTOUR0"
></A
></P
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="KTOUR"
></A
><P
><B
>Example A-45. The Knight's Tour</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#!/bin/bash
   2&nbsp;# ktour.sh
   3&nbsp;
   4&nbsp;# author: mendel cooper
   5&nbsp;# reldate: 12 Jan 2009
   6&nbsp;# license: public domain
   7&nbsp;# (Not much sense GPLing something that's pretty much in the common
   8&nbsp;#+ domain anyhow.)
   9&nbsp;
  10&nbsp;###################################################################
  11&nbsp;#             The Knight's Tour, a classic problem.               #
  12&nbsp;#             =====================================               #
  13&nbsp;#  The knight must move onto every square of the chess board,     #
  14&nbsp;#  but cannot revisit any square he has already visited.          #
  15&nbsp;#                                                                 #
  16&nbsp;#  And just why is Sir Knight unwelcome for a return visit?       #
  17&nbsp;#  Could it be that he has a habit of partying into the wee hours #
  18&nbsp;#+ of the morning?                                                #
  19&nbsp;#  Possibly he leaves pizza crusts in the bed, empty beer bottles #
  20&nbsp;#+ all over the floor, and clogs the plumbing. . . .              #
  21&nbsp;#                                                                 #
  22&nbsp;#  -------------------------------------------------------------  #
  23&nbsp;#                                                                 #
  24&nbsp;#  Usage: ktour.sh [start-square] [stupid]                        #
  25&nbsp;#                                                                 #
  26&nbsp;#  Note that start-square can be a square number                  #
  27&nbsp;#+ in the range 0 - 63 ... or                                     #
  28&nbsp;#  a square designator in conventional chess notation,            #
  29&nbsp;#  such as a1, f5, h3, etc.                                       #
  30&nbsp;#                                                                 #
  31&nbsp;#  If start-square-number not supplied,                           #
  32&nbsp;#+ then starts on a random square somewhere on the board.         #
  33&nbsp;#                                                                 #
  34&nbsp;# "stupid" as second parameter sets the stupid strategy.          #
  35&nbsp;#                                                                 #
  36&nbsp;#  Examples:                                                      #
  37&nbsp;#  ktour.sh 23          starts on square #23 (h3)                 #
  38&nbsp;#  ktour.sh g6 stupid   starts on square #46,                     #
  39&nbsp;#                       using "stupid" (non-Warnsdorff) strategy. #
  40&nbsp;###################################################################
  41&nbsp;
  42&nbsp;DEBUG=      # Set this to echo debugging info to stdout.
  43&nbsp;SUCCESS=0
  44&nbsp;FAIL=99
  45&nbsp;BADMOVE=-999
  46&nbsp;FAILURE=1
  47&nbsp;LINELEN=21  # How many moves to display per line.
  48&nbsp;# ---------------------------------------- #
  49&nbsp;# Board array params
  50&nbsp;ROWS=8   # 8 x 8 board.
  51&nbsp;COLS=8
  52&nbsp;let "SQUARES = $ROWS * $COLS"
  53&nbsp;let "MAX = $SQUARES - 1"
  54&nbsp;MIN=0
  55&nbsp;# 64 squares on board, indexed from 0 to 63.
  56&nbsp;
  57&nbsp;VISITED=1
  58&nbsp;UNVISITED=-1
  59&nbsp;UNVSYM="##"
  60&nbsp;# ---------------------------------------- #
  61&nbsp;# Global variables.
  62&nbsp;startpos=    # Starting position (square #, 0 - 63).
  63&nbsp;currpos=     # Current position.
  64&nbsp;movenum=     # Move number.
  65&nbsp;CRITPOS=37   # Have to patch for f5 starting position!
  66&nbsp;
  67&nbsp;declare -i board
  68&nbsp;# Use a one-dimensional array to simulate a two-dimensional one.
  69&nbsp;# This can make life difficult and result in ugly kludges; see below.
  70&nbsp;declare -i moves  # Offsets from current knight position.
  71&nbsp;
  72&nbsp;
  73&nbsp;initialize_board ()
  74&nbsp;{
  75&nbsp;  local idx
  76&nbsp;
  77&nbsp;  for idx in {0..63}
  78&nbsp;  do
  79&nbsp;    board[$idx]=$UNVISITED
  80&nbsp;  done
  81&nbsp;}
  82&nbsp;
  83&nbsp;
  84&nbsp;
  85&nbsp;print_board ()
  86&nbsp;{
  87&nbsp;  local idx
  88&nbsp;
  89&nbsp;  echo "    _____________________________________"
  90&nbsp;  for row in {7..0}               #  Reverse order of rows ...
  91&nbsp;  do                              #+ so it prints in chessboard order.
  92&nbsp;    let "rownum = $row + 1"       #  Start numbering rows at 1.
  93&nbsp;    echo -n "$rownum  |"          #  Mark board edge with border and
  94&nbsp;    for column in {0..7}          #+ "algebraic notation."
  95&nbsp;    do
  96&nbsp;      let "idx = $ROWS*$row + $column"
  97&nbsp;      if [ ${board[idx]} -eq $UNVISITED ]
  98&nbsp;      then
  99&nbsp;        echo -n "$UNVSYM   "      ##
 100&nbsp;      else                        # Mark square with move number.
 101&nbsp;        printf "%02d " "${board[idx]}"; echo -n "  "
 102&nbsp;      fi
 103&nbsp;    done
 104&nbsp;    echo -e -n "\b\b\b|"  # \b is a backspace.
 105&nbsp;    echo                  # -e enables echoing escaped chars.
 106&nbsp;  done
 107&nbsp;
 108&nbsp;  echo "    -------------------------------------"
 109&nbsp;  echo "     a    b    c    d    e    f    g    h"
 110&nbsp;}
 111&nbsp;
 112&nbsp;
 113&nbsp;
 114&nbsp;failure()
 115&nbsp;{ # Whine, then bail out.
 116&nbsp;  echo
 117&nbsp;  print_board
 118&nbsp;  echo
 119&nbsp;  echo    "   Waah!!! Ran out of squares to move to!"
 120&nbsp;  echo -n "   Knight's Tour attempt ended"
 121&nbsp;  echo    " on $(to_algebraic $currpos) [square #$currpos]"
 122&nbsp;  echo    "   after just $movenum moves!"
 123&nbsp;  echo
 124&nbsp;  exit $FAIL
 125&nbsp;}
 126&nbsp;
 127&nbsp;
 128&nbsp;
 129&nbsp;xlat_coords ()   #  Translate x/y coordinates to board position
 130&nbsp;{                #+ (board-array element #).
 131&nbsp;  #  For user input of starting board position as x/y coords.
 132&nbsp;  #  This function not used in initial release of ktour.sh.
 133&nbsp;  #  May be used in an updated version, for compatibility with
 134&nbsp;  #+ standard implementation of the Knight's Tour in C, Python, etc.
 135&nbsp;  if [ -z "$1" -o -z "$2" ]
 136&nbsp;  then
 137&nbsp;    return $FAIL
 138&nbsp;  fi
 139&nbsp;
 140&nbsp;  local xc=$1
 141&nbsp;  local yc=$2
 142&nbsp;
 143&nbsp;  let "board_index = $xc * $ROWS + yc"
 144&nbsp;
 145&nbsp;  if [ $board_index -lt $MIN -o $board_index -gt $MAX ]
 146&nbsp;  then
 147&nbsp;    return $FAIL    # Strayed off the board!
 148&nbsp;  else
 149&nbsp;    return $board_index
 150&nbsp;  fi
 151&nbsp;}
 152&nbsp;
 153&nbsp;
 154&nbsp;
 155&nbsp;to_algebraic ()   #  Translate board position (board-array element #)
 156&nbsp;{                 #+ to standard algebraic notation used by chess players.
 157&nbsp;  if [ -z "$1" ]
 158&nbsp;  then
 159&nbsp;    return $FAIL
 160&nbsp;  fi
 161&nbsp;
 162&nbsp;  local element_no=$1   # Numerical board position.
 163&nbsp;  local col_arr=( a b c d e f g h )
 164&nbsp;  local row_arr=( 1 2 3 4 5 6 7 8 )
 165&nbsp;
 166&nbsp;  let "row_no = $element_no / $ROWS"
 167&nbsp;  let "col_no = $element_no % $ROWS"
 168&nbsp;  t1=${col_arr[col_no]}; t2=${row_arr[row_no]}
 169&nbsp;  local apos=$t1$t2   # Concatenate.
 170&nbsp;  echo $apos
 171&nbsp;}
 172&nbsp;
 173&nbsp;
 174&nbsp;
 175&nbsp;from_algebraic ()   #  Translate standard algebraic chess notation
 176&nbsp;{                   #+ to numerical board position (board-array element #).
 177&nbsp;                    #  Or recognize numerical input &#38; return it unchanged.
 178&nbsp;  if [ -z "$1" ]
 179&nbsp;  then
 180&nbsp;    return $FAIL
 181&nbsp;  fi   # If no command-line arg, then will default to random start pos.
 182&nbsp;
 183&nbsp;  local ix
 184&nbsp;  local ix_count=0
 185&nbsp;  local b_index     # Board index [0-63]
 186&nbsp;  local alpos="$1"
 187&nbsp;
 188&nbsp;  arow=${alpos:0:1} # position = 0, length = 1
 189&nbsp;  acol=${alpos:1:1}
 190&nbsp;
 191&nbsp;  if [[ $arow =~ [[:digit:]] ]]   #  Numerical input?
 192&nbsp;  then       #  POSIX char class
 193&nbsp;    if [[ $acol =~ [[:alpha:]] ]] # Number followed by a letter? Illegal!
 194&nbsp;      then return $FAIL
 195&nbsp;    else if [ $alpos -gt $MAX ]   # Off board?
 196&nbsp;      then return $FAIL
 197&nbsp;    else return $alpos            #  Return digit(s) unchanged . . .
 198&nbsp;      fi                          #+ if within range.
 199&nbsp;    fi
 200&nbsp;  fi
 201&nbsp;
 202&nbsp;  if [[ $acol -eq $MIN || $acol -gt $ROWS ]]
 203&nbsp;  then        # Outside of range 1 - 8?
 204&nbsp;    return $FAIL
 205&nbsp;  fi
 206&nbsp;
 207&nbsp;  for ix in a b c d e f g h
 208&nbsp;  do  # Convert column letter to column number.
 209&nbsp;   if [ "$arow" = "$ix" ]
 210&nbsp;   then
 211&nbsp;     break
 212&nbsp;   fi
 213&nbsp;  ((ix_count++))    # Find index count.
 214&nbsp;  done
 215&nbsp;
 216&nbsp;  ((acol--))        # Decrementing converts to zero-based array.
 217&nbsp;  let "b_index = $ix_count + $acol * $ROWS"
 218&nbsp;
 219&nbsp;  if [ $b_index -gt $MAX ]   # Off board?
 220&nbsp;  then
 221&nbsp;    return $FAIL
 222&nbsp;  fi
 223&nbsp;    
 224&nbsp;  return $b_index
 225&nbsp;
 226&nbsp;}
 227&nbsp;
 228&nbsp;
 229&nbsp;generate_moves ()   #  Calculate all valid knight moves,
 230&nbsp;{                   #+ relative to current position ($1),
 231&nbsp;                    #+ and store in ${moves} array.
 232&nbsp;  local kt_hop=1    #  One square  :: short leg of knight move.
 233&nbsp;  local kt_skip=2   #  Two squares :: long leg  of knight move.
 234&nbsp;  local valmov=0    #  Valid moves.
 235&nbsp;  local row_pos; let "row_pos = $1 % $COLS"
 236&nbsp;
 237&nbsp;
 238&nbsp;  let "move1 = -$kt_skip + $ROWS"           # 2 sideways to-the-left,  1 up
 239&nbsp;    if [[ `expr $row_pos - $kt_skip` -lt $MIN ]]   # An ugly, ugly kludge!
 240&nbsp;    then                                           # Can't move off board.
 241&nbsp;      move1=$BADMOVE                               # Not even temporarily.
 242&nbsp;    else
 243&nbsp;      ((valmov++))
 244&nbsp;    fi
 245&nbsp;  let "move2 = -$kt_hop + $kt_skip * $ROWS" # 1 sideways to-the-left,  2 up
 246&nbsp;    if [[ `expr $row_pos - $kt_hop` -lt $MIN ]]    # Kludge continued ...
 247&nbsp;    then
 248&nbsp;      move2=$BADMOVE
 249&nbsp;    else
 250&nbsp;      ((valmov++))
 251&nbsp;    fi
 252&nbsp;  let "move3 =  $kt_hop + $kt_skip * $ROWS" # 1 sideways to-the-right, 2 up
 253&nbsp;    if [[ `expr $row_pos + $kt_hop` -ge $COLS ]]
 254&nbsp;    then
 255&nbsp;      move3=$BADMOVE
 256&nbsp;    else
 257&nbsp;      ((valmov++))
 258&nbsp;    fi
 259&nbsp;  let "move4 =  $kt_skip + $ROWS"           # 2 sideways to-the-right, 1 up
 260&nbsp;    if [[ `expr $row_pos + $kt_skip` -ge $COLS ]]
 261&nbsp;    then
 262&nbsp;      move4=$BADMOVE
 263&nbsp;    else
 264&nbsp;      ((valmov++))
 265&nbsp;    fi
 266&nbsp;  let "move5 =  $kt_skip - $ROWS"           # 2 sideways to-the-right, 1 dn
 267&nbsp;    if [[ `expr $row_pos + $kt_skip` -ge $COLS ]]
 268&nbsp;    then
 269&nbsp;      move5=$BADMOVE
 270&nbsp;    else
 271&nbsp;      ((valmov++))
 272&nbsp;    fi
 273&nbsp;  let "move6 =  $kt_hop - $kt_skip * $ROWS" # 1 sideways to-the-right, 2 dn
 274&nbsp;    if [[ `expr $row_pos + $kt_hop` -ge $COLS ]]
 275&nbsp;    then
 276&nbsp;      move6=$BADMOVE
 277&nbsp;    else
 278&nbsp;      ((valmov++))
 279&nbsp;    fi
 280&nbsp;  let "move7 = -$kt_hop - $kt_skip * $ROWS" # 1 sideways to-the-left,  2 dn
 281&nbsp;    if [[ `expr $row_pos - $kt_hop` -lt $MIN ]]
 282&nbsp;    then
 283&nbsp;      move7=$BADMOVE
 284&nbsp;    else
 285&nbsp;      ((valmov++))
 286&nbsp;    fi
 287&nbsp;  let "move8 = -$kt_skip - $ROWS"           # 2 sideways to-the-left,  1 dn
 288&nbsp;    if [[ `expr $row_pos - $kt_skip` -lt $MIN ]]
 289&nbsp;    then
 290&nbsp;      move8=$BADMOVE
 291&nbsp;    else
 292&nbsp;      ((valmov++))
 293&nbsp;    fi   # There must be a better way to do this.
 294&nbsp;
 295&nbsp;  local m=( $valmov $move1 $move2 $move3 $move4 $move5 $move6 $move7 $move8 )
 296&nbsp;  # ${moves[0]} = number of valid moves.
 297&nbsp;  # ${moves[1]} ... ${moves[8]} = possible moves.
 298&nbsp;  echo "${m[*]}"    # Elements of array to stdout for capture in a var.
 299&nbsp;
 300&nbsp;}
 301&nbsp;
 302&nbsp;
 303&nbsp;
 304&nbsp;is_on_board ()  # Is position actually on the board?
 305&nbsp;{
 306&nbsp;  if [[ "$1" -lt "$MIN" || "$1" -gt "$MAX" ]]
 307&nbsp;  then
 308&nbsp;    return $FAILURE
 309&nbsp;  else
 310&nbsp;    return $SUCCESS
 311&nbsp;  fi
 312&nbsp;}
 313&nbsp;
 314&nbsp;
 315&nbsp;
 316&nbsp;do_move ()      # Move the knight!
 317&nbsp;{
 318&nbsp;  local valid_moves=0
 319&nbsp;  local aapos
 320&nbsp;  currposl="$1"
 321&nbsp;  lmin=$ROWS
 322&nbsp;  iex=0
 323&nbsp;  squarel=
 324&nbsp;  mpm=
 325&nbsp;  mov=
 326&nbsp;  declare -a p_moves
 327&nbsp;
 328&nbsp;  ########################## DECIDE-MOVE #############################
 329&nbsp;  if [ $startpos -ne $CRITPOS ]
 330&nbsp;  then   # CRITPOS = square #37
 331&nbsp;    decide_move
 332&nbsp;  else                     # Needs a special patch for startpos=37 !!!
 333&nbsp;    decide_move_patched    # Why this particular move and no other ???
 334&nbsp;  fi
 335&nbsp;  ####################################################################
 336&nbsp;
 337&nbsp;  (( ++movenum ))          # Increment move count.
 338&nbsp;  let "square = $currposl + ${moves[iex]}"
 339&nbsp;
 340&nbsp;  ##################    DEBUG    ###############
 341&nbsp;  if [ "$DEBUG" ]
 342&nbsp;    then debug   # Echo debugging information.
 343&nbsp;  fi
 344&nbsp;  ##############################################
 345&nbsp;
 346&nbsp;  if [[ "$square" -gt $MAX || "$square" -lt $MIN ||
 347&nbsp;        ${board[square]} -ne $UNVISITED ]]
 348&nbsp;  then
 349&nbsp;    (( --movenum ))              #  Decrement move count,
 350&nbsp;    echo "RAN OUT OF SQUARES!!!" #+ since previous one was invalid.
 351&nbsp;    return $FAIL
 352&nbsp;  fi
 353&nbsp;
 354&nbsp;  board[square]=$movenum
 355&nbsp;  currpos=$square       # Update current position.
 356&nbsp;  ((valid_moves++));    # moves[0]=$valid_moves
 357&nbsp;  aapos=$(to_algebraic $square)
 358&nbsp;  echo -n "$aapos "
 359&nbsp;  test $(( $Moves % $LINELEN )) -eq 0 &#38;&#38; echo
 360&nbsp;  # Print LINELEN=21 moves per line. A valid tour shows 3 complete lines.
 361&nbsp;  return $valid_moves   # Found a square to move to!
 362&nbsp;}
 363&nbsp;
 364&nbsp;
 365&nbsp;
 366&nbsp;do_move_stupid()   #  Dingbat algorithm,
 367&nbsp;{                  #+ courtesy of script author, *not* Warnsdorff.
 368&nbsp;  local valid_moves=0
 369&nbsp;  local movloc
 370&nbsp;  local squareloc
 371&nbsp;  local aapos
 372&nbsp;  local cposloc="$1"
 373&nbsp;
 374&nbsp;  for movloc in {1..8}
 375&nbsp;  do       # Move to first-found unvisited square.
 376&nbsp;    let "squareloc = $cposloc + ${moves[movloc]}"
 377&nbsp;    is_on_board $squareloc
 378&nbsp;    if [ $? -eq $SUCCESS ] &#38;&#38; [ ${board[squareloc]} -eq $UNVISITED ]
 379&nbsp;    then   # Add conditions to above if-test to improve algorithm.
 380&nbsp;      (( ++movenum ))
 381&nbsp;      board[squareloc]=$movenum
 382&nbsp;      currpos=$squareloc     # Update current position.
 383&nbsp;      ((valid_moves++));     # moves[0]=$valid_moves
 384&nbsp;      aapos=$(to_algebraic $squareloc)
 385&nbsp;      echo -n "$aapos "
 386&nbsp;      test $(( $Moves % $LINELEN )) -eq 0 &#38;&#38; echo   # Print 21 moves/line.
 387&nbsp;      return $valid_moves    # Found a square to move to!
 388&nbsp;    fi
 389&nbsp;  done
 390&nbsp;
 391&nbsp;  return $FAIL
 392&nbsp;  #  If no square found in all 8 loop iterations,
 393&nbsp;  #+ then Knight's Tour attempt ends in failure.
 394&nbsp;
 395&nbsp;  #  Dingbat algorithm will typically fail after about 30 - 40 moves,
 396&nbsp;  #+ but executes _much_ faster than Warnsdorff's in do_move() function.
 397&nbsp;}
 398&nbsp;
 399&nbsp;
 400&nbsp;
 401&nbsp;decide_move ()         #  Which move will we make?
 402&nbsp;{                      #  But, fails on startpos=37 !!!
 403&nbsp;  for mov in {1..8}
 404&nbsp;  do
 405&nbsp;    let "squarel = $currposl + ${moves[mov]}"
 406&nbsp;    is_on_board $squarel
 407&nbsp;    if [[ $? -eq $SUCCESS &#38;&#38; ${board[squarel]} -eq $UNVISITED ]]
 408&nbsp;    then   #  Find accessible square with least possible future moves.
 409&nbsp;           #  This is Warnsdorff's algorithm.
 410&nbsp;           #  What happens is that the knight wanders toward the outer edge
 411&nbsp;           #+ of the board, then pretty much spirals inward.
 412&nbsp;           #  Given two or more possible moves with same value of
 413&nbsp;           #+ least-possible-future-moves, this implementation chooses
 414&nbsp;           #+ the _first_ of those moves.
 415&nbsp;           #  This means that there is not necessarily a unique solution
 416&nbsp;           #+ for any given starting position.
 417&nbsp;
 418&nbsp;      possible_moves $squarel
 419&nbsp;      mpm=$?
 420&nbsp;      p_moves[mov]=$mpm
 421&nbsp;      
 422&nbsp;      if [ $mpm -lt $lmin ]  # If less than previous minimum ...
 423&nbsp;      then #     ^^
 424&nbsp;        lmin=$mpm            # Update minimum.
 425&nbsp;        iex=$mov             # Save index.
 426&nbsp;      fi
 427&nbsp;
 428&nbsp;    fi
 429&nbsp;  done
 430&nbsp;}
 431&nbsp;
 432&nbsp;
 433&nbsp;
 434&nbsp;decide_move_patched ()         #  Decide which move to make,
 435&nbsp;{  #        ^^^^^^^            #+ but only if startpos=37 !!!
 436&nbsp;  for mov in {1..8}
 437&nbsp;  do
 438&nbsp;    let "squarel = $currposl + ${moves[mov]}"
 439&nbsp;    is_on_board $squarel
 440&nbsp;    if [[ $? -eq $SUCCESS &#38;&#38; ${board[squarel]} -eq $UNVISITED ]]
 441&nbsp;    then
 442&nbsp;      possible_moves $squarel
 443&nbsp;      mpm=$?
 444&nbsp;      p_moves[mov]=$mpm
 445&nbsp;      
 446&nbsp;      if [ $mpm -le $lmin ]  # If less-than-or equal to prev. minimum!
 447&nbsp;      then #     ^^
 448&nbsp;        lmin=$mpm
 449&nbsp;        iex=$mov
 450&nbsp;      fi
 451&nbsp;
 452&nbsp;    fi
 453&nbsp;  done                       # There has to be a better way to do this.
 454&nbsp;}
 455&nbsp;
 456&nbsp;
 457&nbsp;
 458&nbsp;possible_moves ()            #  Calculate number of possible moves,
 459&nbsp;{                            #+ given the current position.
 460&nbsp;
 461&nbsp;  if [ -z "$1" ]
 462&nbsp;  then
 463&nbsp;    return $FAIL
 464&nbsp;  fi
 465&nbsp;
 466&nbsp;  local curr_pos=$1
 467&nbsp;  local valid_movl=0
 468&nbsp;  local icx=0
 469&nbsp;  local movl
 470&nbsp;  local sq
 471&nbsp;  declare -a movesloc
 472&nbsp;
 473&nbsp;  movesloc=( $(generate_moves $curr_pos) )
 474&nbsp;
 475&nbsp;  for movl in {1..8}
 476&nbsp;  do
 477&nbsp;    let "sq = $curr_pos + ${movesloc[movl]}"
 478&nbsp;    is_on_board $sq
 479&nbsp;    if [ $? -eq $SUCCESS ] &#38;&#38; [ ${board[sq]} -eq $UNVISITED ]
 480&nbsp;    then
 481&nbsp;      ((valid_movl++));
 482&nbsp;    fi
 483&nbsp;  done
 484&nbsp;
 485&nbsp;  return $valid_movl         # Found a square to move to!
 486&nbsp;}
 487&nbsp;
 488&nbsp;
 489&nbsp;strategy ()
 490&nbsp;{
 491&nbsp;  echo
 492&nbsp;
 493&nbsp;  if [ -n "$STUPID" ]
 494&nbsp;  then
 495&nbsp;    for Moves in {1..63}
 496&nbsp;    do
 497&nbsp;      cposl=$1
 498&nbsp;      moves=( $(generate_moves $currpos) )
 499&nbsp;      do_move_stupid "$currpos"
 500&nbsp;      if [ $? -eq $FAIL ]
 501&nbsp;      then
 502&nbsp;        failure
 503&nbsp;      fi
 504&nbsp;      done
 505&nbsp;  fi
 506&nbsp;
 507&nbsp;  #  Don't need an "else" clause here,
 508&nbsp;  #+ because Stupid Strategy will always fail and exit!
 509&nbsp;  for Moves in {1..63}
 510&nbsp;  do
 511&nbsp;    cposl=$1
 512&nbsp;    moves=( $(generate_moves $currpos) )
 513&nbsp;    do_move "$currpos"
 514&nbsp;    if [ $? -eq $FAIL ]
 515&nbsp;    then
 516&nbsp;      failure
 517&nbsp;    fi
 518&nbsp;
 519&nbsp;  done
 520&nbsp;        #  Could have condensed above two do-loops into a single one,
 521&nbsp;  echo  #+ but this would have slowed execution.
 522&nbsp;
 523&nbsp;  print_board
 524&nbsp;  echo
 525&nbsp;  echo "Knight's Tour ends on $(to_algebraic $currpos) [square #$currpos]."
 526&nbsp;  return $SUCCESS
 527&nbsp;}
 528&nbsp;
 529&nbsp;debug ()
 530&nbsp;{       # Enable this by setting DEBUG=1 near beginning of script.
 531&nbsp;  local n
 532&nbsp;
 533&nbsp;  echo "================================="
 534&nbsp;  echo "  At move number  $movenum:"
 535&nbsp;  echo " *** possible moves = $mpm ***"
 536&nbsp;# echo "### square = $square ###"
 537&nbsp;  echo "lmin = $lmin"
 538&nbsp;  echo "${moves[@]}"
 539&nbsp;
 540&nbsp;  for n in {1..8}
 541&nbsp;  do
 542&nbsp;    echo -n "($n):${p_moves[n]} "
 543&nbsp;  done
 544&nbsp;
 545&nbsp;  echo
 546&nbsp;  echo "iex = $iex :: moves[iex] = ${moves[iex]}"
 547&nbsp;  echo "square = $square"
 548&nbsp;  echo "================================="
 549&nbsp;  echo
 550&nbsp;} # Gives pretty complete status after ea. move.
 551&nbsp;
 552&nbsp;
 553&nbsp;
 554&nbsp;# =============================================================== #
 555&nbsp;# int main () {
 556&nbsp;from_algebraic "$1"
 557&nbsp;startpos=$?
 558&nbsp;if [ "$startpos" -eq "$FAIL" ]          # Okay even if no $1.
 559&nbsp;then   #         ^^^^^^^^^^^              Okay even if input -lt 0.
 560&nbsp;  echo "No starting square specified (or illegal input)."
 561&nbsp;  let "startpos = $RANDOM % $SQUARES"   # 0 - 63 permissable range.
 562&nbsp;fi
 563&nbsp;
 564&nbsp;
 565&nbsp;if [ "$2" = "stupid" ]
 566&nbsp;then
 567&nbsp;  STUPID=1
 568&nbsp;  echo -n "     ### Stupid Strategy ###"
 569&nbsp;else
 570&nbsp;  STUPID=''
 571&nbsp;  echo -n "  *** Warnsdorff's Algorithm ***"
 572&nbsp;fi
 573&nbsp;
 574&nbsp;
 575&nbsp;initialize_board
 576&nbsp;
 577&nbsp;movenum=0
 578&nbsp;board[startpos]=$movenum   # Mark each board square with move number.
 579&nbsp;currpos=$startpos
 580&nbsp;algpos=$(to_algebraic $startpos)
 581&nbsp;
 582&nbsp;echo; echo "Starting from $algpos [square #$startpos] ..."; echo
 583&nbsp;echo -n "Moves:"
 584&nbsp;
 585&nbsp;strategy "$currpos"
 586&nbsp;
 587&nbsp;echo
 588&nbsp;
 589&nbsp;exit 0   # return 0;
 590&nbsp;
 591&nbsp;# }      # End of main() pseudo-function.
 592&nbsp;# =============================================================== #
 593&nbsp;
 594&nbsp;
 595&nbsp;# Exercises:
 596&nbsp;# ---------
 597&nbsp;#
 598&nbsp;# 1) Extend this example to a 10 x 10 board or larger.
 599&nbsp;# 2) Improve the "stupid strategy" by modifying the
 600&nbsp;#    do_move_stupid function.
 601&nbsp;#    Hint: Prevent straying into corner squares in early moves
 602&nbsp;#          (the exact opposite of Warnsdorff's algorithm!).
 603&nbsp;# 3) This script could stand considerable improvement and
 604&nbsp;#    streamlining, especially in the poorly-written
 605&nbsp;#    generate_moves() function
 606&nbsp;#    and in the DECIDE-MOVE patch in the do_move() function.
 607&nbsp;#    Must figure out why standard algorithm fails for startpos=37 ...
 608&nbsp;#+   but _not_ on any other, including symmetrical startpos=26.
 609&nbsp;#    Possibly, when calculating possible moves, counts the move back
 610&nbsp;#+   to the originating square. If so, it might be a relatively easy fix.</PRE
></TD
></TR
></TABLE
><HR></DIV
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="MSQUARE"
></A
><P
><B
>Example A-46. Magic Squares</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#!/bin/bash
   2&nbsp;# msquare.sh
   3&nbsp;# Magic Square generator (odd-order squares only!)
   4&nbsp;
   5&nbsp;# Author: mendel cooper
   6&nbsp;# reldate: 19 Jan. 2009
   7&nbsp;# License: Public Domain
   8&nbsp;# A C-program by the very talented Kwon Young Shin inspired this script.
   9&nbsp;#     http://user.chollian.net/~brainstm/MagicSquare.htm
  10&nbsp;
  11&nbsp;# Definition: A "magic square" is a two-dimensional array
  12&nbsp;#             of integers in which all the rows, columns,
  13&nbsp;#             and *long* diagonals add up to the same number.
  14&nbsp;#             Being "square," the array has the same number
  15&nbsp;#             of rows and columns. That number is the "order."
  16&nbsp;# An example of a magic square of order 3 is:
  17&nbsp;#   8  1  6   
  18&nbsp;#   3  5  7   
  19&nbsp;#   4  9  2   
  20&nbsp;# All the rows, columns, and the two long diagonals add up to 15.
  21&nbsp;
  22&nbsp;
  23&nbsp;# Globals
  24&nbsp;EVEN=2
  25&nbsp;MAXSIZE=31   # 31 rows x 31 cols.
  26&nbsp;E_usage=90   # Invocation error.
  27&nbsp;dimension=
  28&nbsp;declare -i square
  29&nbsp;
  30&nbsp;usage_message ()
  31&nbsp;{
  32&nbsp;  echo "Usage: $0 order"
  33&nbsp;  echo "   ... where \"order\" (square size) is an ODD integer"
  34&nbsp;  echo "       in the range 3 - 31."
  35&nbsp;  #  Actually works for squares up to order 159,
  36&nbsp;  #+ but large squares will not display pretty-printed in a term window.
  37&nbsp;  #  Try increasing MAXSIZE, above.
  38&nbsp;  exit $E_usage
  39&nbsp;}
  40&nbsp;
  41&nbsp;
  42&nbsp;calculate ()       # Here's where the actual work gets done.
  43&nbsp;{
  44&nbsp;  local row col index dimadj j k cell_val=1
  45&nbsp;  dimension=$1
  46&nbsp;
  47&nbsp;  let "dimadj = $dimension * 3"; let "dimadj /= 2"   # x 1.5, then truncate.
  48&nbsp;
  49&nbsp;  for ((j=0; j &#60; dimension; j++))
  50&nbsp;  do
  51&nbsp;    for ((k=0; k &#60; dimension; k++))
  52&nbsp;    do  # Calculate indices, then convert to 1-dim. array index.
  53&nbsp;        # Bash doesn't support multidimensional arrays. Pity.
  54&nbsp;      let "col = $k - $j + $dimadj"; let "col %= $dimension"
  55&nbsp;      let "row = $j * 2 - $k + $dimension"; let "row %= $dimension"
  56&nbsp;      let "index = $row*($dimension) + $col"
  57&nbsp;      square[$index]=cell_val; ((cell_val++))
  58&nbsp;    done
  59&nbsp;  done
  60&nbsp;}     # Plain math, visualization not required.
  61&nbsp;
  62&nbsp;
  63&nbsp;print_square ()               # Output square, one row at a time.
  64&nbsp;{
  65&nbsp;  local row col idx d1
  66&nbsp;  let "d1 = $dimension - 1"   # Adjust for zero-indexed array.
  67&nbsp; 
  68&nbsp;  for row in $(seq 0 $d1)
  69&nbsp;  do
  70&nbsp;
  71&nbsp;    for col in $(seq 0 $d1)
  72&nbsp;    do
  73&nbsp;      let "idx = $row * $dimension + $col"
  74&nbsp;      printf "%3d " "${square[idx]}"; echo -n "  "
  75&nbsp;    done   # Displays up to 13th order neatly in 80-column term window.
  76&nbsp;
  77&nbsp;    echo   # Newline after each row.
  78&nbsp;  done
  79&nbsp;}
  80&nbsp;
  81&nbsp;
  82&nbsp;#################################################
  83&nbsp;if [[ -z "$1" ]] || [[ "$1" -gt $MAXSIZE ]]
  84&nbsp;then
  85&nbsp;  usage_message
  86&nbsp;fi
  87&nbsp;
  88&nbsp;let "test_even = $1 % $EVEN"
  89&nbsp;if [ $test_even -eq 0 ]
  90&nbsp;then           # Can't handle even-order squares.
  91&nbsp;  usage_message
  92&nbsp;fi
  93&nbsp;
  94&nbsp;calculate $1
  95&nbsp;print_square   # echo "${square[@]}"   # DEBUG
  96&nbsp;
  97&nbsp;exit $?
  98&nbsp;#################################################
  99&nbsp;
 100&nbsp;
 101&nbsp;# Exercises:
 102&nbsp;# ---------
 103&nbsp;# 1) Add a function to calculate the sum of each row, column,
 104&nbsp;#    and *long* diagonal. The sums must match.
 105&nbsp;#    This is the "magic constant" of that particular order square.
 106&nbsp;# 2) Have the print_square function auto-calculate how much space
 107&nbsp;#    to allot between square elements for optimized display.
 108&nbsp;#    This might require parameterizing the "printf" line.
 109&nbsp;# 3) Add appropriate functions for generating magic squares
 110&nbsp;#    with an *even* number of rows/columns.
 111&nbsp;#    This is non-trivial(!).
 112&nbsp;#    See the URL for Kwon Young Shin, above, for help.</PRE
></TD
></TR
></TABLE
><HR></DIV
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="FIFTEEN"
></A
><P
><B
>Example A-47. Fifteen Puzzle</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#!/bin/bash
   2&nbsp;# fifteen.sh
   3&nbsp;
   4&nbsp;# Classic "Fifteen Puzzle"
   5&nbsp;# Author: Antonio Macchi
   6&nbsp;# Lightly edited and commented by ABS Guide author.
   7&nbsp;# Used in ABS Guide with permission. (Thanks!)
   8&nbsp;
   9&nbsp;#  The invention of the Fifteen Puzzle is attributed to either
  10&nbsp;#+ Sam Loyd or Noyes Palmer Chapman.
  11&nbsp;#  The puzzle was wildly popular in the late 19th-century.
  12&nbsp;
  13&nbsp;#  Object: Rearrange the numbers so they read in order,
  14&nbsp;#+ from 1 - 15:   ________________
  15&nbsp;#                |  1   2   3   4 |
  16&nbsp;#                |  5   6   7   8 |
  17&nbsp;#                |  9  10  11  12 |
  18&nbsp;#                | 13  14  15     |
  19&nbsp;#                 ----------------
  20&nbsp;
  21&nbsp;
  22&nbsp;#######################
  23&nbsp;# Constants           #
  24&nbsp;  SQUARES=16          #
  25&nbsp;  FAIL=70             #
  26&nbsp;  E_PREMATURE_EXIT=80 #
  27&nbsp;#######################
  28&nbsp;
  29&nbsp;
  30&nbsp;########
  31&nbsp;# Data #
  32&nbsp;########
  33&nbsp;
  34&nbsp;Puzzle=( 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 " " )
  35&nbsp;
  36&nbsp;
  37&nbsp;#############
  38&nbsp;# Functions #
  39&nbsp;#############
  40&nbsp;
  41&nbsp;function swap
  42&nbsp;{
  43&nbsp;  local tmp
  44&nbsp;
  45&nbsp;  tmp=${Puzzle[$1]}
  46&nbsp;  Puzzle[$1]=${Puzzle[$2]}
  47&nbsp;  Puzzle[$2]=$tmp
  48&nbsp;}
  49&nbsp;
  50&nbsp;
  51&nbsp;function Jumble
  52&nbsp;{ # Scramble the pieces at beginning of round.
  53&nbsp;  local i pos1 pos2
  54&nbsp;
  55&nbsp;  for i in {1..100}
  56&nbsp;  do
  57&nbsp;    pos1=$(( $RANDOM % $SQUARES))
  58&nbsp;    pos2=$(( $RANDOM % $SQUARES ))
  59&nbsp;    swap $pos1 $pos2
  60&nbsp;  done
  61&nbsp;}
  62&nbsp;
  63&nbsp;
  64&nbsp;function PrintPuzzle
  65&nbsp;{
  66&nbsp;  local i1 i2 puzpos
  67&nbsp;  puzpos=0
  68&nbsp;
  69&nbsp;  clear
  70&nbsp;  echo "Enter  quit  to exit."; echo   # Better that than Ctl-C.
  71&nbsp;
  72&nbsp;  echo ",----.----.----.----."   # Top border.
  73&nbsp;  for i1 in {1..4}
  74&nbsp;  do
  75&nbsp;    for i2 in {1..4} 
  76&nbsp;    do
  77&nbsp;      printf "| %2s " "${Puzzle[$puzpos]}"
  78&nbsp;      (( puzpos++ ))
  79&nbsp;    done
  80&nbsp;    echo "|"                     # Right-side border.
  81&nbsp;    test $i1 = 4 || echo "+----+----+----+----+"
  82&nbsp;  done
  83&nbsp;  echo "'----'----'----'----'"   # Bottom border.
  84&nbsp;}
  85&nbsp;
  86&nbsp;
  87&nbsp;function GetNum
  88&nbsp;{ # Test for valid input.
  89&nbsp;  local puznum garbage
  90&nbsp;
  91&nbsp;  while true
  92&nbsp;  do 
  93&nbsp;	  echo "Moves: $moves" # Also counts invalid moves.
  94&nbsp;    read -p "Number to move: " puznum garbage
  95&nbsp;      if [ "$puznum" = "quit" ]; then echo; exit $E_PREMATURE_EXIT; fi
  96&nbsp;    test -z "$puznum" -o -n "${puznum//[0-9]/}" &#38;&#38; continue
  97&nbsp;    test $puznum -gt 0 -a $puznum -lt $SQUARES &#38;&#38; break
  98&nbsp;  done
  99&nbsp;  return $puznum
 100&nbsp;}
 101&nbsp;
 102&nbsp;
 103&nbsp;function GetPosFromNum
 104&nbsp;{ # $1 = puzzle-number
 105&nbsp;  local puzpos
 106&nbsp;
 107&nbsp;  for puzpos in {0..15}
 108&nbsp;  do
 109&nbsp;    test "${Puzzle[$puzpos]}" = "$1" &#38;&#38; break
 110&nbsp;  done
 111&nbsp;  return $puzpos
 112&nbsp;}
 113&nbsp;
 114&nbsp;
 115&nbsp;function Move
 116&nbsp;{ # $1=Puzzle-pos
 117&nbsp;  test $1 -gt 3 &#38;&#38; test "${Puzzle[$(( $1 - 4 ))]}" = " "\
 118&nbsp;       &#38;&#38; swap $1 $(( $1 - 4 )) &#38;&#38; return 0
 119&nbsp;  test $(( $1%4 )) -ne 3 &#38;&#38; test "${Puzzle[$(( $1 + 1 ))]}" = " "\
 120&nbsp;       &#38;&#38; swap $1 $(( $1 + 1 )) &#38;&#38; return 0
 121&nbsp;  test $1 -lt 12 &#38;&#38; test "${Puzzle[$(( $1 + 4 ))]}" = " "\
 122&nbsp;       &#38;&#38; swap $1 $(( $1 + 4 )) &#38;&#38; return 0
 123&nbsp;  test $(( $1%4 )) -ne 0 &#38;&#38; test "${Puzzle[$(( $1 - 1 ))]}" = " " &#38;&#38;\
 124&nbsp;       swap $1 $(( $1 - 1 )) &#38;&#38; return 0
 125&nbsp;  return 1
 126&nbsp;}
 127&nbsp;
 128&nbsp;
 129&nbsp;function Solved
 130&nbsp;{
 131&nbsp;  local pos
 132&nbsp;
 133&nbsp;  for pos in {0..14}
 134&nbsp;  do
 135&nbsp;    test "${Puzzle[$pos]}" = $(( $pos + 1 )) || return $FAIL
 136&nbsp;    # Check whether number in each square = square number.
 137&nbsp;  done
 138&nbsp;  return 0   # Successful solution.
 139&nbsp;}
 140&nbsp;
 141&nbsp;
 142&nbsp;################### MAIN () #######################{
 143&nbsp;moves=0
 144&nbsp;Jumble
 145&nbsp;
 146&nbsp;while true   # Loop continuously until puzzle solved.
 147&nbsp;do
 148&nbsp;  echo; echo
 149&nbsp;  PrintPuzzle
 150&nbsp;  echo
 151&nbsp;  while true
 152&nbsp;  do
 153&nbsp;    GetNum
 154&nbsp;    puznum=$?
 155&nbsp;    GetPosFromNum $puznum
 156&nbsp;    puzpos=$?
 157&nbsp;    ((moves++))
 158&nbsp;    Move $puzpos &#38;&#38; break
 159&nbsp;  done
 160&nbsp;  Solved &#38;&#38; break
 161&nbsp;done
 162&nbsp;
 163&nbsp;echo;echo
 164&nbsp;PrintPuzzle
 165&nbsp;echo; echo "BRAVO!"; echo
 166&nbsp;
 167&nbsp;exit 0
 168&nbsp;###################################################}
 169&nbsp;
 170&nbsp;#  Exercise:
 171&nbsp;#  --------
 172&nbsp;#  Rewrite the script to display the letters A - O,
 173&nbsp;#+ rather than the numbers 1 - 15.</PRE
></TD
></TR
></TABLE
><HR></DIV
><P
><A
NAME="HANOI2REF"
></A
></P
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="HANOI2"
></A
><P
><B
>Example A-48. <I
CLASS="FIRSTTERM"
>The Towers of Hanoi, graphic
	        version</I
></B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#! /bin/bash
   2&nbsp;# The Towers Of Hanoi
   3&nbsp;# Original script (hanoi.bash) copyright (C) 2000 Amit Singh.
   4&nbsp;# All Rights Reserved.
   5&nbsp;# http://hanoi.kernelthread.com
   6&nbsp;
   7&nbsp;#  hanoi2.bash
   8&nbsp;#  Version 2.00: modded for ASCII-graphic display.
   9&nbsp;#  Version 2.01: fixed no command-line param bug.
  10&nbsp;#  Uses code contributed by Antonio Macchi,
  11&nbsp;#+ with heavy editing by ABS Guide author.
  12&nbsp;#  This variant falls under the original copyright, see above.
  13&nbsp;#  Used in ABS Guide with Amit Singh's permission (thanks!).
  14&nbsp;
  15&nbsp;
  16&nbsp;###   Variables &#38;&#38; sanity check   ###
  17&nbsp;
  18&nbsp;E_NOPARAM=86
  19&nbsp;E_BADPARAM=87            # Illegal no. of disks passed to script.
  20&nbsp;E_NOEXIT=88
  21&nbsp;
  22&nbsp;DISKS=${1:-$E_NOPARAM}   # Must specify how many disks.
  23&nbsp;Moves=0
  24&nbsp;
  25&nbsp;MWIDTH=7
  26&nbsp;MARGIN=2
  27&nbsp;# Arbitrary "magic" constants; work okay for relatively small # of disks.
  28&nbsp;# BASEWIDTH=51   # Original code.
  29&nbsp;let "basewidth = $MWIDTH * $DISKS + $MARGIN"       # "Base" beneath rods.
  30&nbsp;# Above "algorithm" could likely stand improvement.
  31&nbsp;
  32&nbsp;###   Display variables   ###
  33&nbsp;let "disks1 = $DISKS - 1"
  34&nbsp;let "spaces1 = $DISKS" 
  35&nbsp;let "spaces2 = 2 * $DISKS" 
  36&nbsp;
  37&nbsp;let "lastmove_t = $DISKS - 1"                      # Final move?
  38&nbsp;
  39&nbsp;
  40&nbsp;declare -a Rod1 Rod2 Rod3
  41&nbsp;
  42&nbsp;###   #########################   ###
  43&nbsp;
  44&nbsp;
  45&nbsp;function repeat  {  # $1=char $2=number of repetitions
  46&nbsp;  local n           # Repeat-print a character.
  47&nbsp;  
  48&nbsp;  for (( n=0; n&#60;$2; n++ )); do
  49&nbsp;    echo -n "$1"
  50&nbsp;  done
  51&nbsp;}
  52&nbsp;
  53&nbsp;function FromRod  {
  54&nbsp;  local rod summit weight sequence
  55&nbsp;
  56&nbsp;  while true; do
  57&nbsp;    rod=$1
  58&nbsp;    test ${rod/[^123]/} || continue
  59&nbsp;
  60&nbsp;    sequence=$(echo $(seq 0 $disks1 | tac))
  61&nbsp;    for summit in $sequence; do
  62&nbsp;      eval weight=\${Rod${rod}[$summit]}
  63&nbsp;      test $weight -ne 0 &#38;&#38;
  64&nbsp;           { echo "$rod $summit $weight"; return; }
  65&nbsp;    done
  66&nbsp;  done
  67&nbsp;}
  68&nbsp;
  69&nbsp;
  70&nbsp;function ToRod  { # $1=previous (FromRod) weight
  71&nbsp;  local rod firstfree weight sequence
  72&nbsp;  
  73&nbsp;  while true; do
  74&nbsp;    rod=$2
  75&nbsp;    test ${rod/[^123]} || continue
  76&nbsp;
  77&nbsp;    sequence=$(echo $(seq 0 $disks1 | tac))
  78&nbsp;    for firstfree in $sequence; do
  79&nbsp;      eval weight=\${Rod${rod}[$firstfree]}
  80&nbsp;      test $weight -gt 0 &#38;&#38; { (( firstfree++ )); break; }
  81&nbsp;    done
  82&nbsp;    test $weight -gt $1 -o $firstfree = 0 &#38;&#38;
  83&nbsp;         { echo "$rod $firstfree"; return; }
  84&nbsp;  done
  85&nbsp;}
  86&nbsp;
  87&nbsp;
  88&nbsp;function PrintRods  {
  89&nbsp;  local disk rod empty fill sp sequence
  90&nbsp;
  91&nbsp;
  92&nbsp;  repeat " " $spaces1
  93&nbsp;  echo -n "|"
  94&nbsp;  repeat " " $spaces2
  95&nbsp;  echo -n "|"
  96&nbsp;  repeat " " $spaces2
  97&nbsp;  echo "|"
  98&nbsp;
  99&nbsp;  sequence=$(echo $(seq 0 $disks1 | tac))
 100&nbsp;  for disk in $sequence; do
 101&nbsp;    for rod in {1..3}; do
 102&nbsp;      eval empty=$(( $DISKS - (Rod${rod}[$disk] / 2) ))
 103&nbsp;      eval fill=\${Rod${rod}[$disk]}
 104&nbsp;      repeat " " $empty
 105&nbsp;      test $fill -gt 0 &#38;&#38; repeat "*" $fill || echo -n "|"
 106&nbsp;      repeat " " $empty
 107&nbsp;    done
 108&nbsp;    echo
 109&nbsp;  done
 110&nbsp;  repeat "=" $basewidth   # Print "base" beneath rods.
 111&nbsp;  echo
 112&nbsp;}
 113&nbsp;
 114&nbsp;
 115&nbsp;display ()
 116&nbsp;{
 117&nbsp;  echo
 118&nbsp;  PrintRods
 119&nbsp;
 120&nbsp;  # Get rod-number, summit and weight
 121&nbsp;  first=( `FromRod $1` )
 122&nbsp;  eval Rod${first[0]}[${first[1]}]=0
 123&nbsp;
 124&nbsp;  # Get rod-number and first-free position
 125&nbsp;  second=( `ToRod ${first[2]} $2` )
 126&nbsp;  eval Rod${second[0]}[${second[1]}]=${first[2]}
 127&nbsp;
 128&nbsp;
 129&nbsp;echo; echo; echo
 130&nbsp;if [ "${Rod3[lastmove_t]}" = 1 ]
 131&nbsp;then   # Last move? If yes, then display final position.
 132&nbsp;    echo "+  Final Position: $Moves moves"; echo
 133&nbsp;    PrintRods
 134&nbsp;  fi
 135&nbsp;}
 136&nbsp;
 137&nbsp;
 138&nbsp;# From here down, almost the same as original (hanoi.bash) script.
 139&nbsp;
 140&nbsp;dohanoi() {   # Recursive function.
 141&nbsp;    case $1 in
 142&nbsp;    0)
 143&nbsp;        ;;
 144&nbsp;    *)
 145&nbsp;        dohanoi "$(($1-1))" $2 $4 $3
 146&nbsp;	if [ "$Moves" -ne 0 ]
 147&nbsp;        then
 148&nbsp;	  echo "+  Position after move $Moves"
 149&nbsp;        fi
 150&nbsp;        ((Moves++))
 151&nbsp;        echo -n "   Next move will be:  "
 152&nbsp;        echo $2 "--&#62;" $3
 153&nbsp;          display $2 $3
 154&nbsp;        dohanoi "$(($1-1))" $4 $3 $2
 155&nbsp;        ;;
 156&nbsp;    esac
 157&nbsp;}
 158&nbsp;
 159&nbsp;
 160&nbsp;setup_arrays ()
 161&nbsp;{
 162&nbsp;  local dim n elem
 163&nbsp;
 164&nbsp;  let "dim1 = $1 - 1"
 165&nbsp;  elem=$dim1
 166&nbsp;
 167&nbsp;  for n in $(seq 0 $dim1)
 168&nbsp;  do
 169&nbsp;   let "Rod1[$elem] = 2 * $n + 1"
 170&nbsp;   Rod2[$n]=0
 171&nbsp;   Rod3[$n]=0
 172&nbsp;   ((elem--))
 173&nbsp;  done
 174&nbsp;}
 175&nbsp;
 176&nbsp;
 177&nbsp;###   Main   ###
 178&nbsp;
 179&nbsp;setup_arrays $DISKS
 180&nbsp;echo; echo "+  Start Position"
 181&nbsp;
 182&nbsp;case $# in
 183&nbsp;    1) case $(($1&#62;0)) in     # Must have at least one disk.
 184&nbsp;       1)
 185&nbsp;           disks=$1
 186&nbsp;           dohanoi $1 1 3 2
 187&nbsp;#          Total moves = 2^n - 1, where n = number of disks.
 188&nbsp;	   echo
 189&nbsp;           exit 0;
 190&nbsp;           ;;
 191&nbsp;       *)
 192&nbsp;           echo "$0: Illegal value for number of disks";
 193&nbsp;           exit $E_BADPARAM;
 194&nbsp;           ;;
 195&nbsp;       esac
 196&nbsp;    ;;
 197&nbsp;    *)
 198&nbsp;       clear
 199&nbsp;       echo "usage: $0 N"
 200&nbsp;       echo "       Where \"N\" is the number of disks."
 201&nbsp;       exit $E_NOPARAM;
 202&nbsp;       ;;
 203&nbsp;esac
 204&nbsp;
 205&nbsp;exit $E_NOEXIT   # Shouldn't exit here.
 206&nbsp;
 207&nbsp;# Note:
 208&nbsp;# Redirect script output to a file, otherwise it scrolls off display.</PRE
></TD
></TR
></TABLE
><HR></DIV
><P
><A
NAME="HANOI2AREF"
></A
></P
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="HANOI2A"
></A
><P
><B
>Example A-49. <I
CLASS="FIRSTTERM"
>The Towers of Hanoi, alternate graphic
	        version</I
></B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#! /bin/bash
   2&nbsp;# The Towers Of Hanoi
   3&nbsp;# Original script (hanoi.bash) copyright (C) 2000 Amit Singh.
   4&nbsp;# All Rights Reserved.
   5&nbsp;# http://hanoi.kernelthread.com
   6&nbsp;
   7&nbsp;#  hanoi2.bash
   8&nbsp;#  Version 2: modded for ASCII-graphic display.
   9&nbsp;#  Uses code contributed by Antonio Macchi,
  10&nbsp;#+ with heavy editing by ABS Guide author.
  11&nbsp;#  This variant also falls under the original copyright, see above.
  12&nbsp;#  Used in ABS Guide with Amit Singh's permission (thanks!).
  13&nbsp;
  14&nbsp;
  15&nbsp;#   Variables   #
  16&nbsp;E_NOPARAM=86
  17&nbsp;E_BADPARAM=87   # Illegal no. of disks passed to script.
  18&nbsp;E_NOEXIT=88
  19&nbsp;DELAY=2         # Interval, in seconds, between moves. Change, if desired.
  20&nbsp;DISKS=$1
  21&nbsp;Moves=0
  22&nbsp;
  23&nbsp;MWIDTH=7
  24&nbsp;MARGIN=2
  25&nbsp;# Arbitrary "magic" constants, work okay for relatively small # of disks.
  26&nbsp;# BASEWIDTH=51   # Original code.
  27&nbsp;let "basewidth = $MWIDTH * $DISKS + $MARGIN" # "Base" beneath rods.
  28&nbsp;# Above "algorithm" could likely stand improvement.
  29&nbsp;
  30&nbsp;# Display variables.
  31&nbsp;let "disks1 = $DISKS - 1"
  32&nbsp;let "spaces1 = $DISKS" 
  33&nbsp;let "spaces2 = 2 * $DISKS" 
  34&nbsp;
  35&nbsp;let "lastmove_t = $DISKS - 1"                # Final move?
  36&nbsp;
  37&nbsp;
  38&nbsp;declare -a Rod1 Rod2 Rod3
  39&nbsp;
  40&nbsp;#################
  41&nbsp;
  42&nbsp;
  43&nbsp;function repeat  {  # $1=char $2=number of repetitions
  44&nbsp;  local n           # Repeat-print a character.
  45&nbsp;  
  46&nbsp;  for (( n=0; n&#60;$2; n++ )); do
  47&nbsp;    echo -n "$1"
  48&nbsp;  done
  49&nbsp;}
  50&nbsp;
  51&nbsp;function FromRod  {
  52&nbsp;  local rod summit weight sequence
  53&nbsp;
  54&nbsp;  while true; do
  55&nbsp;    rod=$1
  56&nbsp;    test ${rod/[^123]/} || continue
  57&nbsp;
  58&nbsp;    sequence=$(echo $(seq 0 $disks1 | tac))
  59&nbsp;    for summit in $sequence; do
  60&nbsp;      eval weight=\${Rod${rod}[$summit]}
  61&nbsp;      test $weight -ne 0 &#38;&#38;
  62&nbsp;           { echo "$rod $summit $weight"; return; }
  63&nbsp;    done
  64&nbsp;  done
  65&nbsp;}
  66&nbsp;
  67&nbsp;
  68&nbsp;function ToRod  { # $1=previous (FromRod) weight
  69&nbsp;  local rod firstfree weight sequence
  70&nbsp;  
  71&nbsp;  while true; do
  72&nbsp;    rod=$2
  73&nbsp;    test ${rod/[^123]} || continue
  74&nbsp;
  75&nbsp;    sequence=$(echo $(seq 0 $disks1 | tac))
  76&nbsp;    for firstfree in $sequence; do
  77&nbsp;      eval weight=\${Rod${rod}[$firstfree]}
  78&nbsp;      test $weight -gt 0 &#38;&#38; { (( firstfree++ )); break; }
  79&nbsp;    done
  80&nbsp;    test $weight -gt $1 -o $firstfree = 0 &#38;&#38;
  81&nbsp;         { echo "$rod $firstfree"; return; }
  82&nbsp;  done
  83&nbsp;}
  84&nbsp;
  85&nbsp;
  86&nbsp;function PrintRods  {
  87&nbsp;  local disk rod empty fill sp sequence
  88&nbsp;
  89&nbsp;  tput cup 5 0
  90&nbsp;
  91&nbsp;  repeat " " $spaces1
  92&nbsp;  echo -n "|"
  93&nbsp;  repeat " " $spaces2
  94&nbsp;  echo -n "|"
  95&nbsp;  repeat " " $spaces2
  96&nbsp;  echo "|"
  97&nbsp;
  98&nbsp;  sequence=$(echo $(seq 0 $disks1 | tac))
  99&nbsp;  for disk in $sequence; do
 100&nbsp;    for rod in {1..3}; do
 101&nbsp;      eval empty=$(( $DISKS - (Rod${rod}[$disk] / 2) ))
 102&nbsp;      eval fill=\${Rod${rod}[$disk]}
 103&nbsp;      repeat " " $empty
 104&nbsp;      test $fill -gt 0 &#38;&#38; repeat "*" $fill || echo -n "|"
 105&nbsp;      repeat " " $empty
 106&nbsp;    done
 107&nbsp;    echo
 108&nbsp;  done
 109&nbsp;  repeat "=" $basewidth   # Print "base" beneath rods.
 110&nbsp;  echo
 111&nbsp;}
 112&nbsp;
 113&nbsp;
 114&nbsp;display ()
 115&nbsp;{
 116&nbsp;  echo
 117&nbsp;  PrintRods
 118&nbsp;
 119&nbsp;  # Get rod-number, summit and weight
 120&nbsp;  first=( `FromRod $1` )
 121&nbsp;  eval Rod${first[0]}[${first[1]}]=0
 122&nbsp;
 123&nbsp;  # Get rod-number and first-free position
 124&nbsp;  second=( `ToRod ${first[2]} $2` )
 125&nbsp;  eval Rod${second[0]}[${second[1]}]=${first[2]}
 126&nbsp;
 127&nbsp;
 128&nbsp;  if [ "${Rod3[lastmove_t]}" = 1 ]
 129&nbsp;  then   # Last move? If yes, then display final position.
 130&nbsp;    tput cup 0 0
 131&nbsp;    echo; echo "+  Final Position: $Moves moves"
 132&nbsp;    PrintRods
 133&nbsp;  fi
 134&nbsp;
 135&nbsp;  sleep $DELAY
 136&nbsp;}
 137&nbsp;
 138&nbsp;# From here down, almost the same as original (hanoi.bash) script.
 139&nbsp;
 140&nbsp;dohanoi() {   # Recursive function.
 141&nbsp;    case $1 in
 142&nbsp;    0)
 143&nbsp;        ;;
 144&nbsp;    *)
 145&nbsp;        dohanoi "$(($1-1))" $2 $4 $3
 146&nbsp;	if [ "$Moves" -ne 0 ]
 147&nbsp;        then
 148&nbsp;	  tput cup 0 0
 149&nbsp;	  echo; echo "+  Position after move $Moves"
 150&nbsp;        fi
 151&nbsp;        ((Moves++))
 152&nbsp;        echo -n "   Next move will be:  "
 153&nbsp;        echo $2 "--&#62;" $3
 154&nbsp;        display $2 $3
 155&nbsp;        dohanoi "$(($1-1))" $4 $3 $2
 156&nbsp;        ;;
 157&nbsp;    esac
 158&nbsp;}
 159&nbsp;
 160&nbsp;setup_arrays ()
 161&nbsp;{
 162&nbsp;  local dim n elem
 163&nbsp;
 164&nbsp;  let "dim1 = $1 - 1"
 165&nbsp;  elem=$dim1
 166&nbsp;
 167&nbsp;  for n in $(seq 0 $dim1)
 168&nbsp;  do
 169&nbsp;   let "Rod1[$elem] = 2 * $n + 1"
 170&nbsp;   Rod2[$n]=0
 171&nbsp;   Rod3[$n]=0
 172&nbsp;   ((elem--))
 173&nbsp;  done
 174&nbsp;}
 175&nbsp;
 176&nbsp;
 177&nbsp;###   Main   ###
 178&nbsp;
 179&nbsp;trap "tput cnorm" 0
 180&nbsp;tput civis
 181&nbsp;clear
 182&nbsp;
 183&nbsp;setup_arrays $DISKS
 184&nbsp;
 185&nbsp;tput cup 0 0
 186&nbsp;echo; echo "+  Start Position"
 187&nbsp;
 188&nbsp;case $# in
 189&nbsp;    1) case $(($1&#62;0)) in     # Must have at least one disk.
 190&nbsp;       1)
 191&nbsp;           disks=$1
 192&nbsp;           dohanoi $1 1 3 2
 193&nbsp;#          Total moves = 2^n - 1, where n = # of disks.
 194&nbsp;	   echo
 195&nbsp;           exit 0;
 196&nbsp;           ;;
 197&nbsp;       *)
 198&nbsp;           echo "$0: Illegal value for number of disks";
 199&nbsp;           exit $E_BADPARAM;
 200&nbsp;           ;;
 201&nbsp;       esac
 202&nbsp;    ;;
 203&nbsp;    *)
 204&nbsp;       echo "usage: $0 N"
 205&nbsp;       echo "       Where \"N\" is the number of disks."
 206&nbsp;       exit $E_NOPARAM;
 207&nbsp;       ;;
 208&nbsp;esac
 209&nbsp;
 210&nbsp;exit $E_NOEXIT   # Shouldn't exit here.
 211&nbsp;
 212&nbsp;#  Exercise:
 213&nbsp;#  --------
 214&nbsp;#  There is a minor bug in the script that causes the display of
 215&nbsp;#+ the next-to-last move to be skipped.
 216&nbsp;#+ Fix this.</PRE
></TD
></TR
></TABLE
><HR></DIV
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="USEGETOPT"
></A
><P
><B
>Example A-50. An alternate version of the
      <A
HREF="manipulatingvars.html#GETOPTSIMPLE"
>getopt-simple.sh</A
> script</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#!/bin/bash
   2&nbsp;# UseGetOpt.sh
   3&nbsp;
   4&nbsp;# Author: Peggy Russell &#60;prusselltechgroup@gmail.com&#62;
   5&nbsp;
   6&nbsp;UseGetOpt () {
   7&nbsp;  declare inputOptions
   8&nbsp;  declare -r E_OPTERR=85
   9&nbsp;  declare -r ScriptName=${0##*/}
  10&nbsp;  declare -r ShortOpts="adf:hlt"
  11&nbsp;  declare -r LongOpts="aoption,debug,file:,help,log,test"
  12&nbsp;
  13&nbsp;DoSomething () {
  14&nbsp;    echo "The function name is '${FUNCNAME}'"
  15&nbsp;    #  Recall that $FUNCNAME is an internal variable
  16&nbsp;    #+ holding the name of the function it is in.
  17&nbsp;  }
  18&nbsp;
  19&nbsp;  inputOptions=$(getopt -o "${ShortOpts}" --long \
  20&nbsp;              "${LongOpts}" --name "${ScriptName}" -- "${@}")
  21&nbsp;
  22&nbsp;  if [[ ($? -ne 0) || ($# -eq 0) ]]; then
  23&nbsp;    echo "Usage: ${ScriptName} [-dhlt] {OPTION...}"
  24&nbsp;    exit $E_OPTERR
  25&nbsp;  fi
  26&nbsp;
  27&nbsp;  eval set -- "${inputOptions}"
  28&nbsp;
  29&nbsp;  # Only for educational purposes. Can be removed.
  30&nbsp;  #-----------------------------------------------
  31&nbsp;  echo "++ Test: Number of arguments: [$#]"
  32&nbsp;  echo '++ Test: Looping through "$@"'
  33&nbsp;  for a in "$@"; do
  34&nbsp;    echo "  ++ [$a]"
  35&nbsp;  done
  36&nbsp;  #-----------------------------------------------
  37&nbsp;
  38&nbsp;  while true; do
  39&nbsp;    case "${1}" in
  40&nbsp;      --aoption | -a)  # Argument found.
  41&nbsp;        echo "Option [$1]"
  42&nbsp;        ;;
  43&nbsp;
  44&nbsp;      --debug | -d)    # Enable informational messages.
  45&nbsp;        echo "Option [$1] Debugging enabled"
  46&nbsp;        ;;
  47&nbsp;
  48&nbsp;      --file | -f)     #  Check for optional argument.
  49&nbsp;        case "$2" in   #+ Double colon is optional argument.
  50&nbsp;          "")          #  Not there.
  51&nbsp;              echo "Option [$1] Use default"
  52&nbsp;              shift
  53&nbsp;              ;;
  54&nbsp;
  55&nbsp;          *) # Got it
  56&nbsp;             echo "Option [$1] Using input [$2]"
  57&nbsp;             shift
  58&nbsp;             ;;
  59&nbsp;
  60&nbsp;        esac
  61&nbsp;        DoSomething
  62&nbsp;        ;;
  63&nbsp;
  64&nbsp;      --log | -l) # Enable Logging.
  65&nbsp;        echo "Option [$1] Logging enabled"
  66&nbsp;        ;;
  67&nbsp;
  68&nbsp;      --test | -t) # Enable testing.
  69&nbsp;        echo "Option [$1] Testing enabled"
  70&nbsp;        ;;
  71&nbsp;
  72&nbsp;      --help | -h)
  73&nbsp;        echo "Option [$1] Display help"
  74&nbsp;        break
  75&nbsp;        ;;
  76&nbsp;
  77&nbsp;      --)   # Done! $# is argument number for "--", $@ is "--"
  78&nbsp;        echo "Option [$1] Dash Dash"
  79&nbsp;        break
  80&nbsp;        ;;
  81&nbsp;
  82&nbsp;       *)
  83&nbsp;        echo "Major internal error!"
  84&nbsp;        exit 8
  85&nbsp;        ;;
  86&nbsp;
  87&nbsp;    esac
  88&nbsp;    echo "Number of arguments: [$#]"
  89&nbsp;    shift
  90&nbsp;  done
  91&nbsp;
  92&nbsp;  shift
  93&nbsp;  # Only for educational purposes. Can be removed.
  94&nbsp;  #----------------------------------------------------------------------
  95&nbsp;  echo "++ Test: Number of arguments after \"--\" is [$#] They are: [$@]"
  96&nbsp;  echo '++ Test: Looping through "$@"'
  97&nbsp;  for a in "$@"; do
  98&nbsp;    echo "  ++ [$a]"
  99&nbsp;  done
 100&nbsp;  #----------------------------------------------------------------------
 101&nbsp;  
 102&nbsp;}
 103&nbsp;
 104&nbsp;################################### M A I N ########################
 105&nbsp;#  If you remove "function UseGetOpt () {" and corresponding "}",
 106&nbsp;#+ you can uncomment the "exit 0" line below, and invoke this script
 107&nbsp;#+ with the various options from the command-line.
 108&nbsp;#-------------------------------------------------------------------
 109&nbsp;# exit 0
 110&nbsp;
 111&nbsp;echo "Test 1"
 112&nbsp;UseGetOpt -f myfile one "two three" four
 113&nbsp;
 114&nbsp;echo;echo "Test 2"
 115&nbsp;UseGetOpt -h
 116&nbsp;
 117&nbsp;echo;echo "Test 3 - Short Options"
 118&nbsp;UseGetOpt -adltf myfile  anotherfile
 119&nbsp;
 120&nbsp;echo;echo "Test 4 - Long Options"
 121&nbsp;UseGetOpt --aoption --debug --log --test --file myfile anotherfile
 122&nbsp;
 123&nbsp;exit</PRE
></TD
></TR
></TABLE
><HR></DIV
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="USEGETOPT2"
></A
><P
><B
>Example A-51. The version of the
      <I
CLASS="FIRSTTERM"
>UseGetOpt.sh</I
> example used in the <A
HREF="tabexpansion.html"
>Tab Expansion appendix</A
></B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#!/bin/bash
   2&nbsp;
   3&nbsp;#  UseGetOpt-2.sh
   4&nbsp;#  Modified version of the script for illustrating tab-expansion
   5&nbsp;#+ of command-line options.
   6&nbsp;#  See the "Introduction to Tab Expansion" appendix.
   7&nbsp;
   8&nbsp;#  Possible options: -a -d -f -l -t -h
   9&nbsp;#+                   --aoption, --debug --file --log --test -- help --
  10&nbsp;
  11&nbsp;#  Author of original script: Peggy Russell &#60;prusselltechgroup@gmail.com&#62;
  12&nbsp;
  13&nbsp;
  14&nbsp;# UseGetOpt () {
  15&nbsp;  declare inputOptions
  16&nbsp;  declare -r E_OPTERR=85
  17&nbsp;  declare -r ScriptName=${0##*/}
  18&nbsp;  declare -r ShortOpts="adf:hlt"
  19&nbsp;  declare -r LongOpts="aoption,debug,file:,help,log,test"
  20&nbsp;
  21&nbsp;DoSomething () {
  22&nbsp;    echo "The function name is '${FUNCNAME}'"
  23&nbsp;  }
  24&nbsp;
  25&nbsp;  inputOptions=$(getopt -o "${ShortOpts}" --long \
  26&nbsp;              "${LongOpts}" --name "${ScriptName}" -- "${@}")
  27&nbsp;
  28&nbsp;  if [[ ($? -ne 0) || ($# -eq 0) ]]; then
  29&nbsp;    echo "Usage: ${ScriptName} [-dhlt] {OPTION...}"
  30&nbsp;    exit $E_OPTERR
  31&nbsp;  fi
  32&nbsp;
  33&nbsp;  eval set -- "${inputOptions}"
  34&nbsp;
  35&nbsp;
  36&nbsp;  while true; do
  37&nbsp;    case "${1}" in
  38&nbsp;      --aoption | -a)  # Argument found.
  39&nbsp;        echo "Option [$1]"
  40&nbsp;        ;;
  41&nbsp;
  42&nbsp;      --debug | -d)    # Enable informational messages.
  43&nbsp;        echo "Option [$1] Debugging enabled"
  44&nbsp;        ;;
  45&nbsp;
  46&nbsp;      --file | -f)     #  Check for optional argument.
  47&nbsp;        case "$2" in   #+ Double colon is optional argument.
  48&nbsp;          "")          #  Not there.
  49&nbsp;              echo "Option [$1] Use default"
  50&nbsp;              shift
  51&nbsp;              ;;
  52&nbsp;
  53&nbsp;          *) # Got it
  54&nbsp;             echo "Option [$1] Using input [$2]"
  55&nbsp;             shift
  56&nbsp;             ;;
  57&nbsp;
  58&nbsp;        esac
  59&nbsp;        DoSomething
  60&nbsp;        ;;
  61&nbsp;
  62&nbsp;      --log | -l) # Enable Logging.
  63&nbsp;        echo "Option [$1] Logging enabled"
  64&nbsp;        ;;
  65&nbsp;
  66&nbsp;      --test | -t) # Enable testing.
  67&nbsp;        echo "Option [$1] Testing enabled"
  68&nbsp;        ;;
  69&nbsp;
  70&nbsp;      --help | -h)
  71&nbsp;        echo "Option [$1] Display help"
  72&nbsp;        break
  73&nbsp;        ;;
  74&nbsp;
  75&nbsp;      --)   # Done! $# is argument number for "--", $@ is "--"
  76&nbsp;        echo "Option [$1] Dash Dash"
  77&nbsp;        break
  78&nbsp;        ;;
  79&nbsp;
  80&nbsp;       *)
  81&nbsp;        echo "Major internal error!"
  82&nbsp;        exit 8
  83&nbsp;        ;;
  84&nbsp;
  85&nbsp;    esac
  86&nbsp;    echo "Number of arguments: [$#]"
  87&nbsp;    shift
  88&nbsp;  done
  89&nbsp;
  90&nbsp;  shift
  91&nbsp;  
  92&nbsp;#  }
  93&nbsp;
  94&nbsp;exit</PRE
></TD
></TR
></TABLE
><HR></DIV
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="SHOWALLC"
></A
><P
><B
>Example A-52. Cycling through all the possible color backgrounds</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#!/bin/bash
   2&nbsp;
   3&nbsp;# show-all-colors.sh
   4&nbsp;# Displays all 256 possible background colors, using ANSI escape sequences.
   5&nbsp;# Author: Chetankumar Phulpagare
   6&nbsp;# Used in ABS Guide with permission.
   7&nbsp;
   8&nbsp;T1=8
   9&nbsp;T2=6
  10&nbsp;T3=36
  11&nbsp;offset=0
  12&nbsp;
  13&nbsp;for num1 in {0..7}
  14&nbsp;do {
  15&nbsp;   for num2 in {0,1}
  16&nbsp;       do {
  17&nbsp;          shownum=`echo "$offset + $T1 * ${num2} + $num1" | bc`
  18&nbsp;          echo -en "\E[0;48;5;${shownum}m color ${shownum} \E[0m"
  19&nbsp;          }
  20&nbsp;       done
  21&nbsp;   echo
  22&nbsp;   }
  23&nbsp;done
  24&nbsp;
  25&nbsp;offset=16
  26&nbsp;for num1 in {0..5}
  27&nbsp;do {
  28&nbsp;   for num2 in {0..5}
  29&nbsp;       do {
  30&nbsp;          for num3 in {0..5}
  31&nbsp;              do {
  32&nbsp;                 shownum=`echo "$offset + $T2 * ${num3} \
  33&nbsp;                 + $num2 + $T3 * ${num1}" | bc`
  34&nbsp;                 echo -en "\E[0;48;5;${shownum}m color ${shownum} \E[0m"
  35&nbsp;                 }
  36&nbsp;               done
  37&nbsp;          echo
  38&nbsp;          }
  39&nbsp;       done
  40&nbsp;}
  41&nbsp;done
  42&nbsp;
  43&nbsp;offset=232
  44&nbsp;for num1 in {0..23}
  45&nbsp;do {
  46&nbsp;   shownum=`expr $offset + $num1`
  47&nbsp;   echo -en "\E[0;48;5;${shownum}m ${shownum}\E[0m"
  48&nbsp;}
  49&nbsp;done
  50&nbsp;
  51&nbsp;echo</PRE
></TD
></TR
></TABLE
><HR></DIV
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="SAMORSE"
></A
><P
><B
>Example A-53. Morse Code Practice</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#!/bin/bash
   2&nbsp;# sam.sh, v. .01a
   3&nbsp;# Still Another Morse (code training script)
   4&nbsp;# With profuse apologies to Sam (F.B.) Morse.
   5&nbsp;# Author: Mendel Cooper
   6&nbsp;# License: GPL3
   7&nbsp;# Reldate: 05/25/11
   8&nbsp;
   9&nbsp;# Morse code training script.
  10&nbsp;# Converts arguments to audible dots and dashes.
  11&nbsp;# Note: lowercase input only at this time.
  12&nbsp;
  13&nbsp;
  14&nbsp;
  15&nbsp;# Get the wav files from the source tarball:
  16&nbsp;# http://bash.deta.in/abs-guide-latest.tar.bz2
  17&nbsp;DOT='soundfiles/dot.wav'
  18&nbsp;DASH='soundfiles/dash.wav'
  19&nbsp;# Maybe move soundfiles to /usr/local/sounds?
  20&nbsp;
  21&nbsp;LETTERSPACE=300000  # Microseconds.
  22&nbsp;WORDSPACE=980000
  23&nbsp;# Nice and slow, for beginners. Maybe 5 wpm?
  24&nbsp;
  25&nbsp;EXIT_MSG="May the Morse be with you!"
  26&nbsp;E_NOARGS=75         # No command-line args?
  27&nbsp;
  28&nbsp;
  29&nbsp;
  30&nbsp;declare -A morse    # Associative array!
  31&nbsp;# ======================================= #
  32&nbsp;morse[a]="dot; dash"
  33&nbsp;morse[b]="dash; dot; dot; dot"
  34&nbsp;morse[c]="dash; dot; dash; dot"
  35&nbsp;morse[d]="dash; dot; dot"
  36&nbsp;morse[e]="dot"
  37&nbsp;morse[f]="dot; dot; dash; dot"
  38&nbsp;morse[g]="dash; dash; dot"
  39&nbsp;morse[h]="dot; dot; dot; dot"
  40&nbsp;morse[i]="dot; dot;"
  41&nbsp;morse[j]="dot; dash; dash; dash"
  42&nbsp;morse[k]="dash; dot; dash"
  43&nbsp;morse[l]="dot; dash; dot; dot"
  44&nbsp;morse[m]="dash; dash"
  45&nbsp;morse[n]="dash; dot"
  46&nbsp;morse[o]="dash; dash; dash"
  47&nbsp;morse[p]="dot; dash; dash; dot"
  48&nbsp;morse[q]="dash; dash; dot; dash"
  49&nbsp;morse[r]="dot; dash; dot"
  50&nbsp;morse[s]="dot; dot; dot"
  51&nbsp;morse[t]="dash"
  52&nbsp;morse[u]="dot; dot; dash"
  53&nbsp;morse[v]="dot; dot; dot; dash"
  54&nbsp;morse[w]="dot; dash; dash"
  55&nbsp;morse[x]="dash; dot; dot; dash"
  56&nbsp;morse[y]="dash; dot; dash; dash"
  57&nbsp;morse[z]="dash; dash; dot; dot"
  58&nbsp;morse[0]="dash; dash; dash; dash; dash"
  59&nbsp;morse[1]="dot; dash; dash; dash; dash"
  60&nbsp;morse[2]="dot; dot; dash; dash; dash"
  61&nbsp;morse[3]="dot; dot; dot; dash; dash"
  62&nbsp;morse[4]="dot; dot; dot; dot; dash"
  63&nbsp;morse[5]="dot; dot; dot; dot; dot"
  64&nbsp;morse[6]="dash; dot; dot; dot; dot"
  65&nbsp;morse[7]="dash; dash; dot; dot; dot"
  66&nbsp;morse[8]="dash; dash; dash; dot; dot"
  67&nbsp;morse[9]="dash; dash; dash; dash; dot"
  68&nbsp;# The following must be escaped or quoted.
  69&nbsp;morse[?]="dot; dot; dash; dash; dot; dot"
  70&nbsp;morse[.]="dot; dash; dot; dash; dot; dash"
  71&nbsp;morse[,]="dash; dash; dot; dot; dash; dash"
  72&nbsp;morse[/]="dash; dot; dot; dash; dot"
  73&nbsp;morse[\@]="dot; dash; dash; dot; dash; dot"
  74&nbsp;# ======================================= #
  75&nbsp;
  76&nbsp;play_letter ()
  77&nbsp;{
  78&nbsp;  eval ${morse[$1]}   # Play dots, dashes from appropriate sound files.
  79&nbsp;  # Why is 'eval' necessary here?
  80&nbsp;  usleep $LETTERSPACE # Pause in between letters.
  81&nbsp;}
  82&nbsp;
  83&nbsp;extract_letters ()
  84&nbsp;{                     # Slice string apart, letter by letter.
  85&nbsp;  local pos=0         # Starting at left end of string.
  86&nbsp;  local len=1         # One letter at a time.
  87&nbsp;  strlen=${#1}
  88&nbsp;
  89&nbsp;  while [ $pos -lt $strlen ]
  90&nbsp;  do
  91&nbsp;    letter=${1:pos:len}
  92&nbsp;    #      ^^^^^^^^^^^^    See Chapter 10.1.
  93&nbsp;    play_letter $letter
  94&nbsp;    echo -n "*"       #    Mark letter just played.
  95&nbsp;    ((pos++))
  96&nbsp;  done
  97&nbsp;}
  98&nbsp;
  99&nbsp;######### Play the sounds ############
 100&nbsp;dot()  { aplay "$DOT" 2&#38;&#62;/dev/null;  }
 101&nbsp;dash() { aplay "$DASH" 2&#38;&#62;/dev/null; }
 102&nbsp;######################################
 103&nbsp;
 104&nbsp;no_args ()
 105&nbsp;{
 106&nbsp;    declare -a usage
 107&nbsp;    usage=( $0 word1 word2 ... )
 108&nbsp;
 109&nbsp;    echo "Usage:"; echo
 110&nbsp;    echo ${usage[*]}
 111&nbsp;    for index in 0 1 2 3
 112&nbsp;    do
 113&nbsp;      extract_letters ${usage[index]}     
 114&nbsp;      usleep $WORDSPACE
 115&nbsp;      echo -n " "     # Print space between words.
 116&nbsp;    done
 117&nbsp;#   echo "Usage: $0 word1 word2 ... "
 118&nbsp;    echo; echo
 119&nbsp;}
 120&nbsp;
 121&nbsp;
 122&nbsp;# int main()
 123&nbsp;# {
 124&nbsp;
 125&nbsp;clear                 # Clear the terminal screen.
 126&nbsp;echo "            SAM"
 127&nbsp;echo "Still Another Morse code trainer"
 128&nbsp;echo "    Author: Mendel Cooper"
 129&nbsp;echo; echo;
 130&nbsp;
 131&nbsp;if [ -z "$1" ]
 132&nbsp;then
 133&nbsp;  no_args
 134&nbsp;  echo; echo; echo "$EXIT_MSG"; echo
 135&nbsp;  exit $E_NOARGS
 136&nbsp;fi
 137&nbsp;
 138&nbsp;echo; echo "$*"       # Print text that will be played.
 139&nbsp;
 140&nbsp;until [ -z "$1" ]
 141&nbsp;do
 142&nbsp;  extract_letters $1
 143&nbsp;  shift           # On to next word.
 144&nbsp;  usleep $WORDSPACE
 145&nbsp;  echo -n " "     # Print space between words.
 146&nbsp;done
 147&nbsp;
 148&nbsp;echo; echo; echo "$EXIT_MSG"; echo
 149&nbsp;
 150&nbsp;exit 0
 151&nbsp;# }
 152&nbsp;
 153&nbsp;#  Exercises:
 154&nbsp;#  ---------
 155&nbsp;#  1) Have the script accept either lowercase or uppercase words
 156&nbsp;#+    as arguments. Hint: Use 'tr' . . .
 157&nbsp;#  2) Have the script optionally accept input from a text file.</PRE
></TD
></TR
></TABLE
><HR></DIV
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="BASE64"
></A
><P
><B
>Example A-54. Base64 encoding/decoding</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#!/bin/bash
   2&nbsp;# base64.sh: Bash implementation of Base64 encoding and decoding.
   3&nbsp;#
   4&nbsp;# Copyright (c) 2011 vladz &#60;vladz@devzero.fr&#62;
   5&nbsp;# Used in ABSG with permission (thanks!).
   6&nbsp;#
   7&nbsp;#  Encode or decode original Base64 (and also Base64url)
   8&nbsp;#+ from STDIN to STDOUT.
   9&nbsp;#
  10&nbsp;#    Usage:
  11&nbsp;#
  12&nbsp;#    Encode
  13&nbsp;#    $ ./base64.sh &#60; binary-file &#62; binary-file.base64
  14&nbsp;#    Decode
  15&nbsp;#    $ ./base64.sh -d &#60; binary-file.base64 &#62; binary-file
  16&nbsp;#
  17&nbsp;# Reference:
  18&nbsp;#
  19&nbsp;#    [1]  RFC4648 - "The Base16, Base32, and Base64 Data Encodings"
  20&nbsp;#         http://tools.ietf.org/html/rfc4648#section-5
  21&nbsp;
  22&nbsp;
  23&nbsp;# The base64_charset[] array contains entire base64 charset,
  24&nbsp;# and additionally the character "=" ...
  25&nbsp;base64_charset=( {A..Z} {a..z} {0..9} + / = )
  26&nbsp;                # Nice illustration of brace expansion.
  27&nbsp;
  28&nbsp;#  Uncomment the ### line below to use base64url encoding instead of
  29&nbsp;#+ original base64.
  30&nbsp;### base64_charset=( {A..Z} {a..z} {0..9} - _ = )
  31&nbsp;
  32&nbsp;#  Output text width when encoding
  33&nbsp;#+ (64 characters, just like openssl output).
  34&nbsp;text_width=64
  35&nbsp;
  36&nbsp;function display_base64_char {
  37&nbsp;#  Convert a 6-bit number (between 0 and 63) into its corresponding values
  38&nbsp;#+ in Base64, then display the result with the specified text width.
  39&nbsp;  printf "${base64_charset[$1]}"; (( width++ ))
  40&nbsp;  (( width % text_width == 0 )) &#38;&#38; printf "\n"
  41&nbsp;}
  42&nbsp;
  43&nbsp;function encode_base64 {
  44&nbsp;# Encode three 8-bit hexadecimal codes into four 6-bit numbers.
  45&nbsp;  #    We need two local int array variables:
  46&nbsp;  #    c8[]: to store the codes of the 8-bit characters to encode
  47&nbsp;  #    c6[]: to store the corresponding encoded values on 6-bit
  48&nbsp;  declare -a -i c8 c6
  49&nbsp;
  50&nbsp;  #  Convert hexadecimal to decimal.
  51&nbsp;  c8=( $(printf "ibase=16; ${1:0:2}\n${1:2:2}\n${1:4:2}\n" | bc) )
  52&nbsp;
  53&nbsp;  #  Let's play with bitwise operators
  54&nbsp;  #+ (3x8-bit into 4x6-bits conversion).
  55&nbsp;  (( c6[0] = c8[0] &#62;&#62; 2 ))
  56&nbsp;  (( c6[1] = ((c8[0] &#38;  3) &#60;&#60; 4) | (c8[1] &#62;&#62; 4) ))
  57&nbsp;
  58&nbsp;  # The following operations depend on the c8 element number.
  59&nbsp;  case ${#c8[*]} in 
  60&nbsp;    3) (( c6[2] = ((c8[1] &#38; 15) &#60;&#60; 2) | (c8[2] &#62;&#62; 6) ))
  61&nbsp;       (( c6[3] = c8[2] &#38; 63 )) ;;
  62&nbsp;    2) (( c6[2] = (c8[1] &#38; 15) &#60;&#60; 2 ))
  63&nbsp;       (( c6[3] = 64 )) ;;
  64&nbsp;    1) (( c6[2] = c6[3] = 64 )) ;;
  65&nbsp;  esac
  66&nbsp;
  67&nbsp;  for char in ${c6[@]}; do
  68&nbsp;    display_base64_char ${char}
  69&nbsp;  done
  70&nbsp;}
  71&nbsp;
  72&nbsp;function decode_base64 {
  73&nbsp;# Decode four base64 characters into three hexadecimal ASCII characters.
  74&nbsp;  #  c8[]: to store the codes of the 8-bit characters
  75&nbsp;  #  c6[]: to store the corresponding Base64 values on 6-bit
  76&nbsp;  declare -a -i c8 c6
  77&nbsp;
  78&nbsp;  # Find decimal value corresponding to the current base64 character.
  79&nbsp;  for current_char in ${1:0:1} ${1:1:1} ${1:2:1} ${1:3:1}; do
  80&nbsp;     [ "${current_char}" = "=" ] &#38;&#38; break
  81&nbsp;
  82&nbsp;     position=0
  83&nbsp;     while [ "${current_char}" != "${base64_charset[${position}]}" ]; do
  84&nbsp;        (( position++ ))
  85&nbsp;     done
  86&nbsp;
  87&nbsp;     c6=( ${c6[*]} ${position} )
  88&nbsp;  done
  89&nbsp;
  90&nbsp;  #  Let's play with bitwise operators
  91&nbsp;  #+ (4x8-bit into 3x6-bits conversion).
  92&nbsp;  (( c8[0] = (c6[0] &#60;&#60; 2) | (c6[1] &#62;&#62; 4) ))
  93&nbsp;
  94&nbsp;  # The next operations depends on the c6 elements number.
  95&nbsp;  case ${#c6[*]} in
  96&nbsp;    3) (( c8[1] = ( (c6[1] &#38; 15) &#60;&#60; 4) | (c6[2] &#62;&#62; 2) ))
  97&nbsp;       (( c8[2] = (c6[2] &#38; 3) &#60;&#60; 6 )); unset c8[2] ;;
  98&nbsp;    4) (( c8[1] = ( (c6[1] &#38; 15) &#60;&#60; 4) | (c6[2] &#62;&#62; 2) ))
  99&nbsp;       (( c8[2] = ( (c6[2] &#38;  3) &#60;&#60; 6) |  c6[3] )) ;;
 100&nbsp;  esac
 101&nbsp;
 102&nbsp;  for char in ${c8[*]}; do
 103&nbsp;     printf "\x$(printf "%x" ${char})"
 104&nbsp;  done
 105&nbsp;}
 106&nbsp;
 107&nbsp;
 108&nbsp;# main ()
 109&nbsp;
 110&nbsp;if [ "$1" = "-d" ]; then   # decode
 111&nbsp;
 112&nbsp;  # Reformat STDIN in pseudo 4x6-bit groups.
 113&nbsp;  content=$(cat - | tr -d "\n" | sed -r "s/(.{4})/\1 /g")
 114&nbsp;
 115&nbsp;  for chars in ${content}; do decode_base64 ${chars}; done
 116&nbsp;
 117&nbsp;else
 118&nbsp;  # Make a hexdump of stdin and reformat in 3-byte groups.
 119&nbsp;  content=$(cat - | xxd -ps -u | sed -r "s/(\w{6})/\1 /g" |
 120&nbsp;            tr -d "\n")
 121&nbsp;
 122&nbsp;  for chars in ${content}; do encode_base64 ${chars}; done
 123&nbsp;
 124&nbsp;  echo
 125&nbsp;
 126&nbsp;fi</PRE
></TD
></TR
></TABLE
><HR></DIV
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="SEDAPPEND"
></A
><P
><B
>Example A-55. Inserting text in a file using
       <I
CLASS="FIRSTTERM"
>sed</I
></B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#!/bin/bash
   2&nbsp;#  Prepends a string at a specified line
   3&nbsp;#+ in files with names ending in "sample"
   4&nbsp;#+ in the current working directory.
   5&nbsp;#  000000000000000000000000000000000000
   6&nbsp;#  This script overwrites files!
   7&nbsp;#  Be careful running it in a directory
   8&nbsp;#+ where you have important files!!!
   9&nbsp;#  000000000000000000000000000000000000
  10&nbsp;
  11&nbsp;#  Create a couple of files to operate on ...
  12&nbsp;#  01sample
  13&nbsp;#  02sample
  14&nbsp;#  ... etc.
  15&nbsp;#  These files must not be empty, else the prepend will not work.
  16&nbsp;
  17&nbsp;lineno=1            # Append at line 1 (prepend).
  18&nbsp;filespec="*sample"  # Filename pattern to operate on.
  19&nbsp;
  20&nbsp;string=$(whoami)    # Will set your username as string to insert.
  21&nbsp;                    # It could just as easily be any other string.
  22&nbsp;
  23&nbsp;for file in $filespec # Specify which files to alter.
  24&nbsp;do #        ^^^^^^^^^
  25&nbsp; sed -i ""$lineno"i "$string"" $file
  26&nbsp;#    ^^ -i option edits files in-place.
  27&nbsp;#                 ^ Insert (i) command.
  28&nbsp; echo ""$file" altered!"
  29&nbsp;done
  30&nbsp;
  31&nbsp;echo "Warning: files possibly clobbered!"
  32&nbsp;
  33&nbsp;exit 0
  34&nbsp;
  35&nbsp;# Exercise:
  36&nbsp;# Add error checking to this script.
  37&nbsp;# It needs it badly.</PRE
></TD
></TR
></TABLE
><HR></DIV
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="GRONSFELD"
></A
><P
><B
>Example A-56. The Gronsfeld Cipher</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#!/bin/bash
   2&nbsp;# gronsfeld.bash
   3&nbsp;
   4&nbsp;# License: GPL3
   5&nbsp;# Reldate 06/23/11
   6&nbsp;
   7&nbsp;#  This is an implementation of the Gronsfeld Cipher.
   8&nbsp;#  It's essentially a stripped-down variant of the 
   9&nbsp;#+ polyalphabetic Vigenre Tableau, but with only 10 alphabets.
  10&nbsp;#  The classic Gronsfeld has a numeric sequence as the key word,
  11&nbsp;#+ but here we substitute a letter string, for ease of use.
  12&nbsp;#  Allegedly, this cipher was invented by the eponymous Count Gronsfeld
  13&nbsp;#+ in the 17th Century. It was at one time considered to be unbreakable.
  14&nbsp;#  Note that this is ###not### a secure cipher by modern standards.
  15&nbsp;
  16&nbsp;#  Global Variables  #
  17&nbsp;Enc_suffix="29379"   #  Encrypted text output with this 5-digit suffix. 
  18&nbsp;                     #  This functions as a decryption flag,
  19&nbsp;                     #+ and when used to generate passwords adds security.
  20&nbsp;Default_key="gronsfeldk"
  21&nbsp;                     #  The script uses this if key not entered below
  22&nbsp;                     #  (at "Keychain").
  23&nbsp;                     #  Change the above two values frequently
  24&nbsp;                     #+ for added security.
  25&nbsp;
  26&nbsp;GROUPLEN=5           #  Output in groups of 5 letters, per tradition.
  27&nbsp;alpha1=( abcdefghijklmnopqrstuvwxyz )
  28&nbsp;alpha2=( {A..Z} )    #  Output in all caps, per tradition.
  29&nbsp;                     #  Use   alpha2=( {a..z} )   for password generator.
  30&nbsp;wraplen=26           #  Wrap around if past end of alphabet.
  31&nbsp;dflag=               #  Decrypt flag (set if $Enc_suffix present).
  32&nbsp;E_NOARGS=76          #  Missing command-line args?
  33&nbsp;DEBUG=77             #  Debugging flag.
  34&nbsp;declare -a offsets   #  This array holds the numeric shift values for
  35&nbsp;                     #+ encryption/decryption.
  36&nbsp;
  37&nbsp;########Keychain#########
  38&nbsp;key=  ### Put key here!!!
  39&nbsp;      # 10 characters!
  40&nbsp;#########################
  41&nbsp;
  42&nbsp;
  43&nbsp;
  44&nbsp;# Function
  45&nbsp;: ()
  46&nbsp;{ # Encrypt or decrypt, depending on whether $dflag is set.
  47&nbsp;  # Why ": ()" as a function name? Just to prove that it can be done.
  48&nbsp;
  49&nbsp;  local idx keydx mlen off1 shft
  50&nbsp;  local plaintext="$1"
  51&nbsp;  local mlen=${#plaintext}
  52&nbsp;
  53&nbsp;for (( idx=0; idx&#60;$mlen; idx++ ))
  54&nbsp;do
  55&nbsp;  let "keydx = $idx % $keylen"
  56&nbsp;  shft=${offsets[keydx]}
  57&nbsp;
  58&nbsp;  if [ -n "$dflag" ]
  59&nbsp;  then                  # Decrypt!
  60&nbsp;    let "off1 = $(expr index "${alpha1[*]}" ${plaintext:idx:1}) - $shft"
  61&nbsp;    # Shift backward to decrypt.
  62&nbsp;  else                  # Encrypt!
  63&nbsp;    let "off1 = $(expr index "${alpha1[*]}" ${plaintext:idx:1}) + $shft"
  64&nbsp;    # Shift forward to encrypt.
  65&nbsp;    test $(( $idx % $GROUPLEN)) = 0 &#38;&#38; echo -n " "  # Groups of 5 letters.
  66&nbsp;    #  Comment out above line for output as a string without whitespace,
  67&nbsp;    #+ for example, if using the script as a password generator.
  68&nbsp;  fi
  69&nbsp;
  70&nbsp;  ((off1--))   # Normalize. Why is this necessary?
  71&nbsp;
  72&nbsp;      if [ $off1 -lt 0 ]
  73&nbsp;      then     # Catch negative indices.
  74&nbsp;        let "off1 += $wraplen"
  75&nbsp;      fi
  76&nbsp;
  77&nbsp;  ((off1 %= $wraplen))   # Wrap around if past end of alphabet.
  78&nbsp;
  79&nbsp;  echo -n "${alpha2[off1]}"
  80&nbsp;
  81&nbsp;done
  82&nbsp;
  83&nbsp;  if [ -z "$dflag" ]
  84&nbsp;  then
  85&nbsp;    echo " $Enc_suffix"
  86&nbsp;#   echo "$Enc_suffix"  # For password generator.
  87&nbsp;  else
  88&nbsp;    echo
  89&nbsp;  fi
  90&nbsp;} # End encrypt/decrypt function.
  91&nbsp;
  92&nbsp;
  93&nbsp;
  94&nbsp;# int main () {
  95&nbsp;
  96&nbsp;# Check for command-line args.
  97&nbsp;if [ -z "$1" ]
  98&nbsp;then
  99&nbsp;   echo "Usage: $0 TEXT TO ENCODE/DECODE"
 100&nbsp;   exit $E_NOARGS
 101&nbsp;fi
 102&nbsp;
 103&nbsp;if [ ${!#} == "$Enc_suffix" ]
 104&nbsp;#    ^^^^^ Final command-line arg.
 105&nbsp;then
 106&nbsp;  dflag=ON
 107&nbsp;  echo -n "+"           # Flag decrypted text with a "+" for easy ID.
 108&nbsp;fi
 109&nbsp;
 110&nbsp;if [ -z "$key" ]
 111&nbsp;then
 112&nbsp;  key="$Default_key"    # "gronsfeldk" per above.
 113&nbsp;fi
 114&nbsp;
 115&nbsp;keylen=${#key}
 116&nbsp;
 117&nbsp;for (( idx=0; idx&#60;$keylen; idx++ ))
 118&nbsp;do  # Calculate shift values for encryption/decryption.
 119&nbsp;  offsets[idx]=$(expr index "${alpha1[*]}" ${key:idx:1})   # Normalize.
 120&nbsp;  ((offsets[idx]--))  #  Necessary because "expr index" starts at 1,
 121&nbsp;                      #+ whereas array count starts at 0.
 122&nbsp;  # Generate array of numerical offsets corresponding to the key.
 123&nbsp;  # There are simpler ways to accomplish this.
 124&nbsp;done
 125&nbsp;
 126&nbsp;args=$(echo "$*" | sed -e 's/ //g' | tr A-Z a-z | sed -e 's/[0-9]//g')
 127&nbsp;# Remove whitespace and digits from command-line args.
 128&nbsp;# Can modify to also remove punctuation characters, if desired.
 129&nbsp;
 130&nbsp;         # Debug:
 131&nbsp;         # echo "$args"; exit $DEBUG
 132&nbsp;
 133&nbsp;: "$args"               # Call the function named ":".
 134&nbsp;# : is a null operator, except . . . when it's a function name!
 135&nbsp;
 136&nbsp;exit $?    # } End-of-script
 137&nbsp;
 138&nbsp;
 139&nbsp;#   **************************************************************   #
 140&nbsp;#   This script can function as a  password generator,
 141&nbsp;#+  with several minor mods, see above.
 142&nbsp;#   That would allow an easy-to-remember password, even the word
 143&nbsp;#+ "password" itself, which encrypts to vrgfotvo29379
 144&nbsp;#+  a fairly secure password not susceptible to a dictionary attack.
 145&nbsp;#   Or, you could use your own name (surely that's easy to remember!).
 146&nbsp;#   For example, Bozo Bozeman encrypts to hfnbttdppkt29379.
 147&nbsp;#   **************************************************************   #</PRE
></TD
></TR
></TABLE
><HR></DIV
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="BINGO"
></A
><P
><B
>Example A-57. Bingo Number Generator</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#!/bin/bash
   2&nbsp;# bingo.sh
   3&nbsp;# Bingo number generator
   4&nbsp;# Reldate 20Aug12, License: Public Domain
   5&nbsp;
   6&nbsp;#######################################################################
   7&nbsp;# This script generates bingo numbers.
   8&nbsp;# Hitting a key generates a new number.
   9&nbsp;# Hitting 'q' terminates the script.
  10&nbsp;# In a given run of the script, there will be no duplicate numbers.
  11&nbsp;# When the script terminates, it prints a log of the numbers generated.
  12&nbsp;#######################################################################
  13&nbsp;
  14&nbsp;MIN=1       # Lowest allowable bingo number.
  15&nbsp;MAX=75      # Highest allowable bingo number.
  16&nbsp;COLS=15     # Numbers in each column (B I N G O).
  17&nbsp;SINGLE_DIGIT_MAX=9
  18&nbsp;
  19&nbsp;declare -a Numbers
  20&nbsp;Prefix=(B I N G O)
  21&nbsp;
  22&nbsp;initialize_Numbers ()
  23&nbsp;{  # Zero them out to start.
  24&nbsp;   # They'll be incremented if chosen.
  25&nbsp;   local index=0
  26&nbsp;   until [ "$index" -gt $MAX ]
  27&nbsp;   do
  28&nbsp;     Numbers[index]=0
  29&nbsp;     ((index++))
  30&nbsp;   done
  31&nbsp;
  32&nbsp;   Numbers[0]=1   # Flag zero, so it won't be selected.
  33&nbsp;}
  34&nbsp;
  35&nbsp;
  36&nbsp;generate_number ()
  37&nbsp;{
  38&nbsp;   local number
  39&nbsp;
  40&nbsp;   while [ 1 ]
  41&nbsp;   do
  42&nbsp;     let "number = $(expr $RANDOM % $MAX)"
  43&nbsp;     if [ ${Numbers[number]} -eq 0 ]    # Number not yet called.
  44&nbsp;     then
  45&nbsp;       let "Numbers[number]+=1"         # Flag it in the array.
  46&nbsp;       break                            # And terminate loop.
  47&nbsp;     fi   # Else if already called, loop and generate another number.
  48&nbsp;   done
  49&nbsp;   # Exercise: Rewrite this more elegantly as an until-loop.
  50&nbsp;
  51&nbsp;   return $number
  52&nbsp;}
  53&nbsp;
  54&nbsp;
  55&nbsp;print_numbers_called ()
  56&nbsp;{   # Print out the called number log in neat columns.
  57&nbsp;    # echo ${Numbers[@]}
  58&nbsp;
  59&nbsp;local pre2=0                #  Prefix a zero, so columns will align
  60&nbsp;                            #+ on single-digit numbers.
  61&nbsp;
  62&nbsp;echo "Number Stats"
  63&nbsp;
  64&nbsp;for (( index=1; index&#60;=MAX; index++))
  65&nbsp;do
  66&nbsp;  count=${Numbers[index]}
  67&nbsp;  let "t = $index - 1"      # Normalize, since array begins with index 0.
  68&nbsp;  let "column = $(expr $t / $COLS)"
  69&nbsp;  pre=${Prefix[column]}
  70&nbsp;# echo -n "${Prefix[column]} "
  71&nbsp;
  72&nbsp;if [ $(expr $t % $COLS) -eq 0 ]
  73&nbsp;then
  74&nbsp;  echo   # Newline at end of row.
  75&nbsp;fi
  76&nbsp;
  77&nbsp;  if [ "$index" -gt $SINGLE_DIGIT_MAX ]  # Check for single-digit number.
  78&nbsp;  then
  79&nbsp;    echo -n "$pre$index#$count "
  80&nbsp;  else    # Prefix a zero.
  81&nbsp;    echo -n "$pre$pre2$index#$count "
  82&nbsp;  fi
  83&nbsp;
  84&nbsp;done
  85&nbsp;}
  86&nbsp;
  87&nbsp;
  88&nbsp;
  89&nbsp;# main () {
  90&nbsp;RANDOM=$$   # Seed random number generator.
  91&nbsp;
  92&nbsp;initialize_Numbers   # Zero out the number tracking array.
  93&nbsp;
  94&nbsp;clear
  95&nbsp;echo "Bingo Number Caller"; echo
  96&nbsp;
  97&nbsp;while [[ "$key" != "q" ]]   # Main loop.
  98&nbsp;do
  99&nbsp;  read -s -n1 -p "Hit a key for the next number [q to exit] " key
 100&nbsp;  # Usually 'q' exits, but not always.
 101&nbsp;  # Can always hit Ctl-C if q fails.
 102&nbsp;  echo
 103&nbsp;
 104&nbsp;  generate_number; new_number=$?
 105&nbsp;
 106&nbsp;  let "column = $(expr $new_number / $COLS)"
 107&nbsp;  echo -n "${Prefix[column]} "   # B-I-N-G-O
 108&nbsp;
 109&nbsp;  echo $new_number
 110&nbsp;done
 111&nbsp;
 112&nbsp;echo; echo
 113&nbsp;
 114&nbsp;# Game over ...
 115&nbsp;print_numbers_called
 116&nbsp;echo; echo "[#0 = not called . . . #1 = called]"
 117&nbsp;
 118&nbsp;echo
 119&nbsp;
 120&nbsp;exit 0
 121&nbsp;# }
 122&nbsp;
 123&nbsp;
 124&nbsp;# Certainly, this script could stand some improvement.
 125&nbsp;#See also the author's Instructable:
 126&nbsp;#www.instructables.com/id/Binguino-An-Arduino-based-Bingo-Number-Generato/</PRE
></TD
></TR
></TABLE
><HR></DIV
><P
><A
NAME="BASICSREV0"
></A
>To end this section, a review of the
      basics . . . and more.</P
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="BASICSREVIEWED"
></A
><P
><B
>Example A-58. Basics Reviewed</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#!/bin/bash
   2&nbsp;# basics-reviewed.bash
   3&nbsp;
   4&nbsp;# File extension == *.bash == specific to Bash
   5&nbsp;
   6&nbsp;#   Copyright (c) Michael S. Zick, 2003; All rights reserved.
   7&nbsp;#   License: Use in any form, for any purpose.
   8&nbsp;#   Revision: $ID$
   9&nbsp;#
  10&nbsp;#              Edited for layout by M.C.
  11&nbsp;#   (author of the "Advanced Bash Scripting Guide")
  12&nbsp;#   Fixes and updates (04/08) by Cliff Bamford.
  13&nbsp;
  14&nbsp;
  15&nbsp;#  This script tested under Bash versions 2.04, 2.05a and 2.05b.
  16&nbsp;#  It may not work with earlier versions.
  17&nbsp;#  This demonstration script generates one --intentional--
  18&nbsp;#+ "command not found" error message. See line 436.
  19&nbsp;
  20&nbsp;#  The current Bash maintainer, Chet Ramey, has fixed the items noted
  21&nbsp;#+ for later versions of Bash.
  22&nbsp;
  23&nbsp;
  24&nbsp;
  25&nbsp;        ###-------------------------------------------###
  26&nbsp;        ###  Pipe the output of this script to 'more' ###
  27&nbsp;        ###+ else it will scroll off the page.        ###
  28&nbsp;        ###                                           ###
  29&nbsp;        ###  You may also redirect its output         ###
  30&nbsp;        ###+ to a file for examination.               ###  
  31&nbsp;        ###-------------------------------------------###
  32&nbsp;
  33&nbsp;
  34&nbsp;
  35&nbsp;#  Most of the following points are described at length in
  36&nbsp;#+ the text of the foregoing "Advanced Bash Scripting Guide."
  37&nbsp;#  This demonstration script is mostly just a reorganized presentation.
  38&nbsp;#      -- msz
  39&nbsp;
  40&nbsp;# Variables are not typed unless otherwise specified.
  41&nbsp;
  42&nbsp;#  Variables are named. Names must contain a non-digit.
  43&nbsp;#  File descriptor names (as in, for example: 2&#62;&#38;1)
  44&nbsp;#+ contain ONLY digits.
  45&nbsp;
  46&nbsp;# Parameters and Bash array elements are numbered.
  47&nbsp;# (Parameters are very similar to Bash arrays.)
  48&nbsp;
  49&nbsp;# A variable name may be undefined (null reference).
  50&nbsp;unset VarNull
  51&nbsp;
  52&nbsp;# A variable name may be defined but empty (null contents).
  53&nbsp;VarEmpty=''                         # Two, adjacent, single quotes.
  54&nbsp;
  55&nbsp;# A variable name may be defined and non-empty.
  56&nbsp;VarSomething='Literal'
  57&nbsp;
  58&nbsp;# A variable may contain:
  59&nbsp;#   * A whole number as a signed 32-bit (or larger) integer
  60&nbsp;#   * A string
  61&nbsp;# A variable may also be an array.
  62&nbsp;
  63&nbsp;#  A string may contain embedded blanks and may be treated
  64&nbsp;#+ as if it where a function name with optional arguments.
  65&nbsp;
  66&nbsp;#  The names of variables and the names of functions
  67&nbsp;#+ are in different namespaces.
  68&nbsp;
  69&nbsp;
  70&nbsp;#  A variable may be defined as a Bash array either explicitly or
  71&nbsp;#+ implicitly by the syntax of the assignment statement.
  72&nbsp;#  Explicit:
  73&nbsp;declare -a ArrayVar
  74&nbsp;
  75&nbsp;
  76&nbsp;
  77&nbsp;# The echo command is a builtin.
  78&nbsp;echo $VarSomething
  79&nbsp;
  80&nbsp;# The printf command is a builtin.
  81&nbsp;# Translate %s as: String-Format
  82&nbsp;printf %s $VarSomething         # No linebreak specified, none output.
  83&nbsp;echo                            # Default, only linebreak output.
  84&nbsp;
  85&nbsp;
  86&nbsp;
  87&nbsp;
  88&nbsp;# The Bash parser word breaks on whitespace.
  89&nbsp;# Whitespace, or the lack of it is significant.
  90&nbsp;# (This holds true in general; there are, of course, exceptions.)
  91&nbsp;
  92&nbsp;
  93&nbsp;
  94&nbsp;
  95&nbsp;# Translate the DOLLAR_SIGN character as: Content-Of.
  96&nbsp;
  97&nbsp;# Extended-Syntax way of writing Content-Of:
  98&nbsp;echo ${VarSomething}
  99&nbsp;
 100&nbsp;#  The ${ ... } Extended-Syntax allows more than just the variable
 101&nbsp;#+ name to be specified.
 102&nbsp;#  In general, $VarSomething can always be written as: ${VarSomething}.
 103&nbsp;
 104&nbsp;# Call this script with arguments to see the following in action.
 105&nbsp;
 106&nbsp;
 107&nbsp;
 108&nbsp;#  Outside of double-quotes, the special characters @ and *
 109&nbsp;#+ specify identical behavior.
 110&nbsp;#  May be pronounced as: All-Elements-Of.
 111&nbsp;
 112&nbsp;#  Without specification of a name, they refer to the
 113&nbsp;#+ pre-defined parameter Bash-Array.
 114&nbsp;
 115&nbsp;
 116&nbsp;
 117&nbsp;# Glob-Pattern references
 118&nbsp;echo $*                         # All parameters to script or function
 119&nbsp;echo ${*}                       # Same
 120&nbsp;
 121&nbsp;# Bash disables filename expansion for Glob-Patterns.
 122&nbsp;# Only character matching is active.
 123&nbsp;
 124&nbsp;
 125&nbsp;# All-Elements-Of references
 126&nbsp;echo $@                         # Same as above
 127&nbsp;echo ${@}                       # Same as above
 128&nbsp;
 129&nbsp;
 130&nbsp;
 131&nbsp;
 132&nbsp;#  Within double-quotes, the behavior of Glob-Pattern references
 133&nbsp;#+ depends on the setting of IFS (Input Field Separator).
 134&nbsp;#  Within double-quotes, All-Elements-Of references behave the same.
 135&nbsp;
 136&nbsp;
 137&nbsp;#  Specifying only the name of a variable holding a string refers
 138&nbsp;#+ to all elements (characters) of a string.
 139&nbsp;
 140&nbsp;
 141&nbsp;#  To specify an element (character) of a string,
 142&nbsp;#+ the Extended-Syntax reference notation (see below) MAY be used.
 143&nbsp;
 144&nbsp;
 145&nbsp;
 146&nbsp;
 147&nbsp;#  Specifying only the name of a Bash array references
 148&nbsp;#+ the subscript zero element,
 149&nbsp;#+ NOT the FIRST DEFINED nor the FIRST WITH CONTENTS element.
 150&nbsp;
 151&nbsp;#  Additional qualification is needed to reference other elements,
 152&nbsp;#+ which means that the reference MUST be written in Extended-Syntax.
 153&nbsp;#  The general form is: ${name[subscript]}.
 154&nbsp;
 155&nbsp;#  The string forms may also be used: ${name:subscript}
 156&nbsp;#+ for Bash-Arrays when referencing the subscript zero element.
 157&nbsp;
 158&nbsp;
 159&nbsp;# Bash-Arrays are implemented internally as linked lists,
 160&nbsp;#+ not as a fixed area of storage as in some programming languages.
 161&nbsp;
 162&nbsp;
 163&nbsp;#   Characteristics of Bash arrays (Bash-Arrays):
 164&nbsp;#   --------------------------------------------
 165&nbsp;
 166&nbsp;#   If not otherwise specified, Bash-Array subscripts begin with
 167&nbsp;#+  subscript number zero. Literally: [0]
 168&nbsp;#   This is called zero-based indexing.
 169&nbsp;###
 170&nbsp;#   If not otherwise specified, Bash-Arrays are subscript packed
 171&nbsp;#+  (sequential subscripts without subscript gaps).
 172&nbsp;###
 173&nbsp;#   Negative subscripts are not allowed.
 174&nbsp;###
 175&nbsp;#   Elements of a Bash-Array need not all be of the same type.
 176&nbsp;###
 177&nbsp;#   Elements of a Bash-Array may be undefined (null reference).
 178&nbsp;#       That is, a Bash-Array may be "subscript sparse."
 179&nbsp;###
 180&nbsp;#   Elements of a Bash-Array may be defined and empty (null contents).
 181&nbsp;###
 182&nbsp;#   Elements of a Bash-Array may contain:
 183&nbsp;#     * A whole number as a signed 32-bit (or larger) integer
 184&nbsp;#     * A string
 185&nbsp;#     * A string formated so that it appears to be a function name
 186&nbsp;#     + with optional arguments
 187&nbsp;###
 188&nbsp;#   Defined elements of a Bash-Array may be undefined (unset).
 189&nbsp;#       That is, a subscript packed Bash-Array may be changed
 190&nbsp;#   +   into a subscript sparse Bash-Array.
 191&nbsp;###
 192&nbsp;#   Elements may be added to a Bash-Array by defining an element
 193&nbsp;#+  not previously defined.
 194&nbsp;###
 195&nbsp;# For these reasons, I have been calling them "Bash-Arrays".
 196&nbsp;# I'll return to the generic term "array" from now on.
 197&nbsp;#     -- msz
 198&nbsp;
 199&nbsp;
 200&nbsp;echo "========================================================="
 201&nbsp;
 202&nbsp;#  Lines 202 - 334 supplied by Cliff Bamford. (Thanks!)
 203&nbsp;#  Demo --- Interaction with Arrays, quoting, IFS, echo, * and @   ---  
 204&nbsp;#+ all affect how things work
 205&nbsp;
 206&nbsp;ArrayVar[0]='zero'                    # 0 normal
 207&nbsp;ArrayVar[1]=one                       # 1 unquoted literal
 208&nbsp;ArrayVar[2]='two'                     # 2 normal
 209&nbsp;ArrayVar[3]='three'                   # 3 normal
 210&nbsp;ArrayVar[4]='I am four'               # 4 normal with spaces
 211&nbsp;ArrayVar[5]='five'                    # 5 normal
 212&nbsp;unset ArrayVar[6]                     # 6 undefined
 213&nbsp;ArrayValue[7]='seven'                 # 7 normal
 214&nbsp;ArrayValue[8]=''                      # 8 defined but empty
 215&nbsp;ArrayValue[9]='nine'                  # 9 normal
 216&nbsp;
 217&nbsp;
 218&nbsp;echo '--- Here is the array we are using for this test'
 219&nbsp;echo
 220&nbsp;echo "ArrayVar[0]='zero'             # 0 normal"
 221&nbsp;echo "ArrayVar[1]=one                # 1 unquoted literal"
 222&nbsp;echo "ArrayVar[2]='two'              # 2 normal"
 223&nbsp;echo "ArrayVar[3]='three'            # 3 normal"
 224&nbsp;echo "ArrayVar[4]='I am four'        # 4 normal with spaces"
 225&nbsp;echo "ArrayVar[5]='five'             # 5 normal"
 226&nbsp;echo "unset ArrayVar[6]              # 6 undefined"
 227&nbsp;echo "ArrayValue[7]='seven'          # 7 normal"
 228&nbsp;echo "ArrayValue[8]=''               # 8 defined but empty"
 229&nbsp;echo "ArrayValue[9]='nine'           # 9 normal"
 230&nbsp;echo
 231&nbsp;
 232&nbsp;
 233&nbsp;echo
 234&nbsp;echo '---Case0: No double-quotes, Default IFS of space,tab,newline ---'
 235&nbsp;IFS=$'\x20'$'\x09'$'\x0A'            # In exactly this order.
 236&nbsp;echo 'Here is: printf %q {${ArrayVar[*]}'
 237&nbsp;printf %q ${ArrayVar[*]}
 238&nbsp;echo
 239&nbsp;echo 'Here is: printf %q {${ArrayVar[@]}'
 240&nbsp;printf %q ${ArrayVar[@]}
 241&nbsp;echo
 242&nbsp;echo 'Here is: echo ${ArrayVar[*]}'
 243&nbsp;echo  ${ArrayVar[@]}
 244&nbsp;echo 'Here is: echo {${ArrayVar[@]}'
 245&nbsp;echo ${ArrayVar[@]}
 246&nbsp;
 247&nbsp;echo
 248&nbsp;echo '---Case1: Within double-quotes - Default IFS of space-tab- 
 249&nbsp;newline ---'
 250&nbsp;IFS=$'\x20'$'\x09'$'\x0A'	    #  These three bytes,
 251&nbsp;echo 'Here is: printf %q "{${ArrayVar[*]}"'
 252&nbsp;printf %q "${ArrayVar[*]}"
 253&nbsp;echo
 254&nbsp;echo 'Here is: printf %q "{${ArrayVar[@]}"'
 255&nbsp;printf %q "${ArrayVar[@]}"
 256&nbsp;echo
 257&nbsp;echo 'Here is: echo "${ArrayVar[*]}"'
 258&nbsp;echo  "${ArrayVar[@]}"
 259&nbsp;echo 'Here is: echo "{${ArrayVar[@]}"'
 260&nbsp;echo "${ArrayVar[@]}"
 261&nbsp;
 262&nbsp;echo
 263&nbsp;echo '---Case2: Within double-quotes - IFS is q'
 264&nbsp;IFS='q'
 265&nbsp;echo 'Here is: printf %q "{${ArrayVar[*]}"'
 266&nbsp;printf %q "${ArrayVar[*]}"
 267&nbsp;echo
 268&nbsp;echo 'Here is: printf %q "{${ArrayVar[@]}"'
 269&nbsp;printf %q "${ArrayVar[@]}"
 270&nbsp;echo
 271&nbsp;echo 'Here is: echo "${ArrayVar[*]}"'
 272&nbsp;echo  "${ArrayVar[@]}"
 273&nbsp;echo 'Here is: echo "{${ArrayVar[@]}"'
 274&nbsp;echo "${ArrayVar[@]}"
 275&nbsp;
 276&nbsp;echo
 277&nbsp;echo '---Case3: Within double-quotes - IFS is ^'
 278&nbsp;IFS='^'
 279&nbsp;echo 'Here is: printf %q "{${ArrayVar[*]}"'
 280&nbsp;printf %q "${ArrayVar[*]}"
 281&nbsp;echo
 282&nbsp;echo 'Here is: printf %q "{${ArrayVar[@]}"'
 283&nbsp;printf %q "${ArrayVar[@]}"
 284&nbsp;echo
 285&nbsp;echo 'Here is: echo "${ArrayVar[*]}"'
 286&nbsp;echo  "${ArrayVar[@]}"
 287&nbsp;echo 'Here is: echo "{${ArrayVar[@]}"'
 288&nbsp;echo "${ArrayVar[@]}"
 289&nbsp;
 290&nbsp;echo
 291&nbsp;echo '---Case4: Within double-quotes - IFS is ^ followed by  
 292&nbsp;space,tab,newline'
 293&nbsp;IFS=$'^'$'\x20'$'\x09'$'\x0A'       # ^ + space tab newline
 294&nbsp;echo 'Here is: printf %q "{${ArrayVar[*]}"'
 295&nbsp;printf %q "${ArrayVar[*]}"
 296&nbsp;echo
 297&nbsp;echo 'Here is: printf %q "{${ArrayVar[@]}"'
 298&nbsp;printf %q "${ArrayVar[@]}"
 299&nbsp;echo
 300&nbsp;echo 'Here is: echo "${ArrayVar[*]}"'
 301&nbsp;echo  "${ArrayVar[@]}"
 302&nbsp;echo 'Here is: echo "{${ArrayVar[@]}"'
 303&nbsp;echo "${ArrayVar[@]}"
 304&nbsp;
 305&nbsp;echo
 306&nbsp;echo '---Case6: Within double-quotes - IFS set and empty '
 307&nbsp;IFS=''
 308&nbsp;echo 'Here is: printf %q "{${ArrayVar[*]}"'
 309&nbsp;printf %q "${ArrayVar[*]}"
 310&nbsp;echo
 311&nbsp;echo 'Here is: printf %q "{${ArrayVar[@]}"'
 312&nbsp;printf %q "${ArrayVar[@]}"
 313&nbsp;echo
 314&nbsp;echo 'Here is: echo "${ArrayVar[*]}"'
 315&nbsp;echo  "${ArrayVar[@]}"
 316&nbsp;echo 'Here is: echo "{${ArrayVar[@]}"'
 317&nbsp;echo "${ArrayVar[@]}"
 318&nbsp;
 319&nbsp;echo
 320&nbsp;echo '---Case7: Within double-quotes - IFS is unset'
 321&nbsp;unset IFS
 322&nbsp;echo 'Here is: printf %q "{${ArrayVar[*]}"'
 323&nbsp;printf %q "${ArrayVar[*]}"
 324&nbsp;echo
 325&nbsp;echo 'Here is: printf %q "{${ArrayVar[@]}"'
 326&nbsp;printf %q "${ArrayVar[@]}"
 327&nbsp;echo
 328&nbsp;echo 'Here is: echo "${ArrayVar[*]}"'
 329&nbsp;echo  "${ArrayVar[@]}"
 330&nbsp;echo 'Here is: echo "{${ArrayVar[@]}"'
 331&nbsp;echo "${ArrayVar[@]}"
 332&nbsp;
 333&nbsp;echo
 334&nbsp;echo '---End of Cases---'
 335&nbsp;echo "========================================================="; echo
 336&nbsp;
 337&nbsp;
 338&nbsp;
 339&nbsp;# Put IFS back to the default.
 340&nbsp;# Default is exactly these three bytes.
 341&nbsp;IFS=$'\x20'$'\x09'$'\x0A'           # In exactly this order.
 342&nbsp;
 343&nbsp;# Interpretation of the above outputs:
 344&nbsp;#   A Glob-Pattern is I/O; the setting of IFS matters.
 345&nbsp;###
 346&nbsp;#   An All-Elements-Of does not consider IFS settings.
 347&nbsp;###
 348&nbsp;#   Note the different output using the echo command and the
 349&nbsp;#+  quoted format operator of the printf command.
 350&nbsp;
 351&nbsp;
 352&nbsp;#  Recall:
 353&nbsp;#   Parameters are similar to arrays and have the similar behaviors.
 354&nbsp;###
 355&nbsp;#  The above examples demonstrate the possible variations.
 356&nbsp;#  To retain the shape of a sparse array, additional script
 357&nbsp;#+ programming is required.
 358&nbsp;###
 359&nbsp;#  The source code of Bash has a routine to output the
 360&nbsp;#+ [subscript]=value   array assignment format.
 361&nbsp;#  As of version 2.05b, that routine is not used,
 362&nbsp;#+ but that might change in future releases.
 363&nbsp;
 364&nbsp;
 365&nbsp;
 366&nbsp;# The length of a string, measured in non-null elements (characters):
 367&nbsp;echo
 368&nbsp;echo '- - Non-quoted references - -'
 369&nbsp;echo 'Non-Null character count: '${#VarSomething}' characters.'
 370&nbsp;
 371&nbsp;# test='Lit'$'\x00''eral'           # $'\x00' is a null character.
 372&nbsp;# echo ${#test}                     # See that?
 373&nbsp;
 374&nbsp;
 375&nbsp;
 376&nbsp;#  The length of an array, measured in defined elements,
 377&nbsp;#+ including null content elements.
 378&nbsp;echo
 379&nbsp;echo 'Defined content count: '${#ArrayVar[@]}' elements.'
 380&nbsp;# That is NOT the maximum subscript (4).
 381&nbsp;# That is NOT the range of the subscripts (1 . . 4 inclusive).
 382&nbsp;# It IS the length of the linked list.
 383&nbsp;###
 384&nbsp;#  Both the maximum subscript and the range of the subscripts may
 385&nbsp;#+ be found with additional script programming.
 386&nbsp;
 387&nbsp;# The length of a string, measured in non-null elements (characters):
 388&nbsp;echo
 389&nbsp;echo '- - Quoted, Glob-Pattern references - -'
 390&nbsp;echo 'Non-Null character count: '"${#VarSomething}"' characters.'
 391&nbsp;
 392&nbsp;#  The length of an array, measured in defined elements,
 393&nbsp;#+ including null-content elements.
 394&nbsp;echo
 395&nbsp;echo 'Defined element count: '"${#ArrayVar[*]}"' elements.'
 396&nbsp;
 397&nbsp;#  Interpretation: Substitution does not effect the ${# ... } operation.
 398&nbsp;#  Suggestion:
 399&nbsp;#  Always use the All-Elements-Of character
 400&nbsp;#+ if that is what is intended (independence from IFS).
 401&nbsp;
 402&nbsp;
 403&nbsp;
 404&nbsp;#  Define a simple function.
 405&nbsp;#  I include an underscore in the name
 406&nbsp;#+ to make it distinctive in the examples below.
 407&nbsp;###
 408&nbsp;#  Bash separates variable names and function names
 409&nbsp;#+ in different namespaces.
 410&nbsp;#  The Mark-One eyeball isn't that advanced.
 411&nbsp;###
 412&nbsp;_simple() {
 413&nbsp;    echo -n 'SimpleFunc'$@          #  Newlines are swallowed in
 414&nbsp;}                                   #+ result returned in any case.
 415&nbsp;
 416&nbsp;
 417&nbsp;# The ( ... ) notation invokes a command or function.
 418&nbsp;# The $( ... ) notation is pronounced: Result-Of.
 419&nbsp;
 420&nbsp;
 421&nbsp;# Invoke the function _simple
 422&nbsp;echo
 423&nbsp;echo '- - Output of function _simple - -'
 424&nbsp;_simple                             # Try passing arguments.
 425&nbsp;echo
 426&nbsp;# or
 427&nbsp;(_simple)                           # Try passing arguments.
 428&nbsp;echo
 429&nbsp;
 430&nbsp;echo '- Is there a variable of that name? -'
 431&nbsp;echo $_simple not defined           # No variable by that name.
 432&nbsp;
 433&nbsp;# Invoke the result of function _simple (Error msg intended)
 434&nbsp;
 435&nbsp;###
 436&nbsp;$(_simple)                          # Gives an error message:
 437&nbsp;#                          line 436: SimpleFunc: command not found
 438&nbsp;#                          ---------------------------------------
 439&nbsp;
 440&nbsp;echo
 441&nbsp;###
 442&nbsp;
 443&nbsp;#  The first word of the result of function _simple
 444&nbsp;#+ is neither a valid Bash command nor the name of a defined function.
 445&nbsp;###
 446&nbsp;# This demonstrates that the output of _simple is subject to evaluation.
 447&nbsp;###
 448&nbsp;# Interpretation:
 449&nbsp;#   A function can be used to generate in-line Bash commands.
 450&nbsp;
 451&nbsp;
 452&nbsp;# A simple function where the first word of result IS a bash command:
 453&nbsp;###
 454&nbsp;_print() {
 455&nbsp;    echo -n 'printf %q '$@
 456&nbsp;}
 457&nbsp;
 458&nbsp;echo '- - Outputs of function _print - -'
 459&nbsp;_print parm1 parm2                  # An Output NOT A Command.
 460&nbsp;echo
 461&nbsp;
 462&nbsp;$(_print parm1 parm2)               #  Executes: printf %q parm1 parm2
 463&nbsp;                                    #  See above IFS examples for the
 464&nbsp;                                    #+ various possibilities.
 465&nbsp;echo
 466&nbsp;
 467&nbsp;$(_print $VarSomething)             # The predictable result.
 468&nbsp;echo
 469&nbsp;
 470&nbsp;
 471&nbsp;
 472&nbsp;# Function variables
 473&nbsp;# ------------------
 474&nbsp;
 475&nbsp;echo
 476&nbsp;echo '- - Function variables - -'
 477&nbsp;# A variable may represent a signed integer, a string or an array.
 478&nbsp;# A string may be used like a function name with optional arguments.
 479&nbsp;
 480&nbsp;# set -vx                           #  Enable if desired
 481&nbsp;declare -f funcVar                  #+ in namespace of functions
 482&nbsp;
 483&nbsp;funcVar=_print                      # Contains name of function.
 484&nbsp;$funcVar parm1                      # Same as _print at this point.
 485&nbsp;echo
 486&nbsp;
 487&nbsp;funcVar=$(_print )                  # Contains result of function.
 488&nbsp;$funcVar                            # No input, No output.
 489&nbsp;$funcVar $VarSomething              # The predictable result.
 490&nbsp;echo
 491&nbsp;
 492&nbsp;funcVar=$(_print $VarSomething)     #  $VarSomething replaced HERE.
 493&nbsp;$funcVar                            #  The expansion is part of the
 494&nbsp;echo                                #+ variable contents.
 495&nbsp;
 496&nbsp;funcVar="$(_print $VarSomething)"   #  $VarSomething replaced HERE.
 497&nbsp;$funcVar                            #  The expansion is part of the
 498&nbsp;echo                                #+ variable contents.
 499&nbsp;
 500&nbsp;#  The difference between the unquoted and the double-quoted versions
 501&nbsp;#+ above can be seen in the "protect_literal.sh" example.
 502&nbsp;#  The first case above is processed as two, unquoted, Bash-Words.
 503&nbsp;#  The second case above is processed as one, quoted, Bash-Word.
 504&nbsp;
 505&nbsp;
 506&nbsp;
 507&nbsp;
 508&nbsp;# Delayed replacement
 509&nbsp;# -------------------
 510&nbsp;
 511&nbsp;echo
 512&nbsp;echo '- - Delayed replacement - -'
 513&nbsp;funcVar="$(_print '$VarSomething')" # No replacement, single Bash-Word.
 514&nbsp;eval $funcVar                       # $VarSomething replaced HERE.
 515&nbsp;echo
 516&nbsp;
 517&nbsp;VarSomething='NewThing'
 518&nbsp;eval $funcVar                       # $VarSomething replaced HERE.
 519&nbsp;echo
 520&nbsp;
 521&nbsp;# Restore the original setting trashed above.
 522&nbsp;VarSomething=Literal
 523&nbsp;
 524&nbsp;#  There are a pair of functions demonstrated in the
 525&nbsp;#+ "protect_literal.sh" and "unprotect_literal.sh" examples.
 526&nbsp;#  These are general purpose functions for delayed replacement literals
 527&nbsp;#+ containing variables.
 528&nbsp;
 529&nbsp;
 530&nbsp;
 531&nbsp;
 532&nbsp;
 533&nbsp;# REVIEW:
 534&nbsp;# ------
 535&nbsp;
 536&nbsp;#  A string can be considered a Classic-Array of elements (characters).
 537&nbsp;#  A string operation applies to all elements (characters) of the string
 538&nbsp;#+ (in concept, anyway).
 539&nbsp;###
 540&nbsp;#  The notation: ${array_name[@]} represents all elements of the
 541&nbsp;#+ Bash-Array: array_name.
 542&nbsp;###
 543&nbsp;#  The Extended-Syntax string operations can be applied to all
 544&nbsp;#+ elements of an array.
 545&nbsp;###
 546&nbsp;#  This may be thought of as a For-Each operation on a vector of strings.
 547&nbsp;###
 548&nbsp;#  Parameters are similar to an array.
 549&nbsp;#  The initialization of a parameter array for a script
 550&nbsp;#+ and a parameter array for a function only differ
 551&nbsp;#+ in the initialization of ${0}, which never changes its setting.
 552&nbsp;###
 553&nbsp;#  Subscript zero of the script's parameter array contains
 554&nbsp;#+ the name of the script.
 555&nbsp;###
 556&nbsp;#  Subscript zero of a function's parameter array DOES NOT contain
 557&nbsp;#+ the name of the function.
 558&nbsp;#  The name of the current function is accessed by the $FUNCNAME variable.
 559&nbsp;###
 560&nbsp;#  A quick, review list follows (quick, not short).
 561&nbsp;
 562&nbsp;echo
 563&nbsp;echo '- - Test (but not change) - -'
 564&nbsp;echo '- null reference -'
 565&nbsp;echo -n ${VarNull-'NotSet'}' '          # NotSet
 566&nbsp;echo ${VarNull}                         # NewLine only
 567&nbsp;echo -n ${VarNull:-'NotSet'}' '         # NotSet
 568&nbsp;echo ${VarNull}                         # Newline only
 569&nbsp;
 570&nbsp;echo '- null contents -'
 571&nbsp;echo -n ${VarEmpty-'Empty'}' '          # Only the space
 572&nbsp;echo ${VarEmpty}                        # Newline only
 573&nbsp;echo -n ${VarEmpty:-'Empty'}' '         # Empty
 574&nbsp;echo ${VarEmpty}                        # Newline only
 575&nbsp;
 576&nbsp;echo '- contents -'
 577&nbsp;echo ${VarSomething-'Content'}          # Literal
 578&nbsp;echo ${VarSomething:-'Content'}         # Literal
 579&nbsp;
 580&nbsp;echo '- Sparse Array -'
 581&nbsp;echo ${ArrayVar[@]-'not set'}
 582&nbsp;
 583&nbsp;# ASCII-Art time
 584&nbsp;# State     Y==yes, N==no
 585&nbsp;#           -       :-
 586&nbsp;# Unset     Y       Y       ${# ... } == 0
 587&nbsp;# Empty     N       Y       ${# ... } == 0
 588&nbsp;# Contents  N       N       ${# ... } &#62; 0
 589&nbsp;
 590&nbsp;#  Either the first and/or the second part of the tests
 591&nbsp;#+ may be a command or a function invocation string.
 592&nbsp;echo
 593&nbsp;echo '- - Test 1 for undefined - -'
 594&nbsp;declare -i t
 595&nbsp;_decT() {
 596&nbsp;    t=$t-1
 597&nbsp;}
 598&nbsp;
 599&nbsp;# Null reference, set: t == -1
 600&nbsp;t=${#VarNull}                           # Results in zero.
 601&nbsp;${VarNull- _decT }                      # Function executes, t now -1.
 602&nbsp;echo $t
 603&nbsp;
 604&nbsp;# Null contents, set: t == 0
 605&nbsp;t=${#VarEmpty}                          # Results in zero.
 606&nbsp;${VarEmpty- _decT }                     # _decT function NOT executed.
 607&nbsp;echo $t
 608&nbsp;
 609&nbsp;# Contents, set: t == number of non-null characters
 610&nbsp;VarSomething='_simple'                  # Set to valid function name.
 611&nbsp;t=${#VarSomething}                      # non-zero length
 612&nbsp;${VarSomething- _decT }                 # Function _simple executed.
 613&nbsp;echo $t                                 # Note the Append-To action.
 614&nbsp;
 615&nbsp;# Exercise: clean up that example.
 616&nbsp;unset t
 617&nbsp;unset _decT
 618&nbsp;VarSomething=Literal
 619&nbsp;
 620&nbsp;echo
 621&nbsp;echo '- - Test and Change - -'
 622&nbsp;echo '- Assignment if null reference -'
 623&nbsp;echo -n ${VarNull='NotSet'}' '          # NotSet NotSet
 624&nbsp;echo ${VarNull}
 625&nbsp;unset VarNull
 626&nbsp;
 627&nbsp;echo '- Assignment if null reference -'
 628&nbsp;echo -n ${VarNull:='NotSet'}' '         # NotSet NotSet
 629&nbsp;echo ${VarNull}
 630&nbsp;unset VarNull
 631&nbsp;
 632&nbsp;echo '- No assignment if null contents -'
 633&nbsp;echo -n ${VarEmpty='Empty'}' '          # Space only
 634&nbsp;echo ${VarEmpty}
 635&nbsp;VarEmpty=''
 636&nbsp;
 637&nbsp;echo '- Assignment if null contents -'
 638&nbsp;echo -n ${VarEmpty:='Empty'}' '         # Empty Empty
 639&nbsp;echo ${VarEmpty}
 640&nbsp;VarEmpty=''
 641&nbsp;
 642&nbsp;echo '- No change if already has contents -'
 643&nbsp;echo ${VarSomething='Content'}          # Literal
 644&nbsp;echo ${VarSomething:='Content'}         # Literal
 645&nbsp;
 646&nbsp;
 647&nbsp;# "Subscript sparse" Bash-Arrays
 648&nbsp;###
 649&nbsp;#  Bash-Arrays are subscript packed, beginning with
 650&nbsp;#+ subscript zero unless otherwise specified.
 651&nbsp;###
 652&nbsp;#  The initialization of ArrayVar was one way
 653&nbsp;#+ to "otherwise specify".  Here is the other way:
 654&nbsp;###
 655&nbsp;echo
 656&nbsp;declare -a ArraySparse
 657&nbsp;ArraySparse=( [1]=one [2]='' [4]='four' )
 658&nbsp;# [0]=null reference, [2]=null content, [3]=null reference
 659&nbsp;
 660&nbsp;echo '- - Array-Sparse List - -'
 661&nbsp;# Within double-quotes, default IFS, Glob-Pattern
 662&nbsp;
 663&nbsp;IFS=$'\x20'$'\x09'$'\x0A'
 664&nbsp;printf %q "${ArraySparse[*]}"
 665&nbsp;echo
 666&nbsp;
 667&nbsp;#  Note that the output does not distinguish between "null content"
 668&nbsp;#+ and "null reference".
 669&nbsp;#  Both print as escaped whitespace.
 670&nbsp;###
 671&nbsp;#  Note also that the output does NOT contain escaped whitespace
 672&nbsp;#+ for the "null reference(s)" prior to the first defined element.
 673&nbsp;###
 674&nbsp;# This behavior of 2.04, 2.05a and 2.05b has been reported
 675&nbsp;#+ and may change in a future version of Bash.
 676&nbsp;
 677&nbsp;#  To output a sparse array and maintain the [subscript]=value
 678&nbsp;#+ relationship without change requires a bit of programming.
 679&nbsp;#  One possible code fragment:
 680&nbsp;###
 681&nbsp;# local l=${#ArraySparse[@]}        # Count of defined elements
 682&nbsp;# local f=0                         # Count of found subscripts
 683&nbsp;# local i=0                         # Subscript to test
 684&nbsp;(                                   # Anonymous in-line function
 685&nbsp;    for (( l=${#ArraySparse[@]}, f = 0, i = 0 ; f &#60; l ; i++ ))
 686&nbsp;    do
 687&nbsp;        # 'if defined then...'
 688&nbsp;        ${ArraySparse[$i]+ eval echo '\ ['$i']='${ArraySparse[$i]} ; (( f++ )) }
 689&nbsp;    done
 690&nbsp;)
 691&nbsp;
 692&nbsp;# The reader coming upon the above code fragment cold
 693&nbsp;#+ might want to review "command lists" and "multiple commands on a line"
 694&nbsp;#+ in the text of the foregoing "Advanced Bash Scripting Guide."
 695&nbsp;###
 696&nbsp;#  Note:
 697&nbsp;#  The "read -a array_name" version of the "read" command
 698&nbsp;#+ begins filling array_name at subscript zero.
 699&nbsp;#  ArraySparse does not define a value at subscript zero.
 700&nbsp;###
 701&nbsp;#  The user needing to read/write a sparse array to either
 702&nbsp;#+ external storage or a communications socket must invent
 703&nbsp;#+ a read/write code pair suitable for their purpose.
 704&nbsp;###
 705&nbsp;# Exercise: clean it up.
 706&nbsp;
 707&nbsp;unset ArraySparse
 708&nbsp;
 709&nbsp;echo
 710&nbsp;echo '- - Conditional alternate (But not change)- -'
 711&nbsp;echo '- No alternate if null reference -'
 712&nbsp;echo -n ${VarNull+'NotSet'}' '
 713&nbsp;echo ${VarNull}
 714&nbsp;unset VarNull
 715&nbsp;
 716&nbsp;echo '- No alternate if null reference -'
 717&nbsp;echo -n ${VarNull:+'NotSet'}' '
 718&nbsp;echo ${VarNull}
 719&nbsp;unset VarNull
 720&nbsp;
 721&nbsp;echo '- Alternate if null contents -'
 722&nbsp;echo -n ${VarEmpty+'Empty'}' '              # Empty
 723&nbsp;echo ${VarEmpty}
 724&nbsp;VarEmpty=''
 725&nbsp;
 726&nbsp;echo '- No alternate if null contents -'
 727&nbsp;echo -n ${VarEmpty:+'Empty'}' '             # Space only
 728&nbsp;echo ${VarEmpty}
 729&nbsp;VarEmpty=''
 730&nbsp;
 731&nbsp;echo '- Alternate if already has contents -'
 732&nbsp;
 733&nbsp;# Alternate literal
 734&nbsp;echo -n ${VarSomething+'Content'}' '        # Content Literal
 735&nbsp;echo ${VarSomething}
 736&nbsp;
 737&nbsp;# Invoke function
 738&nbsp;echo -n ${VarSomething:+ $(_simple) }' '    # SimpleFunc Literal
 739&nbsp;echo ${VarSomething}
 740&nbsp;echo
 741&nbsp;
 742&nbsp;echo '- - Sparse Array - -'
 743&nbsp;echo ${ArrayVar[@]+'Empty'}                 # An array of 'Empty'(ies)
 744&nbsp;echo
 745&nbsp;
 746&nbsp;echo '- - Test 2 for undefined - -'
 747&nbsp;
 748&nbsp;declare -i t
 749&nbsp;_incT() {
 750&nbsp;    t=$t+1
 751&nbsp;}
 752&nbsp;
 753&nbsp;#  Note:
 754&nbsp;#  This is the same test used in the sparse array
 755&nbsp;#+ listing code fragment.
 756&nbsp;
 757&nbsp;# Null reference, set: t == -1
 758&nbsp;t=${#VarNull}-1                     # Results in minus-one.
 759&nbsp;${VarNull+ _incT }                  # Does not execute.
 760&nbsp;echo $t' Null reference'
 761&nbsp;
 762&nbsp;# Null contents, set: t == 0
 763&nbsp;t=${#VarEmpty}-1                    # Results in minus-one.
 764&nbsp;${VarEmpty+ _incT }                 # Executes.
 765&nbsp;echo $t'  Null content'
 766&nbsp;
 767&nbsp;# Contents, set: t == (number of non-null characters)
 768&nbsp;t=${#VarSomething}-1                # non-null length minus-one
 769&nbsp;${VarSomething+ _incT }             # Executes.
 770&nbsp;echo $t'  Contents'
 771&nbsp;
 772&nbsp;# Exercise: clean up that example.
 773&nbsp;unset t
 774&nbsp;unset _incT
 775&nbsp;
 776&nbsp;# ${name?err_msg} ${name:?err_msg}
 777&nbsp;#  These follow the same rules but always exit afterwards
 778&nbsp;#+ if an action is specified following the question mark.
 779&nbsp;#  The action following the question mark may be a literal
 780&nbsp;#+ or a function result.
 781&nbsp;###
 782&nbsp;#  ${name?} ${name:?} are test-only, the return can be tested.
 783&nbsp;
 784&nbsp;
 785&nbsp;
 786&nbsp;
 787&nbsp;# Element operations
 788&nbsp;# ------------------
 789&nbsp;
 790&nbsp;echo
 791&nbsp;echo '- - Trailing sub-element selection - -'
 792&nbsp;
 793&nbsp;#  Strings, Arrays and Positional parameters
 794&nbsp;
 795&nbsp;#  Call this script with multiple arguments
 796&nbsp;#+ to see the parameter selections.
 797&nbsp;
 798&nbsp;echo '- All -'
 799&nbsp;echo ${VarSomething:0}              # all non-null characters
 800&nbsp;echo ${ArrayVar[@]:0}               # all elements with content
 801&nbsp;echo ${@:0}                         # all parameters with content;
 802&nbsp;                                    # ignoring parameter[0]
 803&nbsp;
 804&nbsp;echo
 805&nbsp;echo '- All after -'
 806&nbsp;echo ${VarSomething:1}              # all non-null after character[0]
 807&nbsp;echo ${ArrayVar[@]:1}               # all after element[0] with content
 808&nbsp;echo ${@:2}                         # all after param[1] with content
 809&nbsp;
 810&nbsp;echo
 811&nbsp;echo '- Range after -'
 812&nbsp;echo ${VarSomething:4:3}            # ral
 813&nbsp;                                    # Three characters after
 814&nbsp;                                    # character[3]
 815&nbsp;
 816&nbsp;echo '- Sparse array gotch -'
 817&nbsp;echo ${ArrayVar[@]:1:2}     #  four - The only element with content.
 818&nbsp;                            #  Two elements after (if that many exist).
 819&nbsp;                            #  the FIRST WITH CONTENTS
 820&nbsp;                            #+ (the FIRST WITH  CONTENTS is being
 821&nbsp;                            #+ considered as if it
 822&nbsp;                            #+ were subscript zero).
 823&nbsp;#  Executed as if Bash considers ONLY array elements with CONTENT
 824&nbsp;#  printf %q "${ArrayVar[@]:0:3}"    # Try this one
 825&nbsp;
 826&nbsp;#  In versions 2.04, 2.05a and 2.05b,
 827&nbsp;#+ Bash does not handle sparse arrays as expected using this notation.
 828&nbsp;#
 829&nbsp;#  The current Bash maintainer, Chet Ramey, has corrected this.
 830&nbsp;
 831&nbsp;
 832&nbsp;echo '- Non-sparse array -'
 833&nbsp;echo ${@:2:2}               # Two parameters following parameter[1]
 834&nbsp;
 835&nbsp;# New victims for string vector examples:
 836&nbsp;stringZ=abcABC123ABCabc
 837&nbsp;arrayZ=( abcabc ABCABC 123123 ABCABC abcabc )
 838&nbsp;sparseZ=( [1]='abcabc' [3]='ABCABC' [4]='' [5]='123123' )
 839&nbsp;
 840&nbsp;echo
 841&nbsp;echo ' - - Victim string - -'$stringZ'- - '
 842&nbsp;echo ' - - Victim array - -'${arrayZ[@]}'- - '
 843&nbsp;echo ' - - Sparse array - -'${sparseZ[@]}'- - '
 844&nbsp;echo ' - [0]==null ref, [2]==null ref, [4]==null content - '
 845&nbsp;echo ' - [1]=abcabc [3]=ABCABC [5]=123123 - '
 846&nbsp;echo ' - non-null-reference count: '${#sparseZ[@]}' elements'
 847&nbsp;
 848&nbsp;echo
 849&nbsp;echo '- - Prefix sub-element removal - -'
 850&nbsp;echo '- - Glob-Pattern match must include the first character. - -'
 851&nbsp;echo '- - Glob-Pattern may be a literal or a function result. - -'
 852&nbsp;echo
 853&nbsp;
 854&nbsp;
 855&nbsp;# Function returning a simple, Literal, Glob-Pattern
 856&nbsp;_abc() {
 857&nbsp;    echo -n 'abc'
 858&nbsp;}
 859&nbsp;
 860&nbsp;echo '- Shortest prefix -'
 861&nbsp;echo ${stringZ#123}                 # Unchanged (not a prefix).
 862&nbsp;echo ${stringZ#$(_abc)}             # ABC123ABCabc
 863&nbsp;echo ${arrayZ[@]#abc}               # Applied to each element.
 864&nbsp;
 865&nbsp;# echo ${sparseZ[@]#abc}            # Version-2.05b core dumps.
 866&nbsp;# Has since been fixed by Chet Ramey.
 867&nbsp;
 868&nbsp;# The -it would be nice- First-Subscript-Of
 869&nbsp;# echo ${#sparseZ[@]#*}             # This is NOT valid Bash.
 870&nbsp;
 871&nbsp;echo
 872&nbsp;echo '- Longest prefix -'
 873&nbsp;echo ${stringZ##1*3}                # Unchanged (not a prefix)
 874&nbsp;echo ${stringZ##a*C}                # abc
 875&nbsp;echo ${arrayZ[@]##a*c}              # ABCABC 123123 ABCABC
 876&nbsp;
 877&nbsp;# echo ${sparseZ[@]##a*c}           # Version-2.05b core dumps.
 878&nbsp;# Has since been fixed by Chet Ramey.
 879&nbsp;
 880&nbsp;echo
 881&nbsp;echo '- - Suffix sub-element removal - -'
 882&nbsp;echo '- - Glob-Pattern match must include the last character. - -'
 883&nbsp;echo '- - Glob-Pattern may be a literal or a function result. - -'
 884&nbsp;echo
 885&nbsp;echo '- Shortest suffix -'
 886&nbsp;echo ${stringZ%1*3}                 # Unchanged (not a suffix).
 887&nbsp;echo ${stringZ%$(_abc)}             # abcABC123ABC
 888&nbsp;echo ${arrayZ[@]%abc}               # Applied to each element.
 889&nbsp;
 890&nbsp;# echo ${sparseZ[@]%abc}            # Version-2.05b core dumps.
 891&nbsp;# Has since been fixed by Chet Ramey.
 892&nbsp;
 893&nbsp;# The -it would be nice- Last-Subscript-Of
 894&nbsp;# echo ${#sparseZ[@]%*}             # This is NOT valid Bash.
 895&nbsp;
 896&nbsp;echo
 897&nbsp;echo '- Longest suffix -'
 898&nbsp;echo ${stringZ%%1*3}                # Unchanged (not a suffix)
 899&nbsp;echo ${stringZ%%b*c}                # a
 900&nbsp;echo ${arrayZ[@]%%b*c}              # a ABCABC 123123 ABCABC a
 901&nbsp;
 902&nbsp;# echo ${sparseZ[@]%%b*c}           # Version-2.05b core dumps.
 903&nbsp;# Has since been fixed by Chet Ramey.
 904&nbsp;
 905&nbsp;echo
 906&nbsp;echo '- - Sub-element replacement - -'
 907&nbsp;echo '- - Sub-element at any location in string. - -'
 908&nbsp;echo '- - First specification is a Glob-Pattern - -'
 909&nbsp;echo '- - Glob-Pattern may be a literal or Glob-Pattern function result. - -'
 910&nbsp;echo '- - Second specification may be a literal or function result. - -'
 911&nbsp;echo '- - Second specification may be unspecified. Pronounce that'
 912&nbsp;echo '    as: Replace-With-Nothing (Delete) - -'
 913&nbsp;echo
 914&nbsp;
 915&nbsp;
 916&nbsp;
 917&nbsp;# Function returning a simple, Literal, Glob-Pattern
 918&nbsp;_123() {
 919&nbsp;    echo -n '123'
 920&nbsp;}
 921&nbsp;
 922&nbsp;echo '- Replace first occurrence -'
 923&nbsp;echo ${stringZ/$(_123)/999}         # Changed (123 is a component).
 924&nbsp;echo ${stringZ/ABC/xyz}             # xyzABC123ABCabc
 925&nbsp;echo ${arrayZ[@]/ABC/xyz}           # Applied to each element.
 926&nbsp;echo ${sparseZ[@]/ABC/xyz}          # Works as expected.
 927&nbsp;
 928&nbsp;echo
 929&nbsp;echo '- Delete first occurrence -'
 930&nbsp;echo ${stringZ/$(_123)/}
 931&nbsp;echo ${stringZ/ABC/}
 932&nbsp;echo ${arrayZ[@]/ABC/}
 933&nbsp;echo ${sparseZ[@]/ABC/}
 934&nbsp;
 935&nbsp;#  The replacement need not be a literal,
 936&nbsp;#+ since the result of a function invocation is allowed.
 937&nbsp;#  This is general to all forms of replacement.
 938&nbsp;echo
 939&nbsp;echo '- Replace first occurrence with Result-Of -'
 940&nbsp;echo ${stringZ/$(_123)/$(_simple)}  # Works as expected.
 941&nbsp;echo ${arrayZ[@]/ca/$(_simple)}     # Applied to each element.
 942&nbsp;echo ${sparseZ[@]/ca/$(_simple)}    # Works as expected.
 943&nbsp;
 944&nbsp;echo
 945&nbsp;echo '- Replace all occurrences -'
 946&nbsp;echo ${stringZ//[b2]/X}             # X-out b's and 2's
 947&nbsp;echo ${stringZ//abc/xyz}            # xyzABC123ABCxyz
 948&nbsp;echo ${arrayZ[@]//abc/xyz}          # Applied to each element.
 949&nbsp;echo ${sparseZ[@]//abc/xyz}         # Works as expected.
 950&nbsp;
 951&nbsp;echo
 952&nbsp;echo '- Delete all occurrences -'
 953&nbsp;echo ${stringZ//[b2]/}
 954&nbsp;echo ${stringZ//abc/}
 955&nbsp;echo ${arrayZ[@]//abc/}
 956&nbsp;echo ${sparseZ[@]//abc/}
 957&nbsp;
 958&nbsp;echo
 959&nbsp;echo '- - Prefix sub-element replacement - -'
 960&nbsp;echo '- - Match must include the first character. - -'
 961&nbsp;echo
 962&nbsp;
 963&nbsp;echo '- Replace prefix occurrences -'
 964&nbsp;echo ${stringZ/#[b2]/X}             # Unchanged (neither is a prefix).
 965&nbsp;echo ${stringZ/#$(_abc)/XYZ}        # XYZABC123ABCabc
 966&nbsp;echo ${arrayZ[@]/#abc/XYZ}          # Applied to each element.
 967&nbsp;echo ${sparseZ[@]/#abc/XYZ}         # Works as expected.
 968&nbsp;
 969&nbsp;echo
 970&nbsp;echo '- Delete prefix occurrences -'
 971&nbsp;echo ${stringZ/#[b2]/}
 972&nbsp;echo ${stringZ/#$(_abc)/}
 973&nbsp;echo ${arrayZ[@]/#abc/}
 974&nbsp;echo ${sparseZ[@]/#abc/}
 975&nbsp;
 976&nbsp;echo
 977&nbsp;echo '- - Suffix sub-element replacement - -'
 978&nbsp;echo '- - Match must include the last character. - -'
 979&nbsp;echo
 980&nbsp;
 981&nbsp;echo '- Replace suffix occurrences -'
 982&nbsp;echo ${stringZ/%[b2]/X}             # Unchanged (neither is a suffix).
 983&nbsp;echo ${stringZ/%$(_abc)/XYZ}        # abcABC123ABCXYZ
 984&nbsp;echo ${arrayZ[@]/%abc/XYZ}          # Applied to each element.
 985&nbsp;echo ${sparseZ[@]/%abc/XYZ}         # Works as expected.
 986&nbsp;
 987&nbsp;echo
 988&nbsp;echo '- Delete suffix occurrences -'
 989&nbsp;echo ${stringZ/%[b2]/}
 990&nbsp;echo ${stringZ/%$(_abc)/}
 991&nbsp;echo ${arrayZ[@]/%abc/}
 992&nbsp;echo ${sparseZ[@]/%abc/}
 993&nbsp;
 994&nbsp;echo
 995&nbsp;echo '- - Special cases of null Glob-Pattern - -'
 996&nbsp;echo
 997&nbsp;
 998&nbsp;echo '- Prefix all -'
 999&nbsp;# null substring pattern means 'prefix'
 1000&nbsp;echo ${stringZ/#/NEW}               # NEWabcABC123ABCabc
 1001&nbsp;echo ${arrayZ[@]/#/NEW}             # Applied to each element.
 1002&nbsp;echo ${sparseZ[@]/#/NEW}            # Applied to null-content also.
 1003&nbsp;                                    # That seems reasonable.
 1004&nbsp;
 1005&nbsp;echo
 1006&nbsp;echo '- Suffix all -'
 1007&nbsp;# null substring pattern means 'suffix'
 1008&nbsp;echo ${stringZ/%/NEW}               # abcABC123ABCabcNEW
 1009&nbsp;echo ${arrayZ[@]/%/NEW}             # Applied to each element.
 1010&nbsp;echo ${sparseZ[@]/%/NEW}            # Applied to null-content also.
 1011&nbsp;                                    # That seems reasonable.
 1012&nbsp;
 1013&nbsp;echo
 1014&nbsp;echo '- - Special case For-Each Glob-Pattern - -'
 1015&nbsp;echo '- - - - This is a nice-to-have dream - - - -'
 1016&nbsp;echo
 1017&nbsp;
 1018&nbsp;_GenFunc() {
 1019&nbsp;    echo -n ${0}                    # Illustration only.
 1020&nbsp;    # Actually, that would be an arbitrary computation.
 1021&nbsp;}
 1022&nbsp;
 1023&nbsp;# All occurrences, matching the AnyThing pattern.
 1024&nbsp;# Currently //*/ does not match null-content nor null-reference.
 1025&nbsp;# /#/ and /%/ does match null-content but not null-reference.
 1026&nbsp;echo ${sparseZ[@]//*/$(_GenFunc)}
 1027&nbsp;
 1028&nbsp;
 1029&nbsp;#  A possible syntax would be to make
 1030&nbsp;#+ the parameter notation used within this construct mean:
 1031&nbsp;#   ${1} - The full element
 1032&nbsp;#   ${2} - The prefix, if any, to the matched sub-element
 1033&nbsp;#   ${3} - The matched sub-element
 1034&nbsp;#   ${4} - The suffix, if any, to the matched sub-element
 1035&nbsp;#
 1036&nbsp;# echo ${sparseZ[@]//*/$(_GenFunc ${3})}   # Same as ${1} here.
 1037&nbsp;# Perhaps it will be implemented in a future version of Bash.
 1038&nbsp;
 1039&nbsp;
 1040&nbsp;exit 0</PRE
></TD
></TR
></TABLE
><HR></DIV
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="TESTEXECTIME"
></A
><P
><B
>Example A-59. Testing execution times of various commands</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#!/bin/bash
   2&nbsp;#  test-execution-time.sh
   3&nbsp;#  Example by Erik Brandsberg, for testing execution time
   4&nbsp;#+ of certain operations.
   5&nbsp;#  Referenced in the "Optimizations" section of "Miscellany" chapter.
   6&nbsp;
   7&nbsp;count=50000
   8&nbsp;echo "Math tests"
   9&nbsp;echo "Math via \$(( ))"
  10&nbsp;time for (( i=0; i&#60; $count; i++))
  11&nbsp;do
  12&nbsp;  result=$(( $i%2 ))
  13&nbsp;done
  14&nbsp;
  15&nbsp;echo "Math via *expr*:"
  16&nbsp;time for (( i=0; i&#60; $count; i++))
  17&nbsp;do
  18&nbsp;  result=`expr "$i%2"`
  19&nbsp;done
  20&nbsp;
  21&nbsp;echo "Math via *let*:"
  22&nbsp;time for (( i=0; i&#60; $count; i++))
  23&nbsp;do
  24&nbsp;  let result=$i%2
  25&nbsp;done
  26&nbsp;
  27&nbsp;echo
  28&nbsp;echo "Conditional testing tests"
  29&nbsp;
  30&nbsp;echo "Test via case:"
  31&nbsp;time for (( i=0; i&#60; $count; i++))
  32&nbsp;do
  33&nbsp;  case $(( $i%2 )) in
  34&nbsp;    0) : ;;
  35&nbsp;    1) : ;;
  36&nbsp;  esac
  37&nbsp;done
  38&nbsp;
  39&nbsp;echo "Test with if [], no quotes:"
  40&nbsp;time for (( i=0; i&#60; $count; i++))
  41&nbsp;do
  42&nbsp;  if [ $(( $i%2 )) = 0 ]; then
  43&nbsp;     :
  44&nbsp;  else
  45&nbsp;     :
  46&nbsp;  fi
  47&nbsp;done
  48&nbsp;
  49&nbsp;echo "Test with if [], quotes:"
  50&nbsp;time for (( i=0; i&#60; $count; i++))
  51&nbsp;do
  52&nbsp;  if [ "$(( $i%2 ))" = "0" ]; then
  53&nbsp;     :
  54&nbsp;  else
  55&nbsp;     :
  56&nbsp;  fi
  57&nbsp;done
  58&nbsp;
  59&nbsp;echo "Test with if [], using -eq:"
  60&nbsp;time for (( i=0; i&#60; $count; i++))
  61&nbsp;do
  62&nbsp;  if [ $(( $i%2 )) -eq 0 ]; then
  63&nbsp;     :
  64&nbsp;  else
  65&nbsp;     :
  66&nbsp;  fi
  67&nbsp;done
  68&nbsp;
  69&nbsp;exit $?</PRE
></TD
></TR
></TABLE
><HR></DIV
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="ASSOCARRTEST"
></A
><P
><B
>Example A-60. Associative arrays vs. conventional arrays (execution
	    times)</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#!/bin/bash
   2&nbsp;#  assoc-arr-test.sh
   3&nbsp;#  Benchmark test script to compare execution times of
   4&nbsp;#  numeric-indexed array vs. associative array.
   5&nbsp;#     Thank you, Erik Brandsberg.
   6&nbsp;
   7&nbsp;count=100000       # May take a while for some of the tests below.
   8&nbsp;declare simple     # Can change to 20000, if desired.
   9&nbsp;declare -a array1
  10&nbsp;declare -A array2
  11&nbsp;declare -a array3
  12&nbsp;declare -A array4
  13&nbsp;
  14&nbsp;echo "===Assignment tests==="
  15&nbsp;echo
  16&nbsp;
  17&nbsp;echo "Assigning a simple variable:"
  18&nbsp;# References $i twice to equalize lookup times.
  19&nbsp;time for (( i=0; i&#60; $count; i++)); do
  20&nbsp;        simple=$i$i
  21&nbsp;done
  22&nbsp;
  23&nbsp;echo "---"
  24&nbsp;
  25&nbsp;echo "Assigning a numeric index array entry:"
  26&nbsp;time for (( i=0; i&#60; $count; i++)); do
  27&nbsp;        array1[$i]=$i
  28&nbsp;done
  29&nbsp;
  30&nbsp;echo "---"
  31&nbsp;
  32&nbsp;echo "Overwriting a numeric index array entry:"
  33&nbsp;time for (( i=0; i&#60; $count; i++)); do
  34&nbsp;        array1[$i]=$i
  35&nbsp;done
  36&nbsp;
  37&nbsp;echo "---"
  38&nbsp;
  39&nbsp;echo "Linear reading of numeric index array:"
  40&nbsp;time for (( i=0; i&#60; $count; i++)); do
  41&nbsp;        simple=array1[$i]
  42&nbsp;done
  43&nbsp;
  44&nbsp;echo "---"
  45&nbsp;
  46&nbsp;echo "Assigning an associative array entry:"
  47&nbsp;time for (( i=0; i&#60; $count; i++)); do
  48&nbsp;        array2[$i]=$i
  49&nbsp;done
  50&nbsp;
  51&nbsp;echo "---"
  52&nbsp;
  53&nbsp;echo "Overwriting an associative array entry:"
  54&nbsp;time for (( i=0; i&#60; $count; i++)); do
  55&nbsp;        array2[$i]=$i
  56&nbsp;done
  57&nbsp;
  58&nbsp;echo "---"
  59&nbsp;
  60&nbsp;echo "Linear reading an associative array entry:"
  61&nbsp;time for (( i=0; i&#60; $count; i++)); do
  62&nbsp;        simple=array2[$i]
  63&nbsp;done
  64&nbsp;
  65&nbsp;echo "---"
  66&nbsp;
  67&nbsp;echo "Assigning a random number to a simple variable:"
  68&nbsp;time for (( i=0; i&#60; $count; i++)); do
  69&nbsp;        simple=$RANDOM
  70&nbsp;done
  71&nbsp;
  72&nbsp;echo "---"
  73&nbsp;
  74&nbsp;echo "Assign a sparse numeric index array entry randomly into 64k cells:"
  75&nbsp;time for (( i=0; i&#60; $count; i++)); do
  76&nbsp;        array3[$RANDOM]=$i
  77&nbsp;done
  78&nbsp;
  79&nbsp;echo "---"
  80&nbsp;
  81&nbsp;echo "Reading sparse numeric index array entry:"
  82&nbsp;time for value in "${array3[@]}"i; do
  83&nbsp;        simple=$value
  84&nbsp;done
  85&nbsp;
  86&nbsp;echo "---"
  87&nbsp;
  88&nbsp;echo "Assigning a sparse associative array entry randomly into 64k cells:"
  89&nbsp;time for (( i=0; i&#60; $count; i++)); do
  90&nbsp;        array4[$RANDOM]=$i
  91&nbsp;done
  92&nbsp;
  93&nbsp;echo "---"
  94&nbsp;
  95&nbsp;echo "Reading sparse associative index array entry:"
  96&nbsp;time for value in "${array4[@]}"; do
  97&nbsp;        simple=$value
  98&nbsp;done
  99&nbsp;
 100&nbsp;exit $?</PRE
></TD
></TR
></TABLE
><HR></DIV
></DIV
><DIV
CLASS="NAVFOOTER"
><HR
ALIGN="LEFT"
WIDTH="100%"><TABLE
SUMMARY="Footer navigation table"
WIDTH="100%"
BORDER="0"
CELLPADDING="0"
CELLSPACING="0"
><TR
><TD
WIDTH="33%"
ALIGN="left"
VALIGN="top"
><A
HREF="biblio.html"
ACCESSKEY="P"
>Prev</A
></TD
><TD
WIDTH="34%"
ALIGN="center"
VALIGN="top"
><A
HREF="index.html"
ACCESSKEY="H"
>Home</A
></TD
><TD
WIDTH="33%"
ALIGN="right"
VALIGN="top"
><A
HREF="refcards.html"
ACCESSKEY="N"
>Next</A
></TD
></TR
><TR
><TD
WIDTH="33%"
ALIGN="left"
VALIGN="top"
>Bibliography</TD
><TD
WIDTH="34%"
ALIGN="center"
VALIGN="top"
>&nbsp;</TD
><TD
WIDTH="33%"
ALIGN="right"
VALIGN="top"
>Reference Cards</TD
></TR
></TABLE
></DIV
></BODY
></HTML
>