bug-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

More convenient tracing


From: Dale R. Worley
Subject: More convenient tracing
Date: Wed, 25 Jan 2023 15:00:27 -0500

Some time ago I proposed a new option to Bash to cause it to trace
commands (in the manner of -x) but not within the Bash initialization
scripts.  People advised me that this could be accomplished without a
new option.  I also picked up various suggestions for how to design
it.

This is my latest version.  Comments are requested.

The feature is configured by adding the following lines to the end of
~/.bashrc.  Setting the environment variable BASH_XTRACE causes Bash
to trace the body of the script which it is currently executing.  The
value of BASH_XTRACE is the file name into which to write the trace.
Similarly BASH_XTRACE_ALL causes Bash to trace the body of the current
script and any scripts which are invoked as subprocesses.  The aliases
XTRACE and XTRACE_ALL cause tracing into stderr, which is the common
case.

    $ cat ~/.bashrc
    [various customizations]

    # Insert at the end of ~/.bashrc.
    # "BASH_XTRACE=file shell-script" causes the body of shell-script to be 
executed
    # with xtrace and xtrace output sent to "file".
    # "BASH_XTRACE_ALL=file command" causes the bodies of all descendant
    # shell scripts to be executed with xtrace and xtrace output sent to
    # "file".

    # Aliases to make using these features in the standard way easy.
    alias XTRACE='BASH_XTRACE=/dev/stderr '
    alias XTRACE_ALL='BASH_XTRACE_ALL=/dev/stderr '

    if [[ -n "$BASH_XTRACE" ]] || [[ -n "$BASH_XTRACE_ALL" ]]
    then
        exec {BASH_XTRACEFD}>${BASH_XTRACE:-$BASH_XTRACE_ALL}
        unset BASH_XTRACE
        set -x
    fi

Two test scripts; uu invokes tt.

    $ cat ./tt
    #! /bin/bash

    echo 'Now in tt.'

    $ cat ./uu
    #! /bin/bash

    echo 'Now in uu.'
    ./tt

Tracing with -x prints a lot of (usually) useless lines.

    $ bash -x ./tt
    [300+ lines of Bash initializations]
    + echo 'Now in tt.'
    Now in tt.

XTRACE traces only the commands in the script itself.

    $ XTRACE bash ./tt
    + echo 'Now in tt.'
    Now in tt.

XTRACE of uu shows the invocation of tt but not the commands within tt.

    $ XTRACE bash ./uu
    + echo 'Now in uu.'
    Now in uu.
    + ./tt
    Now in tt.

XTRACE_ALL of uu also shows the commands within tt.

    $ XTRACE_ALL bash ./uu
    + echo 'Now in uu.'
    Now in uu.
    + ./tt
    + echo 'Now in tt.'
    Now in tt.
    $

Dale



reply via email to

[Prev in Thread] Current Thread [Next in Thread]