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
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML
><HEAD
><TITLE
>Debugging</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="Of Zeros and Nulls"
HREF="zeros.html"><LINK
REL="NEXT"
TITLE="Options"
HREF="options.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="zeros.html"
ACCESSKEY="P"
>Prev</A
></TD
><TD
WIDTH="80%"
ALIGN="center"
VALIGN="bottom"
></TD
><TD
WIDTH="10%"
ALIGN="right"
VALIGN="bottom"
><A
HREF="options.html"
ACCESSKEY="N"
>Next</A
></TD
></TR
></TABLE
><HR
ALIGN="LEFT"
WIDTH="100%"></DIV
><DIV
CLASS="CHAPTER"
><H1
><A
NAME="DEBUGGING"
></A
>Chapter 32. Debugging</H1
><TABLE
BORDER="0"
WIDTH="100%"
CELLSPACING="0"
CELLPADDING="0"
CLASS="EPIGRAPH"
><TR
><TD
WIDTH="45%"
> </TD
><TD
WIDTH="45%"
ALIGN="LEFT"
VALIGN="TOP"
><I
><P
><I
>Debugging is twice as hard as writing the code in the first
place. Therefore, if you write the code as cleverly as possible,
you are, by definition, not smart enough to debug it.</I
></P
><P
><I
>--Brian Kernighan</I
></P
></I
></TD
></TR
></TABLE
><P
>The Bash shell contains no built-in debugger, and only bare-bones
debugging-specific commands and constructs. Syntax errors or
outright typos in the script generate cryptic error messages that
are often of no help in debugging a non-functional script.</P
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="EX74"
></A
><P
><B
>Example 32-1. A buggy script</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
> 1 #!/bin/bash
2 # ex74.sh
3
4 # This is a buggy script.
5 # Where, oh where is the error?
6
7 a=37
8
9 if [$a -gt 27 ]
10 then
11 echo $a
12 fi
13
14 exit $? # 0! Why?</PRE
></TD
></TR
></TABLE
><HR></DIV
><P
>Output from script:
<TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="SCREEN"
> <TT
CLASS="COMPUTEROUTPUT"
>./ex74.sh: [37: command not found</TT
></PRE
></TD
></TR
></TABLE
>
What's wrong with the above script? Hint: after the
<I
CLASS="FIRSTTERM"
>if</I
>.</P
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="MISSINGKEYWORD"
></A
><P
><B
>Example 32-2. Missing <A
HREF="internal.html#KEYWORDREF"
>keyword</A
></B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
> 1 #!/bin/bash
2 # missing-keyword.sh
3 # What error message will this script generate? And why?
4
5 for a in 1 2 3
6 do
7 echo "$a"
8 # done # Required keyword 'done' commented out in line 8.
9
10 exit 0 # Will not exit here!
11
12 # === #
13
14 # From command line, after script terminates:
15 echo $? # 2</PRE
></TD
></TR
></TABLE
><HR></DIV
><P
>Output from script:
<TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="SCREEN"
> <TT
CLASS="COMPUTEROUTPUT"
>missing-keyword.sh: line 10: syntax error: unexpected end of file</TT
>
</PRE
></TD
></TR
></TABLE
>
Note that the error message does <SPAN
CLASS="emphasis"
><I
CLASS="EMPHASIS"
>not</I
></SPAN
> necessarily
reference the line in which the error occurs, but the line where the
Bash interpreter finally becomes aware of the error.
</P
><P
>Error messages may disregard comment lines in a script when
reporting the line number of a syntax error.</P
><P
>What if the script executes, but does not work as expected? This is the
all too familiar logic error.</P
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="EX75"
></A
><P
><B
>Example 32-3. <I
CLASS="FIRSTTERM"
>test24</I
>: another buggy script</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
> 1 #!/bin/bash
2
3 # This script is supposed to delete all filenames in current directory
4 #+ containing embedded spaces.
5 # It doesn't work.
6 # Why not?
7
8
9 badname=`ls | grep ' '`
10
11 # Try this:
12 # echo "$badname"
13
14 rm "$badname"
15
16 exit 0</PRE
></TD
></TR
></TABLE
><HR></DIV
><P
>Try to find out what's wrong with <A
HREF="debugging.html#EX75"
>Example 32-3</A
>
by uncommenting the <TT
CLASS="USERINPUT"
><B
>echo "$badname"</B
></TT
> line. Echo
statements are useful for seeing whether what you expect is
actually what you get.</P
><P
>In this particular case, <TT
CLASS="USERINPUT"
><B
>rm "$badname"</B
></TT
>
will not give the desired results because
<TT
CLASS="VARNAME"
>$badname</TT
> should not be quoted. Placing it
in quotes ensures that <B
CLASS="COMMAND"
>rm</B
> has only one
argument (it will match only one filename). A partial fix
is to remove to quotes from <TT
CLASS="VARNAME"
>$badname</TT
> and
to reset <TT
CLASS="VARNAME"
>$IFS</TT
> to contain only a newline,
<TT
CLASS="USERINPUT"
><B
>IFS=$'\n'</B
></TT
>. However, there are simpler
ways of going about it.
<TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
> 1 # Correct methods of deleting filenames containing spaces.
2 rm *\ *
3 rm *" "*
4 rm *' '*
5 # Thank you. S.C.</PRE
></TD
></TR
></TABLE
>
</P
><P
>Summarizing the symptoms of a buggy script,
<OL
TYPE="1"
><LI
><P
>It bombs with a <SPAN
CLASS="QUOTE"
>"<SPAN
CLASS="ERRORNAME"
>syntax error</SPAN
>"</SPAN
> message, or</P
></LI
><LI
><P
>It runs, but does not work as expected
(<SPAN
CLASS="ERRORNAME"
>logic error</SPAN
>).</P
></LI
><LI
><P
>It runs, works as expected, but has nasty side effects
(<SPAN
CLASS="ERRORNAME"
>logic bomb</SPAN
>).</P
></LI
></OL
>
</P
><P
><A
NAME="DEBUGTOOLS"
></A
></P
><P
>Tools for debugging non-working scripts include
<OL
TYPE="1"
><LI
><P
>Inserting <A
HREF="internal.html#ECHOREF"
>echo</A
>
statements at critical points in the script to trace the
variables, and otherwise give a snapshot of what is going
on.</P
><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
>Even better is an <B
CLASS="COMMAND"
>echo</B
> that echoes
only when <I
CLASS="FIRSTTERM"
>debug</I
> is on.</P
><P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="90%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
> 1 ### debecho (debug-echo), by Stefano Falsetto ###
2 ### Will echo passed parameters only if DEBUG is set to a value. ###
3 debecho () {
4 if [ ! -z "$DEBUG" ]; then
5 echo "$1" >&2
6 # ^^^ to stderr
7 fi
8 }
9
10 DEBUG=on
11 Whatever=whatnot
12 debecho $Whatever # whatnot
13
14 DEBUG=
15 Whatever=notwhat
16 debecho $Whatever # (Will not echo.)</PRE
></TD
></TR
></TABLE
></P
></TD
></TR
></TABLE
></DIV
></LI
><LI
><P
>Using the <A
HREF="extmisc.html#TEEREF"
>tee</A
> filter
to check processes or data flows at critical points.</P
></LI
><LI
><P
>Setting option flags <TT
CLASS="OPTION"
>-n -v -x</TT
></P
><P
><TT
CLASS="USERINPUT"
><B
>sh -n scriptname</B
></TT
> checks for
syntax errors without actually running the script. This is
the equivalent of inserting <TT
CLASS="USERINPUT"
><B
>set -n</B
></TT
> or
<TT
CLASS="USERINPUT"
><B
>set -o noexec</B
></TT
> into the script. Note
that certain types of syntax errors can slip past this
check.</P
><P
><TT
CLASS="USERINPUT"
><B
>sh -v scriptname</B
></TT
> echoes each
command before executing it. This is the equivalent of
inserting <TT
CLASS="USERINPUT"
><B
>set -v</B
></TT
> or <TT
CLASS="USERINPUT"
><B
>set
-o verbose</B
></TT
> in the script.</P
><P
>The <TT
CLASS="OPTION"
>-n</TT
> and <TT
CLASS="OPTION"
>-v</TT
>
flags work well together. <TT
CLASS="USERINPUT"
><B
>sh -nv
scriptname</B
></TT
> gives a verbose syntax check.</P
><P
><TT
CLASS="USERINPUT"
><B
>sh -x scriptname</B
></TT
> echoes the result each
command, but in an abbreviated manner. This is the equivalent of
inserting <TT
CLASS="USERINPUT"
><B
>set -x</B
></TT
> or
<TT
CLASS="USERINPUT"
><B
>set -o xtrace</B
></TT
> in the script.</P
><P
><A
NAME="UNDVARERR"
></A
></P
><P
>Inserting <TT
CLASS="USERINPUT"
><B
>set -u</B
></TT
> or
<TT
CLASS="USERINPUT"
><B
>set -o nounset</B
></TT
> in the script runs it, but
gives an <SPAN
CLASS="ERRORNAME"
>unbound variable</SPAN
> error message
and aborts the script.
<TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="90%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
> 1 set -u # Or set -o nounset
2
3 # Setting a variable to null will not trigger the error/abort.
4 # unset_var=
5
6 echo $unset_var # Unset (and undeclared) variable.
7
8 echo "Should not echo!"
9
10 # sh t2.sh
11 # t2.sh: line 6: unset_var: unbound variable</PRE
></TD
></TR
></TABLE
></P
></LI
><LI
><P
>Using an <SPAN
CLASS="QUOTE"
>"assert"</SPAN
> function to test a
variable or condition at critical points in a script. (This is
an idea borrowed from C.)</P
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="ASSERT"
></A
><P
><B
>Example 32-4. Testing a condition with an
<I
CLASS="FIRSTTERM"
>assert</I
></B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="90%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
> 1 #!/bin/bash
2 # assert.sh
3
4 #######################################################################
5 assert () # If condition false,
6 { #+ exit from script
7 #+ with appropriate error message.
8 E_PARAM_ERR=98
9 E_ASSERT_FAILED=99
10
11
12 if [ -z "$2" ] # Not enough parameters passed
13 then #+ to assert() function.
14 return $E_PARAM_ERR # No damage done.
15 fi
16
17 lineno=$2
18
19 if [ ! $1 ]
20 then
21 echo "Assertion failed: \"$1\""
22 echo "File \"$0\", line $lineno" # Give name of file and line number.
23 exit $E_ASSERT_FAILED
24 # else
25 # return
26 # and continue executing the script.
27 fi
28 } # Insert a similar assert() function into a script you need to debug.
29 #######################################################################
30
31
32 a=5
33 b=4
34 condition="$a -lt $b" # Error message and exit from script.
35 # Try setting "condition" to something else
36 #+ and see what happens.
37
38 assert "$condition" $LINENO
39 # The remainder of the script executes only if the "assert" does not fail.
40
41
42 # Some commands.
43 # Some more commands . . .
44 echo "This statement echoes only if the \"assert\" does not fail."
45 # . . .
46 # More commands . . .
47
48 exit $?</PRE
></TD
></TR
></TABLE
><HR></DIV
></LI
><LI
><P
>Using the <A
HREF="variables2.html#LINENOREF"
>$LINENO</A
>
variable and the <A
HREF="internal.html#CALLERREF"
>caller</A
>
builtin.</P
></LI
><LI
><P
><A
NAME="DEBUGTRAP"
></A
>Trapping at exit.</P
><P
>The <A
HREF="internal.html#EXITREF"
>exit</A
> command in a script
triggers a signal <SPAN
CLASS="RETURNVALUE"
>0</SPAN
>, terminating
the process, that is, the script itself.
<A
NAME="AEN19460"
HREF="#FTN.AEN19460"
>[1]</A
>
It is often useful to trap the
<I
CLASS="FIRSTTERM"
>exit</I
>, forcing a <SPAN
CLASS="QUOTE"
>"printout"</SPAN
>
of variables, for example. The <I
CLASS="FIRSTTERM"
>trap</I
>
must be the first command in the script.</P
></LI
></OL
>
</P
><DIV
CLASS="VARIABLELIST"
><P
><B
><A
NAME="TRAPREF1"
></A
>Trapping signals</B
></P
><DL
><DT
><B
CLASS="COMMAND"
>trap</B
></DT
><DD
><P
>Specifies an action on receipt of a
signal; also useful for debugging.</P
><P
><A
NAME="SIGNALD"
></A
></P
><TABLE
CLASS="SIDEBAR"
BORDER="1"
CELLPADDING="5"
><TR
><TD
><DIV
CLASS="SIDEBAR"
><A
NAME="AEN19477"
></A
><P
>A <I
CLASS="FIRSTTERM"
>signal</I
> is a message
sent to a process, either by the kernel or another
process, telling it to take some specified action
(usually to terminate). For example, hitting a
<A
HREF="special-chars.html#CTLCREF"
>Control-C</A
>
sends a user interrupt, an INT signal, to a running
program.</P
></DIV
></TD
></TR
></TABLE
><P
><SPAN
CLASS="emphasis"
><I
CLASS="EMPHASIS"
>A simple instance:</I
></SPAN
>
<TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="90%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
> 1 trap '' 2
2 # Ignore interrupt 2 (Control-C), with no action specified.
3
4 trap 'echo "Control-C disabled."' 2
5 # Message when Control-C pressed.</PRE
></TD
></TR
></TABLE
>
</P
></DD
></DL
></DIV
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="EX76"
></A
><P
><B
>Example 32-5. Trapping at exit</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
> 1 #!/bin/bash
2 # Hunting variables with a trap.
3
4 trap 'echo Variable Listing --- a = $a b = $b' EXIT
5 # EXIT is the name of the signal generated upon exit from a script.
6 #
7 # The command specified by the "trap" doesn't execute until
8 #+ the appropriate signal is sent.
9
10 echo "This prints before the \"trap\" --"
11 echo "even though the script sees the \"trap\" first."
12 echo
13
14 a=39
15
16 b=36
17
18 exit 0
19 # Note that commenting out the 'exit' command makes no difference,
20 #+ since the script exits in any case after running out of commands.</PRE
></TD
></TR
></TABLE
><HR></DIV
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="ONLINE"
></A
><P
><B
>Example 32-6. Cleaning up after <B
CLASS="KEYCAP"
>Control-C</B
></B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
> 1 #!/bin/bash
2 # logon.sh: A quick 'n dirty script to check whether you are on-line yet.
3
4 umask 177 # Make sure temp files are not world readable.
5
6
7 TRUE=1
8 LOGFILE=/var/log/messages
9 # Note that $LOGFILE must be readable
10 #+ (as root, chmod 644 /var/log/messages).
11 TEMPFILE=temp.$$
12 # Create a "unique" temp file name, using process id of the script.
13 # Using 'mktemp' is an alternative.
14 # For example:
15 # TEMPFILE=`mktemp temp.XXXXXX`
16 KEYWORD=address
17 # At logon, the line "remote IP address xxx.xxx.xxx.xxx"
18 # appended to /var/log/messages.
19 ONLINE=22
20 USER_INTERRUPT=13
21 CHECK_LINES=100
22 # How many lines in log file to check.
23
24 trap 'rm -f $TEMPFILE; exit $USER_INTERRUPT' TERM INT
25 # Cleans up the temp file if script interrupted by control-c.
26
27 echo
28
29 while [ $TRUE ] #Endless loop.
30 do
31 tail -n $CHECK_LINES $LOGFILE> $TEMPFILE
32 # Saves last 100 lines of system log file as temp file.
33 # Necessary, since newer kernels generate many log messages at log on.
34 search=`grep $KEYWORD $TEMPFILE`
35 # Checks for presence of the "IP address" phrase,
36 #+ indicating a successful logon.
37
38 if [ ! -z "$search" ] # Quotes necessary because of possible spaces.
39 then
40 echo "On-line"
41 rm -f $TEMPFILE # Clean up temp file.
42 exit $ONLINE
43 else
44 echo -n "." # The -n option to echo suppresses newline,
45 #+ so you get continuous rows of dots.
46 fi
47
48 sleep 1
49 done
50
51
52 # Note: if you change the KEYWORD variable to "Exit",
53 #+ this script can be used while on-line
54 #+ to check for an unexpected logoff.
55
56 # Exercise: Change the script, per the above note,
57 # and prettify it.
58
59 exit 0
60
61
62 # Nick Drage suggests an alternate method:
63
64 while true
65 do ifconfig ppp0 | grep UP 1> /dev/null && echo "connected" && exit 0
66 echo -n "." # Prints dots (.....) until connected.
67 sleep 2
68 done
69
70 # Problem: Hitting Control-C to terminate this process may be insufficient.
71 #+ (Dots may keep on echoing.)
72 # Exercise: Fix this.
73
74
75
76 # Stephane Chazelas has yet another alternative:
77
78 CHECK_INTERVAL=1
79
80 while ! tail -n 1 "$LOGFILE" | grep -q "$KEYWORD"
81 do echo -n .
82 sleep $CHECK_INTERVAL
83 done
84 echo "On-line"
85
86 # Exercise: Discuss the relative strengths and weaknesses
87 # of each of these various approaches.</PRE
></TD
></TR
></TABLE
><HR></DIV
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="PROGRESSBAR2"
></A
><P
><B
>Example 32-7. A Simple Implementation of a Progress Bar</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
> 1 #! /bin/bash
2 # progress-bar2.sh
3 # Author: Graham Ewart (with reformatting by ABS Guide author).
4 # Used in ABS Guide with permission (thanks!).
5
6 # Invoke this script with bash. It doesn't work with sh.
7
8 interval=1
9 long_interval=10
10
11 {
12 trap "exit" SIGUSR1
13 sleep $interval; sleep $interval
14 while true
15 do
16 echo -n '.' # Use dots.
17 sleep $interval
18 done; } & # Start a progress bar as a background process.
19
20 pid=$!
21 trap "echo !; kill -USR1 $pid; wait $pid" EXIT # To handle ^C.
22
23 echo -n 'Long-running process '
24 sleep $long_interval
25 echo ' Finished!'
26
27 kill -USR1 $pid
28 wait $pid # Stop the progress bar.
29 trap EXIT
30
31 exit $?</PRE
></TD
></TR
></TABLE
><HR></DIV
><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
>The <TT
CLASS="OPTION"
>DEBUG</TT
> argument to
<B
CLASS="COMMAND"
>trap</B
> causes a specified action to execute
after every command in a script. This permits tracing variables,
for example.
<DIV
CLASS="EXAMPLE"
><HR><A
NAME="VARTRACE"
></A
><P
><B
>Example 32-8. Tracing a variable</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
> 1 #!/bin/bash
2
3 trap 'echo "VARIABLE-TRACE> \$variable = \"$variable\""' DEBUG
4 # Echoes the value of $variable after every command.
5
6 variable=29; line=$LINENO
7
8 echo " Just initialized \$variable to $variable in line number $line."
9
10 let "variable *= 3"; line=$LINENO
11 echo " Just multiplied \$variable by 3 in line number $line."
12
13 exit 0
14
15 # The "trap 'command1 . . . command2 . . .' DEBUG" construct is
16 #+ more appropriate in the context of a complex script,
17 #+ where inserting multiple "echo $variable" statements might be
18 #+ awkward and time-consuming.
19
20 # Thanks, Stephane Chazelas for the pointer.
21
22
23 Output of script:
24
25 VARIABLE-TRACE> $variable = ""
26 VARIABLE-TRACE> $variable = "29"
27 Just initialized $variable to 29.
28 VARIABLE-TRACE> $variable = "29"
29 VARIABLE-TRACE> $variable = "87"
30 Just multiplied $variable by 3.
31 VARIABLE-TRACE> $variable = "87"</PRE
></TD
></TR
></TABLE
><HR></DIV
>
</P
></TD
></TR
></TABLE
></DIV
><P
>Of course, the <B
CLASS="COMMAND"
>trap</B
> command has other uses
aside from debugging, such as disabling certain keystrokes within a
script (see <A
HREF="contributed-scripts.html#STOPWATCH"
>Example A-43</A
>).</P
><DIV
CLASS="EXAMPLE"
><HR><A
NAME="MULTIPLEPROC"
></A
><P
><B
>Example 32-9. Running multiple processes (on an SMP box)</B
></P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
> 1 #!/bin/bash
2 # parent.sh
3 # Running multiple processes on an SMP box.
4 # Author: Tedman Eng
5
6 # This is the first of two scripts,
7 #+ both of which must be present in the current working directory.
8
9
10
11
12 LIMIT=$1 # Total number of process to start
13 NUMPROC=4 # Number of concurrent threads (forks?)
14 PROCID=1 # Starting Process ID
15 echo "My PID is $$"
16
17 function start_thread() {
18 if [ $PROCID -le $LIMIT ] ; then
19 ./child.sh $PROCID&
20 let "PROCID++"
21 else
22 echo "Limit reached."
23 wait
24 exit
25 fi
26 }
27
28 while [ "$NUMPROC" -gt 0 ]; do
29 start_thread;
30 let "NUMPROC--"
31 done
32
33
34 while true
35 do
36
37 trap "start_thread" SIGRTMIN
38
39 done
40
41 exit 0
42
43
44
45 # ======== Second script follows ========
46
47
48 #!/bin/bash
49 # child.sh
50 # Running multiple processes on an SMP box.
51 # This script is called by parent.sh.
52 # Author: Tedman Eng
53
54 temp=$RANDOM
55 index=$1
56 shift
57 let "temp %= 5"
58 let "temp += 4"
59 echo "Starting $index Time:$temp" "$@"
60 sleep ${temp}
61 echo "Ending $index"
62 kill -s SIGRTMIN $PPID
63
64 exit 0
65
66
67 # ======================= SCRIPT AUTHOR'S NOTES ======================= #
68 # It's not completely bug free.
69 # I ran it with limit = 500 and after the first few hundred iterations,
70 #+ one of the concurrent threads disappeared!
71 # Not sure if this is collisions from trap signals or something else.
72 # Once the trap is received, there's a brief moment while executing the
73 #+ trap handler but before the next trap is set. During this time, it may
74 #+ be possible to miss a trap signal, thus miss spawning a child process.
75
76 # No doubt someone may spot the bug and will be writing
77 #+ . . . in the future.
78
79
80
81 # ===================================================================== #
82
83
84
85 # ----------------------------------------------------------------------#
86
87
88
89 #################################################################
90 # The following is the original script written by Vernia Damiano.
91 # Unfortunately, it doesn't work properly.
92 #################################################################
93
94 #!/bin/bash
95
96 # Must call script with at least one integer parameter
97 #+ (number of concurrent processes).
98 # All other parameters are passed through to the processes started.
99
100
101 INDICE=8 # Total number of process to start
102 TEMPO=5 # Maximum sleep time per process
103 E_BADARGS=65 # No arg(s) passed to script.
104
105 if [ $# -eq 0 ] # Check for at least one argument passed to script.
106 then
107 echo "Usage: `basename $0` number_of_processes [passed params]"
108 exit $E_BADARGS
109 fi
110
111 NUMPROC=$1 # Number of concurrent process
112 shift
113 PARAMETRI=( "$@" ) # Parameters of each process
114
115 function avvia() {
116 local temp
117 local index
118 temp=$RANDOM
119 index=$1
120 shift
121 let "temp %= $TEMPO"
122 let "temp += 1"
123 echo "Starting $index Time:$temp" "$@"
124 sleep ${temp}
125 echo "Ending $index"
126 kill -s SIGRTMIN $$
127 }
128
129 function parti() {
130 if [ $INDICE -gt 0 ] ; then
131 avvia $INDICE "${PARAMETRI[@]}" &
132 let "INDICE--"
133 else
134 trap : SIGRTMIN
135 fi
136 }
137
138 trap parti SIGRTMIN
139
140 while [ "$NUMPROC" -gt 0 ]; do
141 parti;
142 let "NUMPROC--"
143 done
144
145 wait
146 trap - SIGRTMIN
147
148 exit $?
149
150 : <<SCRIPT_AUTHOR_COMMENTS
151 I had the need to run a program, with specified options, on a number of
152 different files, using a SMP machine. So I thought [I'd] keep running
153 a specified number of processes and start a new one each time . . . one
154 of these terminates.
155
156 The "wait" instruction does not help, since it waits for a given process
157 or *all* process started in background. So I wrote [this] bash script
158 that can do the job, using the "trap" instruction.
159 --Vernia Damiano
160 SCRIPT_AUTHOR_COMMENTS</PRE
></TD
></TR
></TABLE
><HR></DIV
><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
><TT
CLASS="USERINPUT"
><B
>trap '' SIGNAL</B
></TT
> (two adjacent
apostrophes) disables SIGNAL for the remainder of the
script. <TT
CLASS="USERINPUT"
><B
>trap SIGNAL</B
></TT
> restores
the functioning of SIGNAL once more. This is useful to
protect a critical portion of a script from an undesirable
interrupt.</P
></TD
></TR
></TABLE
></DIV
><P
><TABLE
BORDER="0"
BGCOLOR="#E0E0E0"
WIDTH="100%"
><TR
><TD
><PRE
CLASS="PROGRAMLISTING"
> 1 trap '' 2 # Signal 2 is Control-C, now disabled.
2 command
3 command
4 command
5 trap 2 # Reenables Control-C
6 </PRE
></TD
></TR
></TABLE
></P
><TABLE
CLASS="SIDEBAR"
BORDER="1"
CELLPADDING="5"
><TR
><TD
><DIV
CLASS="SIDEBAR"
><A
NAME="AEN19513"
></A
><P
><A
HREF="bashver3.html#BASH3REF"
>Version 3</A
> of Bash adds the
following <A
HREF="variables2.html#INTERNALVARIABLES1"
>internal
variables</A
> for use by the debugger.
<OL
TYPE="1"
><LI
><P
><TT
CLASS="VARNAME"
>$BASH_ARGC</TT
></P
><P
>Number of command-line arguments passed to script,
similar to <A
HREF="variables2.html#CLACOUNTREF"
><TT
CLASS="VARNAME"
>$#</TT
></A
>.</P
></LI
><LI
><P
><TT
CLASS="VARNAME"
>$BASH_ARGV</TT
></P
><P
>Final command-line parameter passed to script, equivalent
<A
HREF="othertypesv.html#LASTARGREF"
><TT
CLASS="VARNAME"
>${!#}</TT
></A
>.</P
></LI
><LI
><P
><TT
CLASS="VARNAME"
>$BASH_COMMAND</TT
></P
><P
>Command currently executing.</P
></LI
><LI
><P
><TT
CLASS="VARNAME"
>$BASH_EXECUTION_STRING</TT
></P
><P
>The <I
CLASS="FIRSTTERM"
>option string</I
> following the
<TT
CLASS="OPTION"
>-c</TT
> <A
HREF="bash-options.html#CLOPTS"
>option</A
>
to Bash.</P
></LI
><LI
><P
><TT
CLASS="VARNAME"
>$BASH_LINENO</TT
></P
><P
>In a <A
HREF="functions.html#FUNCTIONREF"
>function</A
>,
indicates the line number of the function call.</P
></LI
><LI
><P
><TT
CLASS="VARNAME"
>$BASH_REMATCH</TT
></P
><P
>Array variable associated with <B
CLASS="COMMAND"
>=~</B
>
<A
HREF="bashver3.html#REGEXMATCHREF"
>conditional regex
matching</A
>.</P
></LI
><LI
><P
><A
NAME="BASHSOURCEREF"
></A
></P
><P
><TT
CLASS="VARNAME"
>$BASH_SOURCE</TT
></P
><P
>This is the name of the script, usually the same as
<A
HREF="othertypesv.html#ARG0"
>$0</A
>.</P
></LI
><LI
><P
> <A
HREF="variables2.html#BASHSUBSHELLREF"
><TT
CLASS="VARNAME"
>$BASH_SUBSHELL</TT
></A
></P
></LI
></OL
></P
></DIV
></TD
></TR
></TABLE
></DIV
><H3
CLASS="FOOTNOTES"
>Notes</H3
><TABLE
BORDER="0"
CLASS="FOOTNOTES"
WIDTH="100%"
><TR
><TD
ALIGN="LEFT"
VALIGN="TOP"
WIDTH="5%"
><A
NAME="FTN.AEN19460"
HREF="debugging.html#AEN19460"
>[1]</A
></TD
><TD
ALIGN="LEFT"
VALIGN="TOP"
WIDTH="95%"
><P
>By convention, <TT
CLASS="REPLACEABLE"
><I
>signal
0</I
></TT
> is assigned to <A
HREF="exit-status.html#EXITCOMMANDREF"
>exit</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="zeros.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="options.html"
ACCESSKEY="N"
>Next</A
></TD
></TR
><TR
><TD
WIDTH="33%"
ALIGN="left"
VALIGN="top"
>Of Zeros and Nulls</TD
><TD
WIDTH="34%"
ALIGN="center"
VALIGN="top"
><A
HREF="part5.html"
ACCESSKEY="U"
>Up</A
></TD
><TD
WIDTH="33%"
ALIGN="right"
VALIGN="top"
>Options</TD
></TR
></TABLE
></DIV
></BODY
></HTML
>
|