File: assortedtips.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 (1904 lines) | stat: -rw-r--r-- 40,282 bytes parent folder | download | duplicates (3)
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
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML
><HEAD
><TITLE
>Assorted Tips</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="UP"
TITLE="Miscellany"
HREF="miscellany.html"><LINK
REL="PREVIOUS"
TITLE="Optimizations"
HREF="optimizations.html"><LINK
REL="NEXT"
TITLE="Security Issues"
HREF="securityissues.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="SECT1"
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="optimizations.html"
ACCESSKEY="P"
>Prev</A
></TD
><TD
WIDTH="80%"
ALIGN="center"
VALIGN="bottom"
>Chapter 36. Miscellany</TD
><TD
WIDTH="10%"
ALIGN="right"
VALIGN="bottom"
><A
HREF="securityissues.html"
ACCESSKEY="N"
>Next</A
></TD
></TR
></TABLE
><HR
ALIGN="LEFT"
WIDTH="100%"></DIV
><DIV
CLASS="SECT1"
><H1
CLASS="SECT1"
><A
NAME="ASSORTEDTIPS"
></A
>36.7. Assorted Tips</H1
><DIV
CLASS="SECT2"
><H2
CLASS="SECT2"
><A
NAME="AEN20460"
></A
>36.7.1. Ideas for more powerful scripts</H2
><UL
><LI
><P
><A
NAME="PSEUDOCODEREF"
></A
></P
><P
>You have a problem that you want to solve by writing a Bash
	     script. Unfortunately, you don't know quite where to start.
	     One method is to plunge right in and code those parts
	     of the script that come easily, and write the hard parts as
	     <I
CLASS="FIRSTTERM"
>pseudo-code</I
>.</P
><P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="90%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#!/bin/bash
   2&nbsp;
   3&nbsp;ARGCOUNT=1                     # Need name as argument.
   4&nbsp;E_WRONGARGS=65
   5&nbsp;
   6&nbsp;if [ number-of-arguments is-not-equal-to "$ARGCOUNT" ]
   7&nbsp;#    ^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^
   8&nbsp;#  Can't figure out how to code this . . .
   9&nbsp;#+ . . . so write it in pseudo-code.
  10&nbsp;
  11&nbsp;then
  12&nbsp;  echo "Usage: name-of-script name"
  13&nbsp;  #            ^^^^^^^^^^^^^^     More pseudo-code.
  14&nbsp;  exit $E_WRONGARGS
  15&nbsp;fi 
  16&nbsp;
  17&nbsp;. . .
  18&nbsp;
  19&nbsp;exit 0
  20&nbsp;
  21&nbsp;
  22&nbsp;# Later on, substitute working code for the pseudo-code.
  23&nbsp;
  24&nbsp;# Line 6 becomes:
  25&nbsp;if [ $# -ne "$ARGCOUNT" ]
  26&nbsp;
  27&nbsp;# Line 12 becomes:
  28&nbsp;  echo "Usage: `basename $0` name"</PRE
></TD
></TR
></TABLE
></P
><P
>For an example of using pseudo-code, see the <A
HREF="writingscripts.html#NEWTONSQRT"
>Square Root</A
> exercise.</P
></LI
><LI
><P
><A
NAME="TRACKINGSCR"
></A
></P
><P
>To keep a record of which user scripts have run
	    during a particular session or over a number of sessions,
	    add the following lines to each script you want to keep track
	    of. This will keep a continuing file record of the script
	    names and invocation times. </P
><P
>	  <TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="90%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;# Append (&#62;&#62;) following to end of each script tracked.
   2&nbsp;
   3&nbsp;whoami&#62;&#62; $SAVE_FILE    # User invoking the script.
   4&nbsp;echo $0&#62;&#62; $SAVE_FILE   # Script name.
   5&nbsp;date&#62;&#62; $SAVE_FILE      # Date and time.
   6&nbsp;echo&#62;&#62; $SAVE_FILE      # Blank line as separator.
   7&nbsp;
   8&nbsp;#  Of course, SAVE_FILE defined and exported as environmental variable in ~/.bashrc
   9&nbsp;#+ (something like ~/.scripts-run)</PRE
></TD
></TR
></TABLE
>
          </P
></LI
><LI
><P
><A
NAME="PREPENDREF"
></A
></P
><P
>The <SPAN
CLASS="TOKEN"
>&#62;&#62;</SPAN
> operator
	    <I
CLASS="FIRSTTERM"
>appends</I
> lines to a file.
	    What if you wish to <I
CLASS="FIRSTTERM"
>prepend</I
> a
	    line to an existing file, that is, to paste it in at the
	    beginning?</P
><P
>	  <TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="90%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;file=data.txt
   2&nbsp;title="***This is the title line of data text file***"
   3&nbsp;
   4&nbsp;echo $title | cat - $file &#62;$file.new
   5&nbsp;# "cat -" concatenates stdout to $file.
   6&nbsp;#  End result is
   7&nbsp;#+ to write a new file with $title appended at *beginning*.</PRE
></TD
></TR
></TABLE
>
	  </P
><P
>This is a simplified variant of the <A
HREF="here-docs.html#PREPENDEX"
>Example 19-13</A
> script given earlier.	And, of course,
	    <A
HREF="sedawk.html#SEDREF"
>sed</A
> can also do this.</P
></LI
><LI
><P
><A
NAME="SCRIPTASEMB"
></A
></P
><P
>A shell script may act as an embedded command inside
	    another shell script, a <I
CLASS="FIRSTTERM"
>Tcl</I
> or
	    <I
CLASS="FIRSTTERM"
>wish</I
> script, or even a <A
HREF="filearchiv.html#MAKEFILEREF"
>Makefile</A
>. It can be invoked
	    as an external shell command in a C program using the
	    <TT
CLASS="REPLACEABLE"
><I
>system()</I
></TT
> call, i.e.,
	   <TT
CLASS="REPLACEABLE"
><I
>system("script_name");</I
></TT
>.</P
></LI
><LI
><P
><A
NAME="SETVAREMB"
></A
></P
><P
>Setting a variable to the contents of an embedded
	    <I
CLASS="FIRSTTERM"
>sed</I
> or <I
CLASS="FIRSTTERM"
>awk</I
>
	    script increases the readability of the surrounding <A
HREF="wrapper.html#SHWRAPPER"
>shell wrapper</A
>. See <A
HREF="contributed-scripts.html#MAILFORMAT"
>Example A-1</A
> and <A
HREF="internal.html#COLTOTALER3"
>Example 15-20</A
>.</P
></LI
><LI
><P
><A
NAME="LIBROUTINES"
></A
></P
><P
>Put together files containing your favorite and most useful
	    definitions and functions.	As necessary,
	    <SPAN
CLASS="QUOTE"
>"include"</SPAN
> one or more of these
	    <SPAN
CLASS="QUOTE"
>"library files"</SPAN
> in scripts with either the
	    <A
HREF="special-chars.html#DOTREF"
>dot</A
> (<B
CLASS="COMMAND"
>.</B
>)
	    or <A
HREF="internal.html#SOURCEREF"
>source</A
> command.</P
><P
>  
            <TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="90%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;# SCRIPT LIBRARY
   2&nbsp;# ------ -------
   3&nbsp;
   4&nbsp;# Note:
   5&nbsp;# No "#!" here.
   6&nbsp;# No "live code" either.
   7&nbsp;
   8&nbsp;
   9&nbsp;# Useful variable definitions
  10&nbsp;
  11&nbsp;ROOT_UID=0             # Root has $UID 0.
  12&nbsp;E_NOTROOT=101          # Not root user error. 
  13&nbsp;MAXRETVAL=255          # Maximum (positive) return value of a function.
  14&nbsp;SUCCESS=0
  15&nbsp;FAILURE=-1
  16&nbsp;
  17&nbsp;
  18&nbsp;
  19&nbsp;# Functions
  20&nbsp;
  21&nbsp;Usage ()               # "Usage:" message.
  22&nbsp;{
  23&nbsp;  if [ -z "$1" ]       # No arg passed.
  24&nbsp;  then
  25&nbsp;    msg=filename
  26&nbsp;  else
  27&nbsp;    msg=$@
  28&nbsp;  fi
  29&nbsp;
  30&nbsp;  echo "Usage: `basename $0` "$msg""
  31&nbsp;}  
  32&nbsp;
  33&nbsp;
  34&nbsp;Check_if_root ()       # Check if root running script.
  35&nbsp;{                      # From "ex39.sh" example.
  36&nbsp;  if [ "$UID" -ne "$ROOT_UID" ]
  37&nbsp;  then
  38&nbsp;    echo "Must be root to run this script."
  39&nbsp;    exit $E_NOTROOT
  40&nbsp;  fi
  41&nbsp;}  
  42&nbsp;
  43&nbsp;
  44&nbsp;CreateTempfileName ()  # Creates a "unique" temp filename.
  45&nbsp;{                      # From "ex51.sh" example.
  46&nbsp;  prefix=temp
  47&nbsp;  suffix=`eval date +%s`
  48&nbsp;  Tempfilename=$prefix.$suffix
  49&nbsp;}
  50&nbsp;
  51&nbsp;
  52&nbsp;isalpha2 ()            # Tests whether *entire string* is alphabetic.
  53&nbsp;{                      # From "isalpha.sh" example.
  54&nbsp;  [ $# -eq 1 ] || return $FAILURE
  55&nbsp;
  56&nbsp;  case $1 in
  57&nbsp;  *[!a-zA-Z]*|"") return $FAILURE;;
  58&nbsp;  *) return $SUCCESS;;
  59&nbsp;  esac                 # Thanks, S.C.
  60&nbsp;}
  61&nbsp;
  62&nbsp;
  63&nbsp;abs ()                           # Absolute value.
  64&nbsp;{                                # Caution: Max return value = 255.
  65&nbsp;  E_ARGERR=-999999
  66&nbsp;
  67&nbsp;  if [ -z "$1" ]                 # Need arg passed.
  68&nbsp;  then
  69&nbsp;    return $E_ARGERR             # Obvious error value returned.
  70&nbsp;  fi
  71&nbsp;
  72&nbsp;  if [ "$1" -ge 0 ]              # If non-negative,
  73&nbsp;  then                           #
  74&nbsp;    absval=$1                    # stays as-is.
  75&nbsp;  else                           # Otherwise,
  76&nbsp;    let "absval = (( 0 - $1 ))"  # change sign.
  77&nbsp;  fi  
  78&nbsp;
  79&nbsp;  return $absval
  80&nbsp;}
  81&nbsp;
  82&nbsp;
  83&nbsp;tolower ()             #  Converts string(s) passed as argument(s)
  84&nbsp;{                      #+ to lowercase.
  85&nbsp;
  86&nbsp;  if [ -z "$1" ]       #  If no argument(s) passed,
  87&nbsp;  then                 #+ send error message
  88&nbsp;    echo "(null)"      #+ (C-style void-pointer error message)
  89&nbsp;    return             #+ and return from function.
  90&nbsp;  fi  
  91&nbsp;
  92&nbsp;  echo "$@" | tr A-Z a-z
  93&nbsp;  # Translate all passed arguments ($@).
  94&nbsp;
  95&nbsp;  return
  96&nbsp;
  97&nbsp;# Use command substitution to set a variable to function output.
  98&nbsp;# For example:
  99&nbsp;#    oldvar="A seT of miXed-caSe LEtTerS"
 100&nbsp;#    newvar=`tolower "$oldvar"`
 101&nbsp;#    echo "$newvar"    # a set of mixed-case letters
 102&nbsp;#
 103&nbsp;# Exercise: Rewrite this function to change lowercase passed argument(s)
 104&nbsp;#           to uppercase ... toupper()  [easy].
 105&nbsp;}</PRE
></TD
></TR
></TABLE
>
          </P
></LI
><LI
><P
><A
NAME="COMMENTH"
></A
></P
><P
>Use special-purpose comment headers to increase clarity
	    and legibility in scripts.</P
><P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="90%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;## Caution.
   2&nbsp;rm -rf *.zzy   ##  The "-rf" options to "rm" are very dangerous,
   3&nbsp;               ##+ especially with wild cards.
   4&nbsp;
   5&nbsp;#+ Line continuation.
   6&nbsp;#  This is line 1
   7&nbsp;#+ of a multi-line comment,
   8&nbsp;#+ and this is the final line.
   9&nbsp;
  10&nbsp;#* Note.
  11&nbsp;
  12&nbsp;#o List item.
  13&nbsp;
  14&nbsp;#&#62; Another point of view.
  15&nbsp;while [ "$var1" != "end" ]    #&#62; while test "$var1" != "end"</PRE
></TD
></TR
></TABLE
></P
></LI
><LI
><P
><A
NAME="PROGBAR"
></A
></P
><P
>Dotan Barak contributes template code for a
	  <I
CLASS="FIRSTTERM"
>progress bar</I
> in a script.</P
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="PROGRESSBAR"
></A
><P
><B
>Example 36-17. A Progress Bar</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="90%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#!/bin/bash
   2&nbsp;# progress-bar.sh
   3&nbsp;
   4&nbsp;# Author: Dotan Barak (very minor revisions by ABS Guide author).
   5&nbsp;# Used in ABS Guide with permission (thanks!).
   6&nbsp;
   7&nbsp;
   8&nbsp;BAR_WIDTH=50
   9&nbsp;BAR_CHAR_START="["
  10&nbsp;BAR_CHAR_END="]"
  11&nbsp;BAR_CHAR_EMPTY="."
  12&nbsp;BAR_CHAR_FULL="="
  13&nbsp;BRACKET_CHARS=2
  14&nbsp;LIMIT=100
  15&nbsp;
  16&nbsp;print_progress_bar()
  17&nbsp;{
  18&nbsp;        # Calculate how many characters will be full.
  19&nbsp;        let "full_limit = ((($1 - $BRACKET_CHARS) * $2) / $LIMIT)"
  20&nbsp;
  21&nbsp;        # Calculate how many characters will be empty.
  22&nbsp;        let "empty_limit = ($1 - $BRACKET_CHARS) - ${full_limit}"
  23&nbsp;
  24&nbsp;        # Prepare the bar.
  25&nbsp;        bar_line="${BAR_CHAR_START}"
  26&nbsp;        for ((j=0; j&#60;full_limit; j++)); do
  27&nbsp;                bar_line="${bar_line}${BAR_CHAR_FULL}"
  28&nbsp;        done
  29&nbsp;
  30&nbsp;        for ((j=0; j&#60;empty_limit; j++)); do
  31&nbsp;                bar_line="${bar_line}${BAR_CHAR_EMPTY}"
  32&nbsp;        done
  33&nbsp;
  34&nbsp;        bar_line="${bar_line}${BAR_CHAR_END}"
  35&nbsp;
  36&nbsp;        printf "%3d%% %s" $2 ${bar_line}
  37&nbsp;}
  38&nbsp;
  39&nbsp;# Here is a sample of code that uses it.
  40&nbsp;MAX_PERCENT=100
  41&nbsp;for ((i=0; i&#60;=MAX_PERCENT; i++)); do
  42&nbsp;        #
  43&nbsp;        usleep 10000
  44&nbsp;        # ... Or run some other commands ...
  45&nbsp;        #
  46&nbsp;        print_progress_bar ${BAR_WIDTH} ${i}
  47&nbsp;        echo -en "\r"
  48&nbsp;done
  49&nbsp;
  50&nbsp;echo ""
  51&nbsp;
  52&nbsp;exit</PRE
></TD
></TR
></TABLE
><HR></DIV
></LI
><LI
><P
><A
NAME="COMOUTBL"
></A
></P
><P
>A particularly clever use of <A
HREF="tests.html#TESTCONSTRUCTS1"
>if-test</A
> constructs
	    is for comment blocks.</P
><P
>    
	      <TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="90%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#!/bin/bash
   2&nbsp;
   3&nbsp;COMMENT_BLOCK=
   4&nbsp;#  Try setting the above variable to some value
   5&nbsp;#+ for an unpleasant surprise.
   6&nbsp;
   7&nbsp;if [ $COMMENT_BLOCK ]; then
   8&nbsp;
   9&nbsp;Comment block --
  10&nbsp;=================================
  11&nbsp;This is a comment line.
  12&nbsp;This is another comment line.
  13&nbsp;This is yet another comment line.
  14&nbsp;=================================
  15&nbsp;
  16&nbsp;echo "This will not echo."
  17&nbsp;
  18&nbsp;Comment blocks are error-free! Whee!
  19&nbsp;
  20&nbsp;fi
  21&nbsp;
  22&nbsp;echo "No more comments, please."
  23&nbsp;
  24&nbsp;exit 0</PRE
></TD
></TR
></TABLE
>
	  </P
><P
>Compare this with <A
HREF="here-docs.html#CBLOCK1"
>using  
	    here documents to comment out code blocks</A
>.</P
></LI
><LI
><P
><A
NAME="INTPARAM"
></A
></P
><P
>Using the <A
HREF="variables2.html#XSTATVARREF"
>$? exit status
	    variable</A
>, a script may test if a parameter contains
	    only digits, so it can be treated as an integer.</P
><P
>  
	    <TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="90%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#!/bin/bash
   2&nbsp;
   3&nbsp;SUCCESS=0
   4&nbsp;E_BADINPUT=85
   5&nbsp;
   6&nbsp;test "$1" -ne 0 -o "$1" -eq 0 2&#62;/dev/null
   7&nbsp;# An integer is either equal to 0 or not equal to 0.
   8&nbsp;# 2&#62;/dev/null suppresses error message.
   9&nbsp;
  10&nbsp;if [ $? -ne "$SUCCESS" ]
  11&nbsp;then
  12&nbsp;  echo "Usage: `basename $0` integer-input"
  13&nbsp;  exit $E_BADINPUT
  14&nbsp;fi
  15&nbsp;
  16&nbsp;let "sum = $1 + 25"             # Would give error if $1 not integer.
  17&nbsp;echo "Sum = $sum"
  18&nbsp;
  19&nbsp;# Any variable, not just a command-line parameter, can be tested this way.
  20&nbsp;
  21&nbsp;exit 0</PRE
></TD
></TR
></TABLE
>
          </P
></LI
><LI
><P
><A
NAME="RVT"
></A
>The 0 - 255 range for function return
	    values is a severe limitation. Global variables and
	    other workarounds are often problematic. An alternative
	    method for a function to communicate a value back to
	    the main body of the script is to have the function
	    write to <TT
CLASS="FILENAME"
>stdout</TT
> (usually with
	    <A
HREF="internal.html#ECHOREF"
>echo</A
>) the <SPAN
CLASS="QUOTE"
>"return
	    value,"</SPAN
> and assign this to a variable. This is
	    actually a variant of <A
HREF="commandsub.html#COMMANDSUBREF"
>command
	    substitution.</A
></P
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="MULTIPLICATION"
></A
><P
><B
>Example 36-18. Return value trickery</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="90%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#!/bin/bash
   2&nbsp;# multiplication.sh
   3&nbsp;
   4&nbsp;multiply ()                     # Multiplies params passed.
   5&nbsp;{                               # Will accept a variable number of args.
   6&nbsp;
   7&nbsp;  local product=1
   8&nbsp;
   9&nbsp;  until [ -z "$1" ]             # Until uses up arguments passed...
  10&nbsp;  do
  11&nbsp;    let "product *= $1"
  12&nbsp;    shift
  13&nbsp;  done
  14&nbsp;
  15&nbsp;  echo $product                 #  Will not echo to stdout,
  16&nbsp;}                               #+ since this will be assigned to a variable.
  17&nbsp;
  18&nbsp;mult1=15383; mult2=25211
  19&nbsp;val1=`multiply $mult1 $mult2`
  20&nbsp;# Assigns stdout (echo) of function to the variable val1.
  21&nbsp;echo "$mult1 X $mult2 = $val1"                   # 387820813
  22&nbsp;
  23&nbsp;mult1=25; mult2=5; mult3=20
  24&nbsp;val2=`multiply $mult1 $mult2 $mult3`
  25&nbsp;echo "$mult1 X $mult2 X $mult3 = $val2"          # 2500
  26&nbsp;
  27&nbsp;mult1=188; mult2=37; mult3=25; mult4=47
  28&nbsp;val3=`multiply $mult1 $mult2 $mult3 $mult4`
  29&nbsp;echo "$mult1 X $mult2 X $mult3 X $mult4 = $val3" # 8173300
  30&nbsp;
  31&nbsp;exit 0</PRE
></TD
></TR
></TABLE
><HR></DIV
><P
>The same technique also works for alphanumeric
	    strings. This means that a function can <SPAN
CLASS="QUOTE"
>"return"</SPAN
>
	    a non-numeric value.</P
><P
>	  <TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="90%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;capitalize_ichar ()          #  Capitalizes initial character
   2&nbsp;{                            #+ of argument string(s) passed.
   3&nbsp;
   4&nbsp;  string0="$@"               # Accepts multiple arguments.
   5&nbsp;
   6&nbsp;  firstchar=${string0:0:1}   # First character.
   7&nbsp;  string1=${string0:1}       # Rest of string(s).
   8&nbsp;
   9&nbsp;  FirstChar=`echo "$firstchar" | tr a-z A-Z`
  10&nbsp;                             # Capitalize first character.
  11&nbsp;
  12&nbsp;  echo "$FirstChar$string1"  # Output to stdout.
  13&nbsp;
  14&nbsp;}  
  15&nbsp;
  16&nbsp;newstring=`capitalize_ichar "every sentence should start with a capital letter."`
  17&nbsp;echo "$newstring"          # Every sentence should start with a capital letter.</PRE
></TD
></TR
></TABLE
> 
	  </P
><P
>It is even possible for a function to <SPAN
CLASS="QUOTE"
>"return"</SPAN
>
	    multiple values with this method.</P
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="SUMPRODUCT"
></A
><P
><B
>Example 36-19. Even more return value trickery</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="90%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#!/bin/bash
   2&nbsp;# sum-product.sh
   3&nbsp;# A function may "return" more than one value.
   4&nbsp;
   5&nbsp;sum_and_product ()   # Calculates both sum and product of passed args.
   6&nbsp;{
   7&nbsp;  echo $(( $1 + $2 )) $(( $1 * $2 ))
   8&nbsp;# Echoes to stdout each calculated value, separated by space.
   9&nbsp;}
  10&nbsp;
  11&nbsp;echo
  12&nbsp;echo "Enter first number "
  13&nbsp;read first
  14&nbsp;
  15&nbsp;echo
  16&nbsp;echo "Enter second number "
  17&nbsp;read second
  18&nbsp;echo
  19&nbsp;
  20&nbsp;retval=`sum_and_product $first $second`      # Assigns output of function.
  21&nbsp;sum=`echo "$retval" | awk '{print $1}'`      # Assigns first field.
  22&nbsp;product=`echo "$retval" | awk '{print $2}'`  # Assigns second field.
  23&nbsp;
  24&nbsp;echo "$first + $second = $sum"
  25&nbsp;echo "$first * $second = $product"
  26&nbsp;echo
  27&nbsp;
  28&nbsp;exit 0</PRE
></TD
></TR
></TABLE
><HR></DIV
><DIV
CLASS="CAUTION"
><TABLE
CLASS="CAUTION"
WIDTH="90%"
BORDER="0"
><TR
><TD
WIDTH="25"
ALIGN="CENTER"
VALIGN="TOP"
><IMG
SRC="common/caution.png"
HSPACE="5"
ALT="Caution"></TD
><TD
ALIGN="LEFT"
VALIGN="TOP"
><P
><A
NAME="RVTCAUTION"
></A
>There can be only
	    <B
CLASS="COMMAND"
>one</B
> <I
CLASS="FIRSTTERM"
>echo</I
> statement
	    in the function for this to work. If you alter the previous
	    example:</P
><P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="90%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;sum_and_product ()
   2&nbsp;{
   3&nbsp;  echo "This is the sum_and_product function." # This messes things up!
   4&nbsp;  echo $(( $1 + $2 )) $(( $1 * $2 ))
   5&nbsp;}
   6&nbsp;...
   7&nbsp;retval=`sum_and_product $first $second`      # Assigns output of function.
   8&nbsp;# Now, this will not work correctly.</PRE
></TD
></TR
></TABLE
></P
></TD
></TR
></TABLE
></DIV
></LI
><LI
><P
><A
NAME="PASSARRAY"
></A
></P
><P
>Next in our bag of tricks are techniques for passing
	    an <A
HREF="arrays.html#ARRAYREF"
>array</A
> to a
	    <A
HREF="functions.html#FUNCTIONREF"
>function</A
>, then
	    <SPAN
CLASS="QUOTE"
>"returning"</SPAN
> an array back to the main body of
	    the script.</P
><P
>Passing an array involves loading the space-separated
	    elements of the array into a variable with <A
HREF="commandsub.html#COMMANDSUBREF"
>command substitution</A
>. <A
NAME="RETARRAY"
></A
>Getting an array back as the <SPAN
CLASS="QUOTE"
>"return
	    value"</SPAN
> from a function uses the previously mentioned
	    strategem of <A
HREF="internal.html#ECHOREF"
>echoing</A
> the
	    array in the function, then invoking command substitution
	    and the <B
CLASS="COMMAND"
>( ... )</B
> operator to assign it to
	    an array.</P
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="ARRFUNC"
></A
><P
><B
>Example 36-20. Passing and returning arrays</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="90%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#!/bin/bash
   2&nbsp;# array-function.sh: Passing an array to a function and ...
   3&nbsp;#                   "returning" an array from a function
   4&nbsp;
   5&nbsp;
   6&nbsp;Pass_Array ()
   7&nbsp;{
   8&nbsp;  local passed_array   # Local variable!
   9&nbsp;  passed_array=( `echo "$1"` )
  10&nbsp;  echo "${passed_array[@]}"
  11&nbsp;  #  List all the elements of the new array
  12&nbsp;  #+ declared and set within the function.
  13&nbsp;}
  14&nbsp;
  15&nbsp;
  16&nbsp;original_array=( element1 element2 element3 element4 element5 )
  17&nbsp;
  18&nbsp;echo
  19&nbsp;echo "original_array = ${original_array[@]}"
  20&nbsp;#                      List all elements of original array.
  21&nbsp;
  22&nbsp;
  23&nbsp;# This is the trick that permits passing an array to a function.
  24&nbsp;# **********************************
  25&nbsp;argument=`echo ${original_array[@]}`
  26&nbsp;# **********************************
  27&nbsp;#  Pack a variable
  28&nbsp;#+ with all the space-separated elements of the original array.
  29&nbsp;#
  30&nbsp;# Attempting to just pass the array itself will not work.
  31&nbsp;
  32&nbsp;
  33&nbsp;# This is the trick that allows grabbing an array as a "return value".
  34&nbsp;# *****************************************
  35&nbsp;returned_array=( `Pass_Array "$argument"` )
  36&nbsp;# *****************************************
  37&nbsp;# Assign 'echoed' output of function to array variable.
  38&nbsp;
  39&nbsp;echo "returned_array = ${returned_array[@]}"
  40&nbsp;
  41&nbsp;echo "============================================================="
  42&nbsp;
  43&nbsp;#  Now, try it again,
  44&nbsp;#+ attempting to access (list) the array from outside the function.
  45&nbsp;Pass_Array "$argument"
  46&nbsp;
  47&nbsp;# The function itself lists the array, but ...
  48&nbsp;#+ accessing the array from outside the function is forbidden.
  49&nbsp;echo "Passed array (within function) = ${passed_array[@]}"
  50&nbsp;# NULL VALUE since the array is a variable local to the function.
  51&nbsp;
  52&nbsp;echo
  53&nbsp;
  54&nbsp;############################################
  55&nbsp;
  56&nbsp;# And here is an even more explicit example:
  57&nbsp;
  58&nbsp;ret_array ()
  59&nbsp;{
  60&nbsp;  for element in {11..20}
  61&nbsp;  do
  62&nbsp;    echo "$element "   #  Echo individual elements
  63&nbsp;  done                 #+ of what will be assembled into an array.
  64&nbsp;}
  65&nbsp;
  66&nbsp;arr=( $(ret_array) )   #  Assemble into array.
  67&nbsp;
  68&nbsp;echo "Capturing array \"arr\" from function ret_array () ..."
  69&nbsp;echo "Third element of array \"arr\" is ${arr[2]}."   # 13  (zero-indexed)
  70&nbsp;echo -n "Entire array is: "
  71&nbsp;echo ${arr[@]}                # 11 12 13 14 15 16 17 18 19 20
  72&nbsp;
  73&nbsp;echo
  74&nbsp;
  75&nbsp;exit 0
  76&nbsp;
  77&nbsp;#  Nathan Coulter points out that passing arrays with elements containing
  78&nbsp;#+ whitespace breaks this example.</PRE
></TD
></TR
></TABLE
><HR></DIV
><P
>For a more elaborate example of passing arrays to
	    functions, see <A
HREF="contributed-scripts.html#LIFESLOW"
>Example A-10</A
>.</P
></LI
><LI
><P
><A
NAME="CSTYLE"
></A
></P
><P
>Using the <A
HREF="dblparens.html"
>double-parentheses
	    construct</A
>, it is possible to use C-style syntax
	    for setting and incrementing/decrementing variables
	    and in <A
HREF="loops.html#FORLOOPREF1"
>for</A
> and <A
HREF="loops.html#WHILELOOPREF"
>while</A
> loops.	See <A
HREF="loops.html#FORLOOPC"
>Example 11-13</A
> and <A
HREF="loops.html#WHLOOPC"
>Example 11-18</A
>.</P
></LI
><LI
><P
><A
NAME="SETPUM"
></A
></P
><P
>Setting the <A
HREF="variables2.html#PATHREF"
>path</A
> and <A
HREF="system.html#UMASKREF"
>umask</A
> at the beginning of a script makes
	    it more <A
HREF="portabilityissues.html"
>portable</A
>
	    -- more likely to run on a <SPAN
CLASS="QUOTE"
>"foreign"</SPAN
> machine
	    whose user may have bollixed up the <TT
CLASS="VARNAME"
>$PATH</TT
>
	    and <B
CLASS="COMMAND"
>umask</B
>.
	      <TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="90%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#!/bin/bash
   2&nbsp;PATH=/bin:/usr/bin:/usr/local/bin ; export PATH
   3&nbsp;umask 022   # Files that the script creates will have 755 permission.
   4&nbsp;
   5&nbsp;# Thanks to Ian D. Allen, for this tip.</PRE
></TD
></TR
></TABLE
></P
></LI
><LI
><P
><A
NAME="FILTEROUTP"
></A
></P
><P
>A useful scripting technique is to
	    <SPAN
CLASS="emphasis"
><I
CLASS="EMPHASIS"
>repeatedly</I
></SPAN
> feed the output of a filter
	    (by piping) back to the <SPAN
CLASS="emphasis"
><I
CLASS="EMPHASIS"
>same filter</I
></SPAN
>, but
	    with a different set of arguments and/or options. Especially
	    suitable for this are <A
HREF="textproc.html#TRREF"
>tr</A
> and
	    <A
HREF="textproc.html#GREPREF"
>grep</A
>.</P
><P
>	  <TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="90%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;# From "wstrings.sh" example.
   2&nbsp;
   3&nbsp;wlist=`strings "$1" | tr A-Z a-z | tr '[:space:]' Z | \
   4&nbsp;tr -cs '[:alpha:]' Z | tr -s '\173-\377' Z | tr Z ' '`</PRE
></TD
></TR
></TABLE
>
	  </P
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="AGRAM"
></A
><P
><B
>Example 36-21. Fun with anagrams</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="90%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#!/bin/bash
   2&nbsp;# agram.sh: Playing games with anagrams.
   3&nbsp;
   4&nbsp;# Find anagrams of...
   5&nbsp;LETTERSET=etaoinshrdlu
   6&nbsp;FILTER='.......'       # How many letters minimum?
   7&nbsp;#       1234567
   8&nbsp;
   9&nbsp;anagram "$LETTERSET" | # Find all anagrams of the letterset...
  10&nbsp;grep "$FILTER" |       # With at least 7 letters,
  11&nbsp;grep '^is' |           # starting with 'is'
  12&nbsp;grep -v 's$' |         # no plurals
  13&nbsp;grep -v 'ed$'          # no past tense verbs
  14&nbsp;# Possible to add many combinations of conditions and filters.
  15&nbsp;
  16&nbsp;#  Uses "anagram" utility
  17&nbsp;#+ that is part of the author's "yawl" word list package.
  18&nbsp;#  http://ibiblio.org/pub/Linux/libs/yawl-0.3.2.tar.gz
  19&nbsp;#  http://bash.deta.in/yawl-0.3.2.tar.gz
  20&nbsp;
  21&nbsp;exit 0                 # End of code.
  22&nbsp;
  23&nbsp;
  24&nbsp;bash$ sh agram.sh
  25&nbsp;islander
  26&nbsp;isolate
  27&nbsp;isolead
  28&nbsp;isotheral
  29&nbsp;
  30&nbsp;
  31&nbsp;
  32&nbsp;#  Exercises:
  33&nbsp;#  ---------
  34&nbsp;#  Modify this script to take the LETTERSET as a command-line parameter.
  35&nbsp;#  Parameterize the filters in lines 11 - 13 (as with $FILTER),
  36&nbsp;#+ so that they can be specified by passing arguments to a function.
  37&nbsp;
  38&nbsp;#  For a slightly different approach to anagramming,
  39&nbsp;#+ see the agram2.sh script.</PRE
></TD
></TR
></TABLE
><HR></DIV
><P
>See also <A
HREF="procref1.html#CONSTAT"
>Example 29-4</A
>, <A
HREF="textproc.html#CRYPTOQUOTE"
>Example 16-25</A
>, and <A
HREF="contributed-scripts.html#SOUNDEX"
>Example A-9</A
>.</P
></LI
><LI
><P
><A
NAME="COMMBLAHD"
></A
></P
><P
>Use <SPAN
CLASS="QUOTE"
>"<A
HREF="here-docs.html#ANONHEREDOC0"
>anonymous here
	    documents</A
>"</SPAN
> to comment out blocks of code,
	    to save having to individually comment out each line with
	    a <SPAN
CLASS="TOKEN"
>#</SPAN
>.  See <A
HREF="here-docs.html#COMMENTBLOCK"
>Example 19-11</A
>.</P
></LI
><LI
><P
><A
NAME="WHATISREF3"
></A
></P
><P
>Running a script on a machine that relies on a command
	    that might not be installed is dangerous. Use <A
HREF="filearchiv.html#WHATISREF"
>whatis</A
> to avoid potential problems
	    with this.</P
><P
>	    <TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="90%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;CMD=command1                 # First choice.
   2&nbsp;PlanB=command2               # Fallback option.
   3&nbsp;
   4&nbsp;command_test=$(whatis "$CMD" | grep 'nothing appropriate')
   5&nbsp;#  If 'command1' not found on system , 'whatis' will return
   6&nbsp;#+ "command1: nothing appropriate."
   7&nbsp;#
   8&nbsp;#  A safer alternative is:
   9&nbsp;#     command_test=$(whereis "$CMD" | grep \/)
  10&nbsp;#  But then the sense of the following test would have to be reversed,
  11&nbsp;#+ since the $command_test variable holds content only if
  12&nbsp;#+ the $CMD exists on the system.
  13&nbsp;#     (Thanks, bojster.)
  14&nbsp;
  15&nbsp;
  16&nbsp;if [[ -z "$command_test" ]]  # Check whether command present.
  17&nbsp;then
  18&nbsp;  $CMD option1 option2       #  Run command1 with options.
  19&nbsp;else                         #  Otherwise,
  20&nbsp;  $PlanB                     #+ run command2. 
  21&nbsp;fi</PRE
></TD
></TR
></TABLE
>
          </P
></LI
><LI
><P
><A
NAME="IFGREPFIX"
></A
></P
><P
>An <A
HREF="tests.html#IFGREPREF"
>if-grep test</A
> may not
	    return expected results in an error case, when text is output to
	    <TT
CLASS="FILENAME"
>stderr</TT
>, rather that
	    <TT
CLASS="FILENAME"
>stdout</TT
>.
	      <TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="90%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;if ls -l nonexistent_filename | grep -q 'No such file or directory'
   2&nbsp;  then echo "File \"nonexistent_filename\" does not exist."
   3&nbsp;fi</PRE
></TD
></TR
></TABLE
></P
><P
><A
HREF="io-redirection.html#IOREDIRREF"
>Redirecting</A
>
	    <TT
CLASS="FILENAME"
>stderr</TT
> to <TT
CLASS="FILENAME"
>stdout</TT
> fixes
	    this.
	      <TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="90%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;if ls -l nonexistent_filename 2&#62;&#38;1 | grep -q 'No such file or directory'
   2&nbsp;#                             ^^^^
   3&nbsp;  then echo "File \"nonexistent_filename\" does not exist."
   4&nbsp;fi
   5&nbsp;
   6&nbsp;# Thanks, Chris Martin, for pointing this out.</PRE
></TD
></TR
></TABLE
></P
></LI
><LI
><P
><A
NAME="SUBSHTMP"
></A
>
        If you absolutely must access a subshell variable outside the
	subshell, here's a way to do it.
	  <TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="90%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;TMPFILE=tmpfile                  # Create a temp file to store the variable.
   2&nbsp;
   3&nbsp;(   # Inside the subshell ...
   4&nbsp;inner_variable=Inner
   5&nbsp;echo $inner_variable
   6&nbsp;echo $inner_variable &#62;&#62;$TMPFILE  # Append to temp file.
   7&nbsp;)
   8&nbsp;
   9&nbsp;    # Outside the subshell ...
  10&nbsp;
  11&nbsp;echo; echo "-----"; echo
  12&nbsp;echo $inner_variable             # Null, as expected.
  13&nbsp;echo "-----"; echo
  14&nbsp;
  15&nbsp;# Now ...
  16&nbsp;read inner_variable &#60;$TMPFILE    # Read back shell variable.
  17&nbsp;rm -f "$TMPFILE"                 # Get rid of temp file.
  18&nbsp;echo "$inner_variable"           # It's an ugly kludge, but it works.</PRE
></TD
></TR
></TABLE
>
	</P
></LI
><LI
><P
><A
NAME="RUNPARTSREF2"
></A
></P
><P
>The <A
HREF="extmisc.html#RUNPARTSREF"
>run-parts</A
>
	    command is handy for running a set of command
	    scripts in a particular sequence, especially in
	    combination with <A
HREF="system.html#CRONREF"
>cron</A
> or
	    <A
HREF="timedate.html#ATREF"
>at</A
>.</P
></LI
><LI
><P
><A
NAME="RCSREF"
></A
></P
><P
>For doing multiple revisions on a complex script, use the
	    <I
CLASS="FIRSTTERM"
>rcs</I
> Revision Control System package.</P
><P
> Among other benefits of this is automatically updated ID
	    header tags. The <B
CLASS="COMMAND"
>co</B
> command in
	    <I
CLASS="FIRSTTERM"
>rcs</I
> does a parameter replacement of
	    certain reserved key words, for example, replacing
	    <TT
CLASS="PARAMETER"
><I
># $Id$</I
></TT
> in a script with something like:
	      <TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="90%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;# $Id: hello-world.sh,v 1.1 2004/10/16 02:43:05 bozo Exp $</PRE
></TD
></TR
></TABLE
></P
></LI
></UL
></DIV
><DIV
CLASS="SECT2"
><H2
CLASS="SECT2"
><A
NAME="AEN20679"
></A
>36.7.2. Widgets</H2
><P
><A
NAME="WIDGETREF"
></A
></P
><P
>It would be nice to be able to invoke X-Windows widgets
	    from a shell script. There happen to exist several packages
	    that purport to do so, namely <I
CLASS="FIRSTTERM"
>Xscript</I
>,
	    <I
CLASS="FIRSTTERM"
>Xmenu</I
>, and <I
CLASS="FIRSTTERM"
>widtools</I
>.
	    The first two of these no longer seem
	    to be maintained.  Fortunately, it is still
	    possible to obtain <I
CLASS="FIRSTTERM"
>widtools</I
> <A
HREF="http://www.batse.msfc.nasa.gov/~mallozzi/home/software/xforms/src/widtools-2.0.tgz"
TARGET="_top"
>here</A
>.
	    </P
><DIV
CLASS="CAUTION"
><TABLE
CLASS="CAUTION"
WIDTH="100%"
BORDER="0"
><TR
><TD
WIDTH="25"
ALIGN="CENTER"
VALIGN="TOP"
><IMG
SRC="common/caution.png"
HSPACE="5"
ALT="Caution"></TD
><TD
ALIGN="LEFT"
VALIGN="TOP"
><P
>The <I
CLASS="FIRSTTERM"
>widtools</I
> (widget tools)
	    package requires the <I
CLASS="FIRSTTERM"
>XForms</I
> library to
	    be installed. Additionally, the <A
HREF="filearchiv.html#MAKEFILEREF"
>Makefile</A
> needs some judicious
	    editing before the package will build on a typical Linux
	    system. Finally, three of the six widgets offered do not work
	    (and, in fact, segfault).</P
></TD
></TR
></TABLE
></DIV
><P
><A
NAME="DIALOGREF"
></A
></P
><P
>The <I
CLASS="FIRSTTERM"
>dialog</I
> family of tools offers a method
	    of calling <SPAN
CLASS="QUOTE"
>"dialog"</SPAN
> widgets from a shell script. The
	    original <I
CLASS="FIRSTTERM"
>dialog</I
> utility works in a text
	    console, but its successors, <I
CLASS="FIRSTTERM"
>gdialog</I
>,
	    <I
CLASS="FIRSTTERM"
>Xdialog</I
>, and <I
CLASS="FIRSTTERM"
>kdialog</I
>
	    use X-Windows-based widget sets.</P
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="DIALOG"
></A
><P
><B
>Example 36-22. Widgets invoked from a shell script</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;#!/bin/bash
   2&nbsp;# dialog.sh: Using 'gdialog' widgets.
   3&nbsp;
   4&nbsp;# Must have 'gdialog' installed on your system to run this script.
   5&nbsp;# Or, you can replace all instance of 'gdialog' below with 'kdialog' ...
   6&nbsp;# Version 1.1 (corrected 04/05/05)
   7&nbsp;
   8&nbsp;# This script was inspired by the following article.
   9&nbsp;#     "Scripting for X Productivity," by Marco Fioretti,
  10&nbsp;#      LINUX JOURNAL, Issue 113, September 2003, pp. 86-9.
  11&nbsp;# Thank you, all you good people at LJ.
  12&nbsp;
  13&nbsp;
  14&nbsp;# Input error in dialog box.
  15&nbsp;E_INPUT=85
  16&nbsp;# Dimensions of display, input widgets.
  17&nbsp;HEIGHT=50
  18&nbsp;WIDTH=60
  19&nbsp;
  20&nbsp;# Output file name (constructed out of script name).
  21&nbsp;OUTFILE=$0.output
  22&nbsp;
  23&nbsp;# Display this script in a text widget.
  24&nbsp;gdialog --title "Displaying: $0" --textbox $0 $HEIGHT $WIDTH
  25&nbsp;
  26&nbsp;
  27&nbsp;
  28&nbsp;# Now, we'll try saving input in a file.
  29&nbsp;echo -n "VARIABLE=" &#62; $OUTFILE
  30&nbsp;gdialog --title "User Input" --inputbox "Enter variable, please:" \
  31&nbsp;$HEIGHT $WIDTH 2&#62;&#62; $OUTFILE
  32&nbsp;
  33&nbsp;
  34&nbsp;if [ "$?" -eq 0 ]
  35&nbsp;# It's good practice to check exit status.
  36&nbsp;then
  37&nbsp;  echo "Executed \"dialog box\" without errors."
  38&nbsp;else
  39&nbsp;  echo "Error(s) in \"dialog box\" execution."
  40&nbsp;        # Or, clicked on "Cancel", instead of "OK" button.
  41&nbsp;  rm $OUTFILE
  42&nbsp;  exit $E_INPUT
  43&nbsp;fi
  44&nbsp;
  45&nbsp;
  46&nbsp;
  47&nbsp;# Now, we'll retrieve and display the saved variable.
  48&nbsp;. $OUTFILE   # 'Source' the saved file.
  49&nbsp;echo "The variable input in the \"input box\" was: "$VARIABLE""
  50&nbsp;
  51&nbsp;
  52&nbsp;rm $OUTFILE  # Clean up by removing the temp file.
  53&nbsp;             # Some applications may need to retain this file.
  54&nbsp;
  55&nbsp;exit $?
  56&nbsp;
  57&nbsp;# Exercise: Rewrite this script using the 'zenity' widget set.</PRE
></TD
></TR
></TABLE
><HR></DIV
><P
><A
NAME="XMESSAGEREF2"
></A
>
	    The <A
HREF="extmisc.html#XMESSAGEREF"
>xmessage</A
> command is
	    a simple method of popping up a message/query window. For
	    example:
	      <TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;xmessage Fatal error in script! -button exit</PRE
></TD
></TR
></TABLE
>
	  </P
><P
><A
NAME="ZENITYREF2"
></A
>
	    The latest entry in the widget sweepstakes is
	    <A
HREF="extmisc.html#ZENITYREF"
>zenity</A
>.
	    This utility pops up
	    <I
CLASS="FIRSTTERM"
>GTK+</I
> dialog widgets-and-windows,
	    and it works very nicely within a script.
	      <TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
>   1&nbsp;get_info ()
   2&nbsp;{
   3&nbsp;  zenity --entry       #  Pops up query window . . .
   4&nbsp;                       #+ and prints user entry to stdout.
   5&nbsp;
   6&nbsp;                       #  Also try the --calendar and --scale options.
   7&nbsp;}
   8&nbsp;
   9&nbsp;answer=$( get_info )   #  Capture stdout in $answer variable.
  10&nbsp;
  11&nbsp;echo "User entered: "$answer""</PRE
></TD
></TR
></TABLE
>
	  </P
><P
>For other methods of scripting with widgets, try
	    <I
CLASS="FIRSTTERM"
>Tk</I
> or <I
CLASS="FIRSTTERM"
>wish</I
>
	    (<I
CLASS="FIRSTTERM"
>Tcl</I
> derivatives),
	    <I
CLASS="FIRSTTERM"
>PerlTk</I
> (<I
CLASS="FIRSTTERM"
>Perl</I
>
	    with <I
CLASS="FIRSTTERM"
>Tk</I
> extensions),
	    <I
CLASS="FIRSTTERM"
>tksh</I
> (<I
CLASS="FIRSTTERM"
>ksh</I
>
	    with <I
CLASS="FIRSTTERM"
>Tk</I
> extensions),
	    <I
CLASS="FIRSTTERM"
>XForms4Perl</I
>
	    (<I
CLASS="FIRSTTERM"
>Perl</I
> with
	    <I
CLASS="FIRSTTERM"
>XForms</I
> extensions),
	    <I
CLASS="FIRSTTERM"
>Gtk-Perl</I
> (<I
CLASS="FIRSTTERM"
>Perl</I
>
	    with <I
CLASS="FIRSTTERM"
>Gtk</I
> extensions), or
	    <I
CLASS="FIRSTTERM"
>PyQt</I
> (<I
CLASS="FIRSTTERM"
>Python</I
>
	    with <I
CLASS="FIRSTTERM"
>Qt</I
> extensions).</P
></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="optimizations.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="securityissues.html"
ACCESSKEY="N"
>Next</A
></TD
></TR
><TR
><TD
WIDTH="33%"
ALIGN="left"
VALIGN="top"
>Optimizations</TD
><TD
WIDTH="34%"
ALIGN="center"
VALIGN="top"
><A
HREF="miscellany.html"
ACCESSKEY="U"
>Up</A
></TD
><TD
WIDTH="33%"
ALIGN="right"
VALIGN="top"
>Security Issues</TD
></TR
></TABLE
></DIV
></BODY
></HTML
>