Home > Articles > Operating Systems, Server > Linux/UNIX/Open Source

This chapter is from the book

Shell Tracing

There are many instances when syntax checking will give your script a clean bill of health, even though bugs are still lurking within it. Running syntax checking on a shell script is similar to running a spelling checker on a text document—it might find most of the misspellings, but it can't fix problems like read spelled red. In order to find and fix these types of errors in a text document, you need to proofread it. Shell tracing is proofreading your shell script.

In shell tracing mode each command is printed in the exact form that it is executed. For this reason, shell tracing mode is often referred to as execution tracing mode. Shell tracing is enabled by the -x option (x as in execution). The following command enables tracing for an entire script:

$ /bin/sh -x script arg1 arg2 ... argN

Tracing can also be enabled using the set command:

set -x

To get an idea of what the output of shell tracing looks like, try the following command:

$ set -x ; ls *.sh ; set +x

The output will be similar to the following:

+ ls buggy.sh buggy1.sh buggy2.sh buggy3.sh buggy4.sh 
buggy.sh  buggy1.sh buggy2.sh buggy3.sh buggy4.sh
+ set +x

In the output, the lines preceded by the plus (+) character are the commands that the shell executes. The other lines are output from those commands. As you can see from the output, the shell prints the exact ls command it executes. This is extremely useful in debugging because it enables you to determine whether all the substitutions were performed correctly.

Finding Syntax Bugs Using Shell Tracing

In the preceding example, you used the script buggy2.sh. One of the problems with this script is that it deleted the old backup before asking whether you wanted to make a new backup. To solve this problem, the script is rewritten as follows:

#!/bin/sh

Failed() {
  if [ $1 -ne 0 ] ; then
    echo "Failed. Exiting." ; exit 1 ;
  fi
  echo "Done."
}

YesNo() {
  echo "$1 (y/n)? \c"
  read RESPONSE
  case $RESPONSE in
    [yY]|[Yy][Ee][Ss]) RESPONSE=y ;;
    [nN]|[Nn][Oo]) RESPONSE=n ;;
  esac
}

YesNo "Make backup"
if [ $RESPONSE = "y" ] ; then

  echo "Deleting old backups, please wait... \c"
  rm -fr backup > /dev/null 2>&1
  Failed $?

  echo "Making new backups, please wait... \c"
  cp -r docs backup
  Failed 

fi

There are at least three syntax bugs in this script and at least one logical oversight. See if you can find them.

Assuming that the script is called buggy3.sh, first check its syntax as follows:

$ /bin/sh -n ./buggy3.sh

Because there is no output, you can execute it:

$ /bin/sh ./buggy3.sh

The script first prompts you as follows:

Make backup (y/n)?

Answering y to this prompt produces output similar to the following:

Deleting old backups, please wait... Done.
Making new backups, please wait... buggy3.sh: test: argument expected

Now you know there is a problem with the script, but the error message doesn't tell you where it is, so you need to track it down manually. From the output you know that the old backup was deleted successfully; therefore, the error is probably in the following part of the script:

  echo "Making new backups, please wait... \c"
  cp -r docs backup
  Failed 

Let's just enable shell tracing for this section:

  set -x
  echo "Making new backups, please wait... \c"
  cp -r docs backup
  Failed
  set +x

The output changes as follows (assuming you answer y to the question):

Make backup (y/n)? y
Deleting old backups, please wait... Done.
+ echo Making new backups, please wait... \c 
Making new backups, please wait... + cp -r docs backup 
+ Failed 
+ [ -ne 0 ] 
buggy3.sh: test: argument expected

From this output you can see that the problem occurred in the following statement:

[ -ne 0 ]

From Chapter 11, "Flow Control," you know that the form of a numerical test command is

[ num1 operator num2 ]

Here it looks like num1 does not exist. Also from the trace you can tell that this error occurred after executing the Failed function:

Failed() {
  if [ $1 -ne 0 ] ; then
    echo "Failed. Exiting." ; exit 1 ;
  fi
  echo "Done."
}

There is only one numerical test in this function; the test that compares $1, the first argument to the function, to see whether it is equal to 0. The problem should be obvious now. When Failed was invoked, you forgot to give it an argument:

  echo "Making new backups, please wait... \c"
  cp -r docs backup
  Failed

Therefore, the numeric test failed. There are two possible fixes for this bug. The first is to fix the code that calls the function:

  echo "Making new backups, please wait... \c"
  cp -r docs backup
  Failed $?

The second is to fix the function itself by quoting the first argument, "$1":

Failed() {
  if [ "$1" -ne 0 ] ; then
    echo "Failed. Exiting." ; exit 1 ;
  fi
  echo "Done."
}

By quoting the first argument, "$1", the shell uses the null or empty string when the function is called without any arguments. In this case the numeric test will not fail because both num1 and num2 have a value.

The best idea is to perform both fixes. After these fixes are applied, the shell tracing output is similar to the following:

Make backup (y/n)? y
Deleting old backups, please wait... Done.
+ echo Making new backups, please wait... \c 
Making new backups, please wait... + cp -r docs backup 
+ Failed 
+ [ -ne 0 ] 
+ echo Done. 
Done. 
+ set +x

Finding Logical Bugs Using Shell Tracing

As mentioned before, there is at least one logical bug in this script. With the help of shell tracing, you can locate and fix this bug.

Consider the prompt produced by this script:

Make backup (y/n)?

If you do not type a response but simply press Enter or Return, the script reports an error similar to the following:

./buggy3.sh: [: =: unary operator expected

To determine where this error occurs, it is probably best to run the entire script in shell tracing mode:

$ /bin/sh -x ./buggy3.sh

The output is similar to the following:

+ YesNo Make backup
+ echo Make backup (y/n)? \c
+ /bin/echo Make backup (y/n)? \c
Make backup (y/n)? + read RESPONSE

+ [ = y ]
./buggy3.sh: [: =: unary operator expected

The blank line is the result of pressing Enter or Return without typing a response to the prompt. The next line that the shell executes is the source of the error message:

[ = y ]

Which is part of the if statement:

if [ $RESPONSE = "y" ] ; then

Although this problem can be fixed by just quoting $RESPONSE,

if [ "$RESPONSE" = "y" ] ; then

the better fix is to determine why it is not set and change that code so that it always sets $RESPONSE. Looking at the script, you find that this variable is set by the function YesNo:

YesNo() {
  echo "$1 (y/n)? \c"
  read RESPONSE
  case $RESPONSE in
    [yY]|[Yy][Ee][Ss]) RESPONSE=y ;;
    [nN]|[Nn][Oo]) RESPONSE=n ;;
  esac
}

There are two problems here. The first one is that the read command

read RESPONSE

will not set a value for $RESPONSE if the user just presses Enter or Return. Because you can't change the read command, you need to find a different method to solving the problem. Basically you have a logical problem—the case statement needs to validate the user input, which it is currently not doing. A simple fix for the problem is to change YesNo as follows:

YesNo() {
  echo "$1 (y/n)? \c"
  read RESPONSE
  case "$RESPONSE" in
    [yY]|[Yy][Ee][Ss]) RESPONSE=y ;;
    *) RESPONSE=n ;;
  esac
}

Now you treat all responses other than "yes" as negative responses. This includes null responses generated when the user simply types Enter or Return.

Using Debugging Hooks

In the previous examples, you were able to deduce the location of a bug using shell tracing. In order to enable tracing for a particular part of the script, you have to edit the script and insert the debug command:

set -x

For larger scripts, a better practice is to embed debugging hooks. Debugging hooks are functions that enable shell tracing in critical code sections. Debugging hooks are normally activated in one of two ways:

  • The script is run with a command-line option (commonly -d or -x).

  • The script is run with an environment variable set to true (commonly DEBUG=true or TRACE=true).

The following function enables you to activate and deactivate debugging by setting $DEBUG to true:

Debug() {
  if [ "$DEBUG" = "true" ] ; then
    if [ "$1" = "on" -o "$1" = "ON" ] ; then
      set -x
    else
      set +x
    fi
  fi
}

To activate debugging, you can use the following:

Debug on

To deactivate debugging, you can use either of the following:

Debug
Debug off

Actually, passing any argument to this function other than on or ON deactivates debugging.

NOTE

The normal practice, with regard to debugging, is to activate it only when necessary. By default, debugging should be off.

To demonstrate the use of this function, you can modify the functions in the script buggy3.sh to have debugging automatically enabled if the variable DEBUG is set. The modified version of buggy3.sh is as follows:

#!/bin/sh

Debug() {
  if [ "$DEBUG" = "true" ] ; then
    if [ "$1" = "on" -o "$1" = "ON" ] ; then
      set -x
    else
      set +x
    fi
  fi
}

Failed() {
  Debug on
  if [ "$1" -ne 0 ] ; then
    echo "Failed. Exiting." ; exit 1 ;
  fi
  echo "Done."
  Debug off
}

YesNo() {
  Debug on
  echo "$1 (y/n)? \c"
  read RESPONSE
  case "$RESPONSE" in
    [yY]|[Yy][Ee][Ss]) RESPONSE=y ;;
    *) RESPONSE=n ;;
  esac
  Debug off
}

YesNo "Make backup"
if [ "$RESPONSE" = "y" ] ; then

  echo "Deleting old backups, please wait... \c"
  rm -r backup > /dev/null 2>&1
  Failed $?

  echo "Making new backups, please wait... \c"
  cp -r docs backup
  Failed $?
fi

There is no change in the output if the script is executed in either of the following ways:

$ /bin/sh ./buggy3.sh
$ ./buggy3.sh

The output includes shell tracing if the same script is executed in either of the following ways:

$ DEBUG=true /bin/sh ./buggy3.sh
$ DEBUG=true ./buggy3.sh

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020