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
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML
><HEAD
><TITLE
>Functions</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="Advanced Topics"
HREF="part5.html"><LINK
REL="PREVIOUS"
TITLE="Process Substitution"
HREF="process-sub.html"><LINK
REL="NEXT"
TITLE="Local Variables"
HREF="localvar.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="CHAPTER"
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="process-sub.html"
ACCESSKEY="P"
>Prev</A
></TD
><TD
WIDTH="80%"
ALIGN="center"
VALIGN="bottom"
></TD
><TD
WIDTH="10%"
ALIGN="right"
VALIGN="bottom"
><A
HREF="localvar.html"
ACCESSKEY="N"
>Next</A
></TD
></TR
></TABLE
><HR
ALIGN="LEFT"
WIDTH="100%"></DIV
><DIV
CLASS="CHAPTER"
><H1
><A
NAME="FUNCTIONS"
></A
>Chapter 24. Functions</H1
><P
><A
NAME="FUNCTIONREF"
></A
></P
><P
>Like <SPAN
CLASS="QUOTE"
>"real"</SPAN
> programming languages,
Bash has functions, though in a somewhat limited implementation.
A function is a subroutine, a <A
HREF="special-chars.html#CODEBLOCKREF"
>code
block</A
> that implements a set of operations, a <SPAN
CLASS="QUOTE"
>"black
box"</SPAN
> that performs a specified task. Wherever there is
repetitive code, when a task repeats with only slight variations in
procedure, then consider using a function.</P
><P
><P
><B
CLASS="COMMAND"
>function</B
> <TT
CLASS="REPLACEABLE"
><I
>function_name</I
></TT
> { <BR> <TT
CLASS="REPLACEABLE"
><I
>command</I
></TT
>... <BR> } <BR></P
>
or
<P
> <TT
CLASS="REPLACEABLE"
><I
>function_name</I
></TT
> () { <BR> <TT
CLASS="REPLACEABLE"
><I
>command</I
></TT
>... <BR> } <BR></P
>
</P
><P
>This second form will cheer the hearts of C programmers
(and is more <A
HREF="portabilityissues.html"
>portable</A
>).</P
><P
>As in C, the function's opening bracket may optionally appear
on the second line.</P
><P
><P
> <TT
CLASS="REPLACEABLE"
><I
>function_name</I
></TT
> () <BR> { <BR> <TT
CLASS="REPLACEABLE"
><I
>command</I
></TT
>... <BR> } <BR></P
>
</P
><DIV
CLASS="NOTE"
><TABLE
CLASS="NOTE"
WIDTH="100%"
BORDER="0"
><TR
><TD
WIDTH="25"
ALIGN="CENTER"
VALIGN="TOP"
><IMG
SRC="common/note.png"
HSPACE="5"
ALT="Note"></TD
><TD
ALIGN="LEFT"
VALIGN="TOP"
><P
>A function may be <SPAN
CLASS="QUOTE"
>"compacted"</SPAN
> into a single
line.</P
><P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
> 1 fun () { echo "This is a function"; echo; }
2 # ^ ^</PRE
></TD
></TR
></TABLE
></P
><P
>In this case, however, a <I
CLASS="FIRSTTERM"
>semicolon</I
>
must follow the final command in the function.</P
><P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
> 1 fun () { echo "This is a function"; echo } # Error!
2 # ^
3
4 fun2 () { echo "Even a single-command function? Yes!"; }
5 # ^</PRE
></TD
></TR
></TABLE
></P
></TD
></TR
></TABLE
></DIV
><P
>Functions are called, <I
CLASS="FIRSTTERM"
>triggered</I
>, simply by
invoking their names. <SPAN
CLASS="emphasis"
><I
CLASS="EMPHASIS"
>A function call is equivalent to
a command.</I
></SPAN
></P
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="EX59"
></A
><P
><B
>Example 24-1. Simple functions</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
> 1 #!/bin/bash
2 # ex59.sh: Exercising functions (simple).
3
4 JUST_A_SECOND=1
5
6 funky ()
7 { # This is about as simple as functions get.
8 echo "This is a funky function."
9 echo "Now exiting funky function."
10 } # Function declaration must precede call.
11
12
13 fun ()
14 { # A somewhat more complex function.
15 i=0
16 REPEATS=30
17
18 echo
19 echo "And now the fun really begins."
20 echo
21
22 sleep $JUST_A_SECOND # Hey, wait a second!
23 while [ $i -lt $REPEATS ]
24 do
25 echo "----------FUNCTIONS---------->"
26 echo "<------------ARE-------------"
27 echo "<------------FUN------------>"
28 echo
29 let "i+=1"
30 done
31 }
32
33 # Now, call the functions.
34
35 funky
36 fun
37
38 exit $?</PRE
></TD
></TR
></TABLE
><HR></DIV
><P
><A
NAME="FUNCTDEFMUST"
></A
></P
><P
>The function definition must precede the first call to
it. There is no method of <SPAN
CLASS="QUOTE"
>"declaring"</SPAN
> the function,
as, for example, in C.
<TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
> 1 f1
2 # Will give an error message, since function "f1" not yet defined.
3
4 declare -f f1 # This doesn't help either.
5 f1 # Still an error message.
6
7 # However...
8
9
10 f1 ()
11 {
12 echo "Calling function \"f2\" from within function \"f1\"."
13 f2
14 }
15
16 f2 ()
17 {
18 echo "Function \"f2\"."
19 }
20
21 f1 # Function "f2" is not actually called until this point,
22 #+ although it is referenced before its definition.
23 # This is permissible.
24
25 # Thanks, S.C.</PRE
></TD
></TR
></TABLE
>
</P
><DIV
CLASS="NOTE"
><TABLE
CLASS="NOTE"
WIDTH="100%"
BORDER="0"
><TR
><TD
WIDTH="25"
ALIGN="CENTER"
VALIGN="TOP"
><IMG
SRC="common/note.png"
HSPACE="5"
ALT="Note"></TD
><TD
ALIGN="LEFT"
VALIGN="TOP"
><P
><A
NAME="EMPTYFUNC"
></A
>Functions may not be empty!
<TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
> 1 #!/bin/bash
2 # empty-function.sh
3
4 empty ()
5 {
6 }
7
8 exit 0 # Will not exit here!
9
10 # $ sh empty-function.sh
11 # empty-function.sh: line 6: syntax error near unexpected token `}'
12 # empty-function.sh: line 6: `}'
13
14 # $ echo $?
15 # 2
16
17
18 # Note that a function containing only comments is empty.
19
20 func ()
21 {
22 # Comment 1.
23 # Comment 2.
24 # This is still an empty function.
25 # Thank you, Mark Bova, for pointing this out.
26 }
27 # Results in same error message as above.
28
29
30 # However ...
31
32 not_quite_empty ()
33 {
34 illegal_command
35 } # A script containing this function will *not* bomb
36 #+ as long as the function is not called.
37
38 not_empty ()
39 {
40 :
41 } # Contains a : (null command), and this is okay.
42
43
44 # Thank you, Dominick Geyer and Thiemo Kellner.</PRE
></TD
></TR
></TABLE
></P
></TD
></TR
></TABLE
></DIV
><P
>It is even possible to nest a function within another function,
although this is not very useful.
<TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
> 1 f1 ()
2 {
3
4 f2 () # nested
5 {
6 echo "Function \"f2\", inside \"f1\"."
7 }
8
9 }
10
11 f2 # Gives an error message.
12 # Even a preceding "declare -f f2" wouldn't help.
13
14 echo
15
16 f1 # Does nothing, since calling "f1" does not automatically call "f2".
17 f2 # Now, it's all right to call "f2",
18 #+ since its definition has been made visible by calling "f1".
19
20 # Thanks, S.C.</PRE
></TD
></TR
></TABLE
>
</P
><P
>Function declarations can appear in unlikely places, even where a
command would otherwise go.
<TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
> 1 ls -l | foo() { echo "foo"; } # Permissible, but useless.
2
3
4
5 if [ "$USER" = bozo ]
6 then
7 bozo_greet () # Function definition embedded in an if/then construct.
8 {
9 echo "Hello, Bozo."
10 }
11 fi
12
13 bozo_greet # Works only for Bozo, and other users get an error.
14
15
16
17 # Something like this might be useful in some contexts.
18 NO_EXIT=1 # Will enable function definition below.
19
20 [[ $NO_EXIT -eq 1 ]] && exit() { true; } # Function definition in an "and-list".
21 # If $NO_EXIT is 1, declares "exit ()".
22 # This disables the "exit" builtin by aliasing it to "true".
23
24 exit # Invokes "exit ()" function, not "exit" builtin.
25
26
27
28 # Or, similarly:
29 filename=file1
30
31 [ -f "$filename" ] &&
32 foo () { rm -f "$filename"; echo "File "$filename" deleted."; } ||
33 foo () { echo "File "$filename" not found."; touch bar; }
34
35 foo
36
37 # Thanks, S.C. and Christopher Head</PRE
></TD
></TR
></TABLE
>
</P
><P
><A
NAME="FSTRANGEREF"
></A
>Function names can take strange
forms.
<TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
> 1 _(){ for i in {1..10}; do echo -n "$FUNCNAME"; done; echo; }
2 # ^^^ No space between function name and parentheses.
3 # This doesn't always work. Why not?
4
5 # Now, let's invoke the function.
6 _ # __________
7 # ^^^^^^^^^^ 10 underscores (10 x function name)!
8 # A "naked" underscore is an acceptable function name.
9
10
11 # In fact, a colon is likewise an acceptable function name.
12
13 :(){ echo ":"; }; :
14
15 # Of what use is this?
16 # It's a devious way to obfuscate the code in a script.</PRE
></TD
></TR
></TABLE
>
See also <A
HREF="contributed-scripts.html#GRONSFELD"
>Example A-56</A
></P
><DIV
CLASS="NOTE"
><TABLE
CLASS="NOTE"
WIDTH="100%"
BORDER="0"
><TR
><TD
WIDTH="25"
ALIGN="CENTER"
VALIGN="TOP"
><IMG
SRC="common/note.png"
HSPACE="5"
ALT="Note"></TD
><TD
ALIGN="LEFT"
VALIGN="TOP"
><P
>What happens when different versions of the same function
appear in a script?
<TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
> 1 # As Yan Chen points out,
2 # when a function is defined multiple times,
3 # the final version is what is invoked.
4 # This is not, however, particularly useful.
5
6 func ()
7 {
8 echo "First version of func ()."
9 }
10
11 func ()
12 {
13 echo "Second version of func ()."
14 }
15
16 func # Second version of func ().
17
18 exit $?
19
20 # It is even possible to use functions to override
21 #+ or preempt system commands.
22 # Of course, this is *not* advisable.</PRE
></TD
></TR
></TABLE
></P
></TD
></TR
></TABLE
></DIV
><DIV
CLASS="SECT1"
><H1
CLASS="SECT1"
><A
NAME="COMPLEXFUNCT"
></A
>24.1. Complex Functions and Function Complexities</H1
><P
>Functions may process arguments passed to them and return
an <A
HREF="exit-status.html#EXITSTATUSREF"
>exit status</A
> to the script
for further processing.</P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
> 1 function_name $arg1 $arg2</PRE
></TD
></TR
></TABLE
><P
><A
NAME="PASSEDARGS"
></A
></P
><P
>The function refers to the passed arguments by position (as if they were
<A
HREF="variables2.html#POSPARAMREF"
>positional parameters</A
>),
that is, <TT
CLASS="VARNAME"
>$1</TT
>, <TT
CLASS="VARNAME"
>$2</TT
>, and
so forth.</P
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="EX60"
></A
><P
><B
>Example 24-2. Function Taking Parameters</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
> 1 #!/bin/bash
2 # Functions and parameters
3
4 DEFAULT=default # Default param value.
5
6 func2 () {
7 if [ -z "$1" ] # Is parameter #1 zero length?
8 then
9 echo "-Parameter #1 is zero length.-" # Or no parameter passed.
10 else
11 echo "-Parameter #1 is \"$1\".-"
12 fi
13
14 variable=${1-$DEFAULT} # What does
15 echo "variable = $variable" #+ parameter substitution show?
16 # ---------------------------
17 # It distinguishes between
18 #+ no param and a null param.
19
20 if [ "$2" ]
21 then
22 echo "-Parameter #2 is \"$2\".-"
23 fi
24
25 return 0
26 }
27
28 echo
29
30 echo "Nothing passed."
31 func2 # Called with no params
32 echo
33
34
35 echo "Zero-length parameter passed."
36 func2 "" # Called with zero-length param
37 echo
38
39 echo "Null parameter passed."
40 func2 "$uninitialized_param" # Called with uninitialized param
41 echo
42
43 echo "One parameter passed."
44 func2 first # Called with one param
45 echo
46
47 echo "Two parameters passed."
48 func2 first second # Called with two params
49 echo
50
51 echo "\"\" \"second\" passed."
52 func2 "" second # Called with zero-length first parameter
53 echo # and ASCII string as a second one.
54
55 exit 0</PRE
></TD
></TR
></TABLE
><HR></DIV
><P
><A
NAME="FSHIFTREF"
></A
></P
><DIV
CLASS="IMPORTANT"
><TABLE
CLASS="IMPORTANT"
WIDTH="100%"
BORDER="0"
><TR
><TD
WIDTH="25"
ALIGN="CENTER"
VALIGN="TOP"
><IMG
SRC="common/important.png"
HSPACE="5"
ALT="Important"></TD
><TD
ALIGN="LEFT"
VALIGN="TOP"
><P
>The <A
HREF="othertypesv.html#SHIFTREF"
>shift</A
>
command works on arguments passed to functions (see <A
HREF="assortedtips.html#MULTIPLICATION"
>Example 36-18</A
>).</P
></TD
></TR
></TABLE
></DIV
><P
>But, what about command-line arguments passed to the script?
Does a function see them? Well, let's clear up the confusion.</P
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="FUNCCMDLINEARG"
></A
><P
><B
>Example 24-3. Functions and command-line args passed to the script</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
> 1 #!/bin/bash
2 # func-cmdlinearg.sh
3 # Call this script with a command-line argument,
4 #+ something like $0 arg1.
5
6
7 func ()
8
9 {
10 echo "$1" # Echoes first arg passed to the function.
11 } # Does a command-line arg qualify?
12
13 echo "First call to function: no arg passed."
14 echo "See if command-line arg is seen."
15 func
16 # No! Command-line arg not seen.
17
18 echo "============================================================"
19 echo
20 echo "Second call to function: command-line arg passed explicitly."
21 func $1
22 # Now it's seen!
23
24 exit 0</PRE
></TD
></TR
></TABLE
><HR></DIV
><P
>In contrast to certain other programming languages,
shell scripts normally pass only value parameters to
functions. Variable names (which are actually
<I
CLASS="FIRSTTERM"
>pointers</I
>), if
passed as parameters to functions, will be treated as string
literals. <SPAN
CLASS="emphasis"
><I
CLASS="EMPHASIS"
>Functions interpret their arguments
literally.</I
></SPAN
></P
><P
><A
NAME="FUNCPOINTERS"
></A
></P
><P
><A
HREF="ivr.html#IVRREF"
>Indirect variable
references</A
> (see <A
HREF="bash2.html#EX78"
>Example 37-2</A
>) provide a clumsy
sort of mechanism for passing variable pointers to
functions.</P
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="INDFUNC"
></A
><P
><B
>Example 24-4. Passing an indirect reference to a function</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
> 1 #!/bin/bash
2 # ind-func.sh: Passing an indirect reference to a function.
3
4 echo_var ()
5 {
6 echo "$1"
7 }
8
9 message=Hello
10 Hello=Goodbye
11
12 echo_var "$message" # Hello
13 # Now, let's pass an indirect reference to the function.
14 echo_var "${!message}" # Goodbye
15
16 echo "-------------"
17
18 # What happens if we change the contents of "hello" variable?
19 Hello="Hello, again!"
20 echo_var "$message" # Hello
21 echo_var "${!message}" # Hello, again!
22
23 exit 0</PRE
></TD
></TR
></TABLE
><HR></DIV
><P
>The next logical question is whether parameters can be
dereferenced <SPAN
CLASS="emphasis"
><I
CLASS="EMPHASIS"
>after</I
></SPAN
> being passed to a
function.</P
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="DEREFERENCECL"
></A
><P
><B
>Example 24-5. Dereferencing a parameter passed to a function</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
> 1 #!/bin/bash
2 # dereference.sh
3 # Dereferencing parameter passed to a function.
4 # Script by Bruce W. Clare.
5
6 dereference ()
7 {
8 y=\$"$1" # Name of variable (not value!).
9 echo $y # $Junk
10
11 x=`eval "expr \"$y\" "`
12 echo $1=$x
13 eval "$1=\"Some Different Text \"" # Assign new value.
14 }
15
16 Junk="Some Text"
17 echo $Junk "before" # Some Text before
18
19 dereference Junk
20 echo $Junk "after" # Some Different Text after
21
22 exit 0</PRE
></TD
></TR
></TABLE
><HR></DIV
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="REFPARAMS"
></A
><P
><B
>Example 24-6. Again, dereferencing a parameter passed to a function</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
> 1 #!/bin/bash
2 # ref-params.sh: Dereferencing a parameter passed to a function.
3 # (Complex Example)
4
5 ITERATIONS=3 # How many times to get input.
6 icount=1
7
8 my_read () {
9 # Called with my_read varname,
10 #+ outputs the previous value between brackets as the default value,
11 #+ then asks for a new value.
12
13 local local_var
14
15 echo -n "Enter a value "
16 eval 'echo -n "[$'$1'] "' # Previous value.
17 # eval echo -n "[\$$1] " # Easier to understand,
18 #+ but loses trailing space in user prompt.
19 read local_var
20 [ -n "$local_var" ] && eval $1=\$local_var
21
22 # "And-list": if "local_var" then set "$1" to its value.
23 }
24
25 echo
26
27 while [ "$icount" -le "$ITERATIONS" ]
28 do
29 my_read var
30 echo "Entry #$icount = $var"
31 let "icount += 1"
32 echo
33 done
34
35
36 # Thanks to Stephane Chazelas for providing this instructive example.
37
38 exit 0</PRE
></TD
></TR
></TABLE
><HR></DIV
><DIV
CLASS="VARIABLELIST"
><P
><B
><A
NAME="EXITRETURN1"
></A
>Exit and Return</B
></P
><DL
><DT
><B
CLASS="COMMAND"
>exit status</B
></DT
><DD
><P
>Functions return a value, called an <I
CLASS="FIRSTTERM"
>exit
status</I
>. This is analogous to the <A
HREF="exit-status.html#EXITSTATUSREF"
>exit status</A
> returned by a
command. The exit status may be explicitly specified
by a <B
CLASS="COMMAND"
>return</B
> statement, otherwise it
is the exit status of the last command in the function
(<SPAN
CLASS="RETURNVALUE"
>0</SPAN
> if successful, and a non-zero
error code if not). This <A
HREF="exit-status.html#EXITSTATUSREF"
>exit
status</A
> may be used in the script by referencing it
as <A
HREF="variables2.html#XSTATVARREF"
>$?</A
>. This mechanism
effectively permits script functions to have a <SPAN
CLASS="QUOTE"
>"return
value"</SPAN
> similar to C functions.</P
></DD
><DT
><B
CLASS="COMMAND"
>return</B
></DT
><DD
><P
><A
NAME="RETURNREF"
></A
></P
><P
>Terminates a function. A <B
CLASS="COMMAND"
>return</B
> command
<A
NAME="AEN18474"
HREF="#FTN.AEN18474"
>[1]</A
>
optionally takes an <I
CLASS="FIRSTTERM"
>integer</I
>
argument, which is returned to the calling script as
the <SPAN
CLASS="QUOTE"
>"exit status"</SPAN
> of the function, and
this exit status is assigned to the variable <A
HREF="variables2.html#XSTATVARREF"
>$?</A
>.</P
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="MAX"
></A
><P
><B
>Example 24-7. Maximum of two numbers</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="90%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
> 1 #!/bin/bash
2 # max.sh: Maximum of two integers.
3
4 E_PARAM_ERR=250 # If less than 2 params passed to function.
5 EQUAL=251 # Return value if both params equal.
6 # Error values out of range of any
7 #+ params that might be fed to the function.
8
9 max2 () # Returns larger of two numbers.
10 { # Note: numbers compared must be less than 250.
11 if [ -z "$2" ]
12 then
13 return $E_PARAM_ERR
14 fi
15
16 if [ "$1" -eq "$2" ]
17 then
18 return $EQUAL
19 else
20 if [ "$1" -gt "$2" ]
21 then
22 return $1
23 else
24 return $2
25 fi
26 fi
27 }
28
29 max2 33 34
30 return_val=$?
31
32 if [ "$return_val" -eq $E_PARAM_ERR ]
33 then
34 echo "Need to pass two parameters to the function."
35 elif [ "$return_val" -eq $EQUAL ]
36 then
37 echo "The two numbers are equal."
38 else
39 echo "The larger of the two numbers is $return_val."
40 fi
41
42
43 exit 0
44
45 # Exercise (easy):
46 # ---------------
47 # Convert this to an interactive script,
48 #+ that is, have the script ask for input (two numbers).</PRE
></TD
></TR
></TABLE
><HR></DIV
><DIV
CLASS="TIP"
><TABLE
CLASS="TIP"
WIDTH="90%"
BORDER="0"
><TR
><TD
WIDTH="25"
ALIGN="CENTER"
VALIGN="TOP"
><IMG
SRC="common/tip.png"
HSPACE="5"
ALT="Tip"></TD
><TD
ALIGN="LEFT"
VALIGN="TOP"
><P
>For a function to return a string or array, use a
dedicated variable.
<TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="90%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
> 1 count_lines_in_etc_passwd()
2 {
3 [[ -r /etc/passwd ]] && REPLY=$(echo $(wc -l < /etc/passwd))
4 # If /etc/passwd is readable, set REPLY to line count.
5 # Returns both a parameter value and status information.
6 # The 'echo' seems unnecessary, but . . .
7 #+ it removes excess whitespace from the output.
8 }
9
10 if count_lines_in_etc_passwd
11 then
12 echo "There are $REPLY lines in /etc/passwd."
13 else
14 echo "Cannot count lines in /etc/passwd."
15 fi
16
17 # Thanks, S.C.</PRE
></TD
></TR
></TABLE
>
</P
></TD
></TR
></TABLE
></DIV
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="EX61"
></A
><P
><B
>Example 24-8. Converting numbers to Roman numerals</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="90%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
> 1 #!/bin/bash
2
3 # Arabic number to Roman numeral conversion
4 # Range: 0 - 200
5 # It's crude, but it works.
6
7 # Extending the range and otherwise improving the script is left as an exercise.
8
9 # Usage: roman number-to-convert
10
11 LIMIT=200
12 E_ARG_ERR=65
13 E_OUT_OF_RANGE=66
14
15 if [ -z "$1" ]
16 then
17 echo "Usage: `basename $0` number-to-convert"
18 exit $E_ARG_ERR
19 fi
20
21 num=$1
22 if [ "$num" -gt $LIMIT ]
23 then
24 echo "Out of range!"
25 exit $E_OUT_OF_RANGE
26 fi
27
28 to_roman () # Must declare function before first call to it.
29 {
30 number=$1
31 factor=$2
32 rchar=$3
33 let "remainder = number - factor"
34 while [ "$remainder" -ge 0 ]
35 do
36 echo -n $rchar
37 let "number -= factor"
38 let "remainder = number - factor"
39 done
40
41 return $number
42 # Exercises:
43 # ---------
44 # 1) Explain how this function works.
45 # Hint: division by successive subtraction.
46 # 2) Extend to range of the function.
47 # Hint: use "echo" and command-substitution capture.
48 }
49
50
51 to_roman $num 100 C
52 num=$?
53 to_roman $num 90 LXXXX
54 num=$?
55 to_roman $num 50 L
56 num=$?
57 to_roman $num 40 XL
58 num=$?
59 to_roman $num 10 X
60 num=$?
61 to_roman $num 9 IX
62 num=$?
63 to_roman $num 5 V
64 num=$?
65 to_roman $num 4 IV
66 num=$?
67 to_roman $num 1 I
68 # Successive calls to conversion function!
69 # Is this really necessary??? Can it be simplified?
70
71 echo
72
73 exit</PRE
></TD
></TR
></TABLE
><HR></DIV
><P
>See also <A
HREF="testbranch.html#ISALPHA"
>Example 11-29</A
>.</P
><DIV
CLASS="IMPORTANT"
><TABLE
CLASS="IMPORTANT"
WIDTH="90%"
BORDER="0"
><TR
><TD
WIDTH="25"
ALIGN="CENTER"
VALIGN="TOP"
><IMG
SRC="common/important.png"
HSPACE="5"
ALT="Important"></TD
><TD
ALIGN="LEFT"
VALIGN="TOP"
><P
>The largest positive integer a function can return is
255. The <B
CLASS="COMMAND"
>return</B
> command is closely tied
to the concept of <A
HREF="exit-status.html#EXITSTATUSREF"
>exit
status</A
>, which accounts for this particular
limitation. Fortunately, there are various <A
HREF="assortedtips.html#RVT"
>workarounds</A
> for those situations
requiring a large integer return value from a
function.</P
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="RETURNTEST"
></A
><P
><B
>Example 24-9. Testing large return values in a function</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="90%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
> 1 #!/bin/bash
2 # return-test.sh
3
4 # The largest positive value a function can return is 255.
5
6 return_test () # Returns whatever passed to it.
7 {
8 return $1
9 }
10
11 return_test 27 # o.k.
12 echo $? # Returns 27.
13
14 return_test 255 # Still o.k.
15 echo $? # Returns 255.
16
17 return_test 257 # Error!
18 echo $? # Returns 1 (return code for miscellaneous error).
19
20 # =========================================================
21 return_test -151896 # Do large negative numbers work?
22 echo $? # Will this return -151896?
23 # No! It returns 168.
24 # Version of Bash before 2.05b permitted
25 #+ large negative integer return values.
26 # It happened to be a useful feature.
27 # Newer versions of Bash unfortunately plug this loophole.
28 # This may break older scripts.
29 # Caution!
30 # =========================================================
31
32 exit 0</PRE
></TD
></TR
></TABLE
><HR></DIV
><P
>A workaround for obtaining large integer <SPAN
CLASS="QUOTE"
>"return
values"</SPAN
> is to simply assign the <SPAN
CLASS="QUOTE"
>"return
value"</SPAN
> to a global variable.
<TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="90%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
> 1 Return_Val= # Global variable to hold oversize return value of function.
2
3 alt_return_test ()
4 {
5 fvar=$1
6 Return_Val=$fvar
7 return # Returns 0 (success).
8 }
9
10 alt_return_test 1
11 echo $? # 0
12 echo "return value = $Return_Val" # 1
13
14 alt_return_test 256
15 echo "return value = $Return_Val" # 256
16
17 alt_return_test 257
18 echo "return value = $Return_Val" # 257
19
20 alt_return_test 25701
21 echo "return value = $Return_Val" #25701</PRE
></TD
></TR
></TABLE
>
</P
><P
><A
NAME="CAPTURERETVAL"
></A
></P
><P
>A more elegant method is to have the function
<B
CLASS="COMMAND"
>echo</B
> its <SPAN
CLASS="QUOTE"
>"return
value to <TT
CLASS="FILENAME"
>stdout</TT
>,"</SPAN
> and
then capture it by <A
HREF="commandsub.html#COMMANDSUBREF"
>command
substitution</A
>. See the <A
HREF="assortedtips.html#RVT"
>discussion
of this</A
> in <A
HREF="assortedtips.html"
>Section 36.7</A
>.</P
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="MAX2"
></A
><P
><B
>Example 24-10. Comparing two large integers</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="90%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
> 1 #!/bin/bash
2 # max2.sh: Maximum of two LARGE integers.
3
4 # This is the previous "max.sh" example,
5 #+ modified to permit comparing large integers.
6
7 EQUAL=0 # Return value if both params equal.
8 E_PARAM_ERR=-99999 # Not enough params passed to function.
9 # ^^^^^^ Out of range of any params that might be passed.
10
11 max2 () # "Returns" larger of two numbers.
12 {
13 if [ -z "$2" ]
14 then
15 echo $E_PARAM_ERR
16 return
17 fi
18
19 if [ "$1" -eq "$2" ]
20 then
21 echo $EQUAL
22 return
23 else
24 if [ "$1" -gt "$2" ]
25 then
26 retval=$1
27 else
28 retval=$2
29 fi
30 fi
31
32 echo $retval # Echoes (to stdout), rather than returning value.
33 # Why?
34 }
35
36
37 return_val=$(max2 33001 33997)
38 # ^^^^ Function name
39 # ^^^^^ ^^^^^ Params passed
40 # This is actually a form of command substitution:
41 #+ treating a function as if it were a command,
42 #+ and assigning the stdout of the function to the variable "return_val."
43
44
45 # ========================= OUTPUT ========================
46 if [ "$return_val" -eq "$E_PARAM_ERR" ]
47 then
48 echo "Error in parameters passed to comparison function!"
49 elif [ "$return_val" -eq "$EQUAL" ]
50 then
51 echo "The two numbers are equal."
52 else
53 echo "The larger of the two numbers is $return_val."
54 fi
55 # =========================================================
56
57 exit 0
58
59 # Exercises:
60 # ---------
61 # 1) Find a more elegant way of testing
62 #+ the parameters passed to the function.
63 # 2) Simplify the if/then structure at "OUTPUT."
64 # 3) Rewrite the script to take input from command-line parameters.</PRE
></TD
></TR
></TABLE
><HR></DIV
><P
>Here is another example of capturing a function
<SPAN
CLASS="QUOTE"
>"return value."</SPAN
> Understanding it requires some
knowledge of <A
HREF="awk.html#AWKREF"
>awk</A
>.
<TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="90%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
> 1 month_length () # Takes month number as an argument.
2 { # Returns number of days in month.
3 monthD="31 28 31 30 31 30 31 31 30 31 30 31" # Declare as local?
4 echo "$monthD" | awk '{ print $'"${1}"' }' # Tricky.
5 # ^^^^^^^^^
6 # Parameter passed to function ($1 -- month number), then to awk.
7 # Awk sees this as "print $1 . . . print $12" (depending on month number)
8 # Template for passing a parameter to embedded awk script:
9 # $'"${script_parameter}"'
10
11 # Here's a slightly simpler awk construct:
12 # echo $monthD | awk -v month=$1 '{print $(month)}'
13 # Uses the -v awk option, which assigns a variable value
14 #+ prior to execution of the awk program block.
15 # Thank you, Rich.
16
17 # Needs error checking for correct parameter range (1-12)
18 #+ and for February in leap year.
19 }
20
21 # ----------------------------------------------
22 # Usage example:
23 month=4 # April, for example (4th month).
24 days_in=$(month_length $month)
25 echo $days_in # 30
26 # ----------------------------------------------</PRE
></TD
></TR
></TABLE
></P
><P
>See also <A
HREF="contributed-scripts.html#DAYSBETWEEN"
>Example A-7</A
>
and <A
HREF="contributed-scripts.html#STDDEV"
>Example A-37</A
>.</P
><P
><TT
CLASS="USERINPUT"
><B
>Exercise:</B
></TT
> Using what we have
just learned, extend the previous <A
HREF="functions.html#EX61"
>Roman numerals example</A
> to accept
arbitrarily large input.</P
></TD
></TR
></TABLE
></DIV
></DD
></DL
></DIV
><DIV
CLASS="VARIABLELIST"
><P
><B
><A
NAME="REDSTDINFUNC1"
></A
>Redirection</B
></P
><DL
><DT
><TT
CLASS="REPLACEABLE"
><I
>Redirecting the stdin
of a function</I
></TT
></DT
><DD
><P
>A function is essentially a <A
HREF="special-chars.html#CODEBLOCKREF"
>code block</A
>, which means its
<TT
CLASS="FILENAME"
>stdin</TT
> can be redirected (as in <A
HREF="special-chars.html#EX8"
>Example 3-1</A
>).</P
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="REALNAME"
></A
><P
><B
>Example 24-11. Real name from username</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="90%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
> 1 #!/bin/bash
2 # realname.sh
3 #
4 # From username, gets "real name" from /etc/passwd.
5
6
7 ARGCOUNT=1 # Expect one arg.
8 E_WRONGARGS=85
9
10 file=/etc/passwd
11 pattern=$1
12
13 if [ $# -ne "$ARGCOUNT" ]
14 then
15 echo "Usage: `basename $0` USERNAME"
16 exit $E_WRONGARGS
17 fi
18
19 file_excerpt () # Scan file for pattern,
20 { #+ then print relevant portion of line.
21 while read line # "while" does not necessarily need [ condition ]
22 do
23 echo "$line" | grep $1 | awk -F":" '{ print $5 }'
24 # Have awk use ":" delimiter.
25 done
26 } <$file # Redirect into function's stdin.
27
28 file_excerpt $pattern
29
30 # Yes, this entire script could be reduced to
31 # grep PATTERN /etc/passwd | awk -F":" '{ print $5 }'
32 # or
33 # awk -F: '/PATTERN/ {print $5}'
34 # or
35 # awk -F: '($1 == "username") { print $5 }' # real name from username
36 # However, it might not be as instructive.
37
38 exit 0</PRE
></TD
></TR
></TABLE
><HR></DIV
><P
>There is an alternate, and perhaps less confusing
method of redirecting a function's
<TT
CLASS="FILENAME"
>stdin</TT
>. This involves redirecting the
<TT
CLASS="FILENAME"
>stdin</TT
> to an embedded bracketed code
block within the function.
<TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="90%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
> 1 # Instead of:
2 Function ()
3 {
4 ...
5 } < file
6
7 # Try this:
8 Function ()
9 {
10 {
11 ...
12 } < file
13 }
14
15 # Similarly,
16
17 Function () # This works.
18 {
19 {
20 echo $*
21 } | tr a b
22 }
23
24 Function () # This doesn't work.
25 {
26 echo $*
27 } | tr a b # A nested code block is mandatory here.
28
29
30 # Thanks, S.C.</PRE
></TD
></TR
></TABLE
>
</P
><DIV
CLASS="NOTE"
><TABLE
CLASS="NOTE"
WIDTH="90%"
BORDER="0"
><TR
><TD
WIDTH="25"
ALIGN="CENTER"
VALIGN="TOP"
><IMG
SRC="common/note.png"
HSPACE="5"
ALT="Note"></TD
><TD
ALIGN="LEFT"
VALIGN="TOP"
><P
>Emmanuel Rouat's <A
HREF="sample-bashrc.html"
>sample <TT
CLASS="FILENAME"
>bashrc</TT
>
file</A
> contains some instructive examples of
functions.</P
></TD
></TR
></TABLE
></DIV
></DD
></DL
></DIV
></DIV
></DIV
><H3
CLASS="FOOTNOTES"
>Notes</H3
><TABLE
BORDER="0"
CLASS="FOOTNOTES"
WIDTH="100%"
><TR
><TD
ALIGN="LEFT"
VALIGN="TOP"
WIDTH="5%"
><A
NAME="FTN.AEN18474"
HREF="functions.html#AEN18474"
>[1]</A
></TD
><TD
ALIGN="LEFT"
VALIGN="TOP"
WIDTH="95%"
><P
>The <B
CLASS="COMMAND"
>return</B
> command is a
Bash <A
HREF="internal.html#BUILTINREF"
>builtin</A
>.</P
></TD
></TR
></TABLE
><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="process-sub.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="localvar.html"
ACCESSKEY="N"
>Next</A
></TD
></TR
><TR
><TD
WIDTH="33%"
ALIGN="left"
VALIGN="top"
>Process Substitution</TD
><TD
WIDTH="34%"
ALIGN="center"
VALIGN="top"
><A
HREF="part5.html"
ACCESSKEY="U"
>Up</A
></TD
><TD
WIDTH="33%"
ALIGN="right"
VALIGN="top"
>Local Variables</TD
></TR
></TABLE
></DIV
></BODY
></HTML
>
|