|
|
At times you may need to debug a program to find and correct errors. Two options to the sh command can help you debug a program:
To try these two options, create a shell program that has an error in it. For example, create a file called bug that contains the following list of commands:
$ cat bug today=`date` echo enter person read person mail $1 $person When you log off come into my office please. $today. MLH $
Notice that today equals the output of the date command, which must be enclosed in grave accents for command substitution to occur.
The mail message sent to Tom at login tommy ($1) should look like the following screen:
$ mail From mlh Wed Apr 10 11:36 CST 1991 Tom When you log off come into my office please. Wed Apr 10 11:36:32 CST 1991 MLH ? .
To execute bug, you have to press the <BREAK> or <DELETE> key to end the program.
To debug this program, try executing bug using sh -v. This will print the lines of the file as they are read by the system, as shown below:
$ sh -v bug tommy today=`date` echo enter person enter person read person tom mail $1
Notice the output stops on the mail command, since there is a problem with mail. You must use the here document to redirect input into mail.
Before you fix the bug program, try executing it with sh -x, which prints the commands and their arguments as they are read by the system.
$ sh -x bug tommy +date today=Wed Apr 10 11:07:23 CST 1991 + echo enter person enter person + read person tom + mail tommy $Once again, the program stops at the mail command. Notice that the substitutions for the variables have been made and are displayed.
The corrected bug program is as follows:
$ cat bug today=`date` echo enter person read person mail $1 <<! $person When you log off come into my office please. $today MLH ! $The tee command is helpful for debugging pipelines. While simply passing its standard input to its standard output, it also saves a copy of its input into the file whose name is given as an argument.
The general format of the tee command is:
command_1 | tee saverfile | command_2saverfile is the file in which the output of command_1 is saved for you to study.
For example, suppose you want to check on the output of the grep command in the following command line:
who | grep $1 | cut -c1-9You can use tee to copy the output of grep into a file called check, without disturbing the rest of the pipeline.
who | grep $1 | tee check | cut -c1-9The file check contains a copy of the grep output:
$ who | grep mlhmo | tee check | cut -c1-9 mlhmo $ cat check mlhmo tty61 Apr 10 11:30 $