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 #!/bin/bash
2
3 ARGCOUNT=1 # Need name as argument.
4 E_WRONGARGS=65
5
6 if [ number-of-arguments is-not-equal-to "$ARGCOUNT" ]
7 # ^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^
8 # Can't figure out how to code this . . .
9 #+ . . . so write it in pseudo-code.
10
11 then
12 echo "Usage: name-of-script name"
13 # ^^^^^^^^^^^^^^ More pseudo-code.
14 exit $E_WRONGARGS
15 fi
16
17 . . .
18
19 exit 0
20
21
22 # Later on, substitute working code for the pseudo-code.
23
24 # Line 6 becomes:
25 if [ $# -ne "$ARGCOUNT" ]
26
27 # Line 12 becomes:
28 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 # Append (>>) following to end of each script tracked.
2
3 whoami>> $SAVE_FILE # User invoking the script.
4 echo $0>> $SAVE_FILE # Script name.
5 date>> $SAVE_FILE # Date and time.
6 echo>> $SAVE_FILE # Blank line as separator.
7
8 # Of course, SAVE_FILE defined and exported as environmental variable in ~/.bashrc
9 #+ (something like ~/.scripts-run)</PRE
></TD
></TR
></TABLE
>
</P
></LI
><LI
><P
><A
NAME="PREPENDREF"
></A
></P
><P
>The <SPAN
CLASS="TOKEN"
>>></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 file=data.txt
2 title="***This is the title line of data text file***"
3
4 echo $title | cat - $file >$file.new
5 # "cat -" concatenates stdout to $file.
6 # End result is
7 #+ 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 # SCRIPT LIBRARY
2 # ------ -------
3
4 # Note:
5 # No "#!" here.
6 # No "live code" either.
7
8
9 # Useful variable definitions
10
11 ROOT_UID=0 # Root has $UID 0.
12 E_NOTROOT=101 # Not root user error.
13 MAXRETVAL=255 # Maximum (positive) return value of a function.
14 SUCCESS=0
15 FAILURE=-1
16
17
18
19 # Functions
20
21 Usage () # "Usage:" message.
22 {
23 if [ -z "$1" ] # No arg passed.
24 then
25 msg=filename
26 else
27 msg=$@
28 fi
29
30 echo "Usage: `basename $0` "$msg""
31 }
32
33
34 Check_if_root () # Check if root running script.
35 { # From "ex39.sh" example.
36 if [ "$UID" -ne "$ROOT_UID" ]
37 then
38 echo "Must be root to run this script."
39 exit $E_NOTROOT
40 fi
41 }
42
43
44 CreateTempfileName () # Creates a "unique" temp filename.
45 { # From "ex51.sh" example.
46 prefix=temp
47 suffix=`eval date +%s`
48 Tempfilename=$prefix.$suffix
49 }
50
51
52 isalpha2 () # Tests whether *entire string* is alphabetic.
53 { # From "isalpha.sh" example.
54 [ $# -eq 1 ] || return $FAILURE
55
56 case $1 in
57 *[!a-zA-Z]*|"") return $FAILURE;;
58 *) return $SUCCESS;;
59 esac # Thanks, S.C.
60 }
61
62
63 abs () # Absolute value.
64 { # Caution: Max return value = 255.
65 E_ARGERR=-999999
66
67 if [ -z "$1" ] # Need arg passed.
68 then
69 return $E_ARGERR # Obvious error value returned.
70 fi
71
72 if [ "$1" -ge 0 ] # If non-negative,
73 then #
74 absval=$1 # stays as-is.
75 else # Otherwise,
76 let "absval = (( 0 - $1 ))" # change sign.
77 fi
78
79 return $absval
80 }
81
82
83 tolower () # Converts string(s) passed as argument(s)
84 { #+ to lowercase.
85
86 if [ -z "$1" ] # If no argument(s) passed,
87 then #+ send error message
88 echo "(null)" #+ (C-style void-pointer error message)
89 return #+ and return from function.
90 fi
91
92 echo "$@" | tr A-Z a-z
93 # Translate all passed arguments ($@).
94
95 return
96
97 # Use command substitution to set a variable to function output.
98 # For example:
99 # oldvar="A seT of miXed-caSe LEtTerS"
100 # newvar=`tolower "$oldvar"`
101 # echo "$newvar" # a set of mixed-case letters
102 #
103 # Exercise: Rewrite this function to change lowercase passed argument(s)
104 # to uppercase ... toupper() [easy].
105 }</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 ## Caution.
2 rm -rf *.zzy ## The "-rf" options to "rm" are very dangerous,
3 ##+ especially with wild cards.
4
5 #+ Line continuation.
6 # This is line 1
7 #+ of a multi-line comment,
8 #+ and this is the final line.
9
10 #* Note.
11
12 #o List item.
13
14 #> Another point of view.
15 while [ "$var1" != "end" ] #> 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 #!/bin/bash
2 # progress-bar.sh
3
4 # Author: Dotan Barak (very minor revisions by ABS Guide author).
5 # Used in ABS Guide with permission (thanks!).
6
7
8 BAR_WIDTH=50
9 BAR_CHAR_START="["
10 BAR_CHAR_END="]"
11 BAR_CHAR_EMPTY="."
12 BAR_CHAR_FULL="="
13 BRACKET_CHARS=2
14 LIMIT=100
15
16 print_progress_bar()
17 {
18 # Calculate how many characters will be full.
19 let "full_limit = ((($1 - $BRACKET_CHARS) * $2) / $LIMIT)"
20
21 # Calculate how many characters will be empty.
22 let "empty_limit = ($1 - $BRACKET_CHARS) - ${full_limit}"
23
24 # Prepare the bar.
25 bar_line="${BAR_CHAR_START}"
26 for ((j=0; j<full_limit; j++)); do
27 bar_line="${bar_line}${BAR_CHAR_FULL}"
28 done
29
30 for ((j=0; j<empty_limit; j++)); do
31 bar_line="${bar_line}${BAR_CHAR_EMPTY}"
32 done
33
34 bar_line="${bar_line}${BAR_CHAR_END}"
35
36 printf "%3d%% %s" $2 ${bar_line}
37 }
38
39 # Here is a sample of code that uses it.
40 MAX_PERCENT=100
41 for ((i=0; i<=MAX_PERCENT; i++)); do
42 #
43 usleep 10000
44 # ... Or run some other commands ...
45 #
46 print_progress_bar ${BAR_WIDTH} ${i}
47 echo -en "\r"
48 done
49
50 echo ""
51
52 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 #!/bin/bash
2
3 COMMENT_BLOCK=
4 # Try setting the above variable to some value
5 #+ for an unpleasant surprise.
6
7 if [ $COMMENT_BLOCK ]; then
8
9 Comment block --
10 =================================
11 This is a comment line.
12 This is another comment line.
13 This is yet another comment line.
14 =================================
15
16 echo "This will not echo."
17
18 Comment blocks are error-free! Whee!
19
20 fi
21
22 echo "No more comments, please."
23
24 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 #!/bin/bash
2
3 SUCCESS=0
4 E_BADINPUT=85
5
6 test "$1" -ne 0 -o "$1" -eq 0 2>/dev/null
7 # An integer is either equal to 0 or not equal to 0.
8 # 2>/dev/null suppresses error message.
9
10 if [ $? -ne "$SUCCESS" ]
11 then
12 echo "Usage: `basename $0` integer-input"
13 exit $E_BADINPUT
14 fi
15
16 let "sum = $1 + 25" # Would give error if $1 not integer.
17 echo "Sum = $sum"
18
19 # Any variable, not just a command-line parameter, can be tested this way.
20
21 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 #!/bin/bash
2 # multiplication.sh
3
4 multiply () # Multiplies params passed.
5 { # Will accept a variable number of args.
6
7 local product=1
8
9 until [ -z "$1" ] # Until uses up arguments passed...
10 do
11 let "product *= $1"
12 shift
13 done
14
15 echo $product # Will not echo to stdout,
16 } #+ since this will be assigned to a variable.
17
18 mult1=15383; mult2=25211
19 val1=`multiply $mult1 $mult2`
20 # Assigns stdout (echo) of function to the variable val1.
21 echo "$mult1 X $mult2 = $val1" # 387820813
22
23 mult1=25; mult2=5; mult3=20
24 val2=`multiply $mult1 $mult2 $mult3`
25 echo "$mult1 X $mult2 X $mult3 = $val2" # 2500
26
27 mult1=188; mult2=37; mult3=25; mult4=47
28 val3=`multiply $mult1 $mult2 $mult3 $mult4`
29 echo "$mult1 X $mult2 X $mult3 X $mult4 = $val3" # 8173300
30
31 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 capitalize_ichar () # Capitalizes initial character
2 { #+ of argument string(s) passed.
3
4 string0="$@" # Accepts multiple arguments.
5
6 firstchar=${string0:0:1} # First character.
7 string1=${string0:1} # Rest of string(s).
8
9 FirstChar=`echo "$firstchar" | tr a-z A-Z`
10 # Capitalize first character.
11
12 echo "$FirstChar$string1" # Output to stdout.
13
14 }
15
16 newstring=`capitalize_ichar "every sentence should start with a capital letter."`
17 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 #!/bin/bash
2 # sum-product.sh
3 # A function may "return" more than one value.
4
5 sum_and_product () # Calculates both sum and product of passed args.
6 {
7 echo $(( $1 + $2 )) $(( $1 * $2 ))
8 # Echoes to stdout each calculated value, separated by space.
9 }
10
11 echo
12 echo "Enter first number "
13 read first
14
15 echo
16 echo "Enter second number "
17 read second
18 echo
19
20 retval=`sum_and_product $first $second` # Assigns output of function.
21 sum=`echo "$retval" | awk '{print $1}'` # Assigns first field.
22 product=`echo "$retval" | awk '{print $2}'` # Assigns second field.
23
24 echo "$first + $second = $sum"
25 echo "$first * $second = $product"
26 echo
27
28 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 sum_and_product ()
2 {
3 echo "This is the sum_and_product function." # This messes things up!
4 echo $(( $1 + $2 )) $(( $1 * $2 ))
5 }
6 ...
7 retval=`sum_and_product $first $second` # Assigns output of function.
8 # 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 #!/bin/bash
2 # array-function.sh: Passing an array to a function and ...
3 # "returning" an array from a function
4
5
6 Pass_Array ()
7 {
8 local passed_array # Local variable!
9 passed_array=( `echo "$1"` )
10 echo "${passed_array[@]}"
11 # List all the elements of the new array
12 #+ declared and set within the function.
13 }
14
15
16 original_array=( element1 element2 element3 element4 element5 )
17
18 echo
19 echo "original_array = ${original_array[@]}"
20 # List all elements of original array.
21
22
23 # This is the trick that permits passing an array to a function.
24 # **********************************
25 argument=`echo ${original_array[@]}`
26 # **********************************
27 # Pack a variable
28 #+ with all the space-separated elements of the original array.
29 #
30 # Attempting to just pass the array itself will not work.
31
32
33 # This is the trick that allows grabbing an array as a "return value".
34 # *****************************************
35 returned_array=( `Pass_Array "$argument"` )
36 # *****************************************
37 # Assign 'echoed' output of function to array variable.
38
39 echo "returned_array = ${returned_array[@]}"
40
41 echo "============================================================="
42
43 # Now, try it again,
44 #+ attempting to access (list) the array from outside the function.
45 Pass_Array "$argument"
46
47 # The function itself lists the array, but ...
48 #+ accessing the array from outside the function is forbidden.
49 echo "Passed array (within function) = ${passed_array[@]}"
50 # NULL VALUE since the array is a variable local to the function.
51
52 echo
53
54 ############################################
55
56 # And here is an even more explicit example:
57
58 ret_array ()
59 {
60 for element in {11..20}
61 do
62 echo "$element " # Echo individual elements
63 done #+ of what will be assembled into an array.
64 }
65
66 arr=( $(ret_array) ) # Assemble into array.
67
68 echo "Capturing array \"arr\" from function ret_array () ..."
69 echo "Third element of array \"arr\" is ${arr[2]}." # 13 (zero-indexed)
70 echo -n "Entire array is: "
71 echo ${arr[@]} # 11 12 13 14 15 16 17 18 19 20
72
73 echo
74
75 exit 0
76
77 # Nathan Coulter points out that passing arrays with elements containing
78 #+ 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 #!/bin/bash
2 PATH=/bin:/usr/bin:/usr/local/bin ; export PATH
3 umask 022 # Files that the script creates will have 755 permission.
4
5 # 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 # From "wstrings.sh" example.
2
3 wlist=`strings "$1" | tr A-Z a-z | tr '[:space:]' Z | \
4 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 #!/bin/bash
2 # agram.sh: Playing games with anagrams.
3
4 # Find anagrams of...
5 LETTERSET=etaoinshrdlu
6 FILTER='.......' # How many letters minimum?
7 # 1234567
8
9 anagram "$LETTERSET" | # Find all anagrams of the letterset...
10 grep "$FILTER" | # With at least 7 letters,
11 grep '^is' | # starting with 'is'
12 grep -v 's$' | # no plurals
13 grep -v 'ed$' # no past tense verbs
14 # Possible to add many combinations of conditions and filters.
15
16 # Uses "anagram" utility
17 #+ that is part of the author's "yawl" word list package.
18 # http://ibiblio.org/pub/Linux/libs/yawl-0.3.2.tar.gz
19 # http://bash.deta.in/yawl-0.3.2.tar.gz
20
21 exit 0 # End of code.
22
23
24 bash$ sh agram.sh
25 islander
26 isolate
27 isolead
28 isotheral
29
30
31
32 # Exercises:
33 # ---------
34 # Modify this script to take the LETTERSET as a command-line parameter.
35 # Parameterize the filters in lines 11 - 13 (as with $FILTER),
36 #+ so that they can be specified by passing arguments to a function.
37
38 # For a slightly different approach to anagramming,
39 #+ 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 CMD=command1 # First choice.
2 PlanB=command2 # Fallback option.
3
4 command_test=$(whatis "$CMD" | grep 'nothing appropriate')
5 # If 'command1' not found on system , 'whatis' will return
6 #+ "command1: nothing appropriate."
7 #
8 # A safer alternative is:
9 # command_test=$(whereis "$CMD" | grep \/)
10 # But then the sense of the following test would have to be reversed,
11 #+ since the $command_test variable holds content only if
12 #+ the $CMD exists on the system.
13 # (Thanks, bojster.)
14
15
16 if [[ -z "$command_test" ]] # Check whether command present.
17 then
18 $CMD option1 option2 # Run command1 with options.
19 else # Otherwise,
20 $PlanB #+ run command2.
21 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 if ls -l nonexistent_filename | grep -q 'No such file or directory'
2 then echo "File \"nonexistent_filename\" does not exist."
3 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 if ls -l nonexistent_filename 2>&1 | grep -q 'No such file or directory'
2 # ^^^^
3 then echo "File \"nonexistent_filename\" does not exist."
4 fi
5
6 # 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 TMPFILE=tmpfile # Create a temp file to store the variable.
2
3 ( # Inside the subshell ...
4 inner_variable=Inner
5 echo $inner_variable
6 echo $inner_variable >>$TMPFILE # Append to temp file.
7 )
8
9 # Outside the subshell ...
10
11 echo; echo "-----"; echo
12 echo $inner_variable # Null, as expected.
13 echo "-----"; echo
14
15 # Now ...
16 read inner_variable <$TMPFILE # Read back shell variable.
17 rm -f "$TMPFILE" # Get rid of temp file.
18 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 # $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 #!/bin/bash
2 # dialog.sh: Using 'gdialog' widgets.
3
4 # Must have 'gdialog' installed on your system to run this script.
5 # Or, you can replace all instance of 'gdialog' below with 'kdialog' ...
6 # Version 1.1 (corrected 04/05/05)
7
8 # This script was inspired by the following article.
9 # "Scripting for X Productivity," by Marco Fioretti,
10 # LINUX JOURNAL, Issue 113, September 2003, pp. 86-9.
11 # Thank you, all you good people at LJ.
12
13
14 # Input error in dialog box.
15 E_INPUT=85
16 # Dimensions of display, input widgets.
17 HEIGHT=50
18 WIDTH=60
19
20 # Output file name (constructed out of script name).
21 OUTFILE=$0.output
22
23 # Display this script in a text widget.
24 gdialog --title "Displaying: $0" --textbox $0 $HEIGHT $WIDTH
25
26
27
28 # Now, we'll try saving input in a file.
29 echo -n "VARIABLE=" > $OUTFILE
30 gdialog --title "User Input" --inputbox "Enter variable, please:" \
31 $HEIGHT $WIDTH 2>> $OUTFILE
32
33
34 if [ "$?" -eq 0 ]
35 # It's good practice to check exit status.
36 then
37 echo "Executed \"dialog box\" without errors."
38 else
39 echo "Error(s) in \"dialog box\" execution."
40 # Or, clicked on "Cancel", instead of "OK" button.
41 rm $OUTFILE
42 exit $E_INPUT
43 fi
44
45
46
47 # Now, we'll retrieve and display the saved variable.
48 . $OUTFILE # 'Source' the saved file.
49 echo "The variable input in the \"input box\" was: "$VARIABLE""
50
51
52 rm $OUTFILE # Clean up by removing the temp file.
53 # Some applications may need to retain this file.
54
55 exit $?
56
57 # 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 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 get_info ()
2 {
3 zenity --entry # Pops up query window . . .
4 #+ and prints user entry to stdout.
5
6 # Also try the --calendar and --scale options.
7 }
8
9 answer=$( get_info ) # Capture stdout in $answer variable.
10
11 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
>
|