     [file version.texi not included]
     [file macros.texi not included]

This file documents the BASH debugger BASH.

This is the EDITION Edition, UPDATED, of Debugging with BASHDB: the GNU Source-Level Debugger for BASH

Copyright (C) 2002, 2003, 2004, 2006, 2007, 2008, 2009 Rocky Bernstein for the Free Software Foundation.

Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.1 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.

Debugging with
**************

This file describes the BASH debugger, the BASH symbolic debugger.

This is the EDITION Edition, UPDATED, for BASH.

Copyright (C) 2002, 2003, 2004, 2006, 2007, 2008, 2009 Rocky Bernstein

Summary of the BASH Debugger
****************************

The purpose of a debugger such as is to allow you to see what is going on ``inside'' a bash script while it executes.

can do four main kinds of things (plus other things in support of
these) to help you catch bugs in the act:

  * Start your script, specifying anything that might affect its behavior.

  * Make your script stop on specified conditions.

  * Examine what has happened, when your script has stopped.

  * Change things in your script, so you can experiment with correcting the effects of one bug and go on to learn about another.

Although you can use the BASH debugger to debug scripts written in BASH, it can also be used just as a front-end for learning more about programming in BASH. As an additional aid, the debugger can be used within the context of an existing script with its functions and variables that have already been initialized; fragments of the existing can be experimented with by entering them inside the debugger.

A Sample BASH Debugger Session
==============================

You can use this manual at your leisure to read all about the BASH debugger. However, a handful of commands are enough to get started using the debugger.  This chapter illustrates those commands.

Below we will debug a script that contains a function to compute the factorial of a number: fact(0) is 1 and fact(n) is n*fact(n-1).

     $ bashdb -L .  /tmp/fact.sh
     Bourne-Again Shell Debugger, release bash-VERSION
     Copyright 2002, 2003, 2004, 2006, 2007, 2008, 2009 Rocky Bernstein
     This is free software, covered by the GNU General Public License, and you are
     welcome to change it and/or distribute copies of it under certain conditions.

     (/tmp/fact.sh:9):
       9:	echo fact 0 is: `fact 0`
     bashdb<0> -
       1:    #!/usr/local/bin/bash
       2:    fact() {
       3:    ((n==0)) && echo 1 && return
       4:    ((nm1=n-1))
       5:    ((result=n*`fact $nm1`))
       6:    echo $result
       7:    }
       8:
       9:==> echo fact 0 is: `fact 0`
     bashdb<1> list
      10:   echo fact 3 is: $(fact 3)

The command invocation uses the option ``-L .'' Here we assume that the bashdb script and the debugger files are in the same location. If you are running from the source code, this will be the case. However if bashdb has been installed this probably won't be true and here you probably don't need to use ``-L .'' Instead you would type simply bashdb /tmp/fact.sh.

Position information consists of a filename and line number, e.g. (/tmp/fact.sh:9) and is given parenthesis. This position format is similar to that used by the Perl debugger and is also in the same format used by my GNU make debugger (http://bashdb.sourceforge.net/remake) the Extended Python Debugger http://remake.sourceforge.net/pydb, and one for Ruby (http://bashdb.sorceforge.net/ruby-debug.html).  GNU Emacs and DDD can parse this and in fact the same regular expression is used on the 3 debuggers.

The first debugger command we gave -, we listed a window of lines before where we were executing. Because the window, 10 lines, is larger than the number of lines to the top of the file we printed only 9 lines here. The next command, list, starts from the current line and again wants to print 10 lines but because there are only one remaining line, that is what is printed.

     bashdb<2> step
     (/tmp/fact.sh:9):
     fact 0
     9:	echo fact 0 is: `fact 0`
     bashdb<(3)> RET
     2:	fact() {
     bashdb<(4)> RET
     3:	((n==0)) && echo 1 && return
     bashdb<(5)> print $n

     bashdb<(6)>

Ooops... The variable n isn't initialized. (Recall that
variables in BASH don't need to be declared before they are
referred to and that the default value would be the a null value which
here prints as an empty string.)

The first step command steps the script one instruction. It may seem odd that the line printed is exactly the same one as before. What has happened though is that we've ``stepped'' into the subshell needed to run `fact 0`; we haven't however started running anything inside that subshell yet though.

To indicate that which piece of the multi-part line echo fact 0 is: `fact 0` we show that part all by itself fact 0. If nothing is shown then it means we are running the beginning statement or in this case the outermost statement.

To indicate that we are now nested in a subshell, notice that the command number, starting with 3, or the third command entered, now appears in parenthesis. Each subshell nesting adds a set of parenthesis.

The first step command steps the script one instruction; it didn't advance the line number, 9, at all. That is because we were stopping before the command substitution or backtick is to take place. The second command we entered was just hitting the return key; bashdb remembers that you entered step previously, so it runs the step rather than next, the other alternative when you hit RET. Step one more instruction and we are just before running the first statement of the function.

Next, we print the value of the variable n. Notice we need to add a preceding dollar simple to get the substitution or value of n. As we will see later, if the pe command were used this would not be necessary.

We now modify the file to add an assignment to local variable n and restart.

     bashdb<6> restart
     Restarting with: /usr/local/bin/bashdb -L . fact.sh
     (/tmp/fact.sh:10):
     10:	echo fact 0 is: `fact 0`
     bashdb<0> list 1
       1:    #!/usr/local/bin/bash
       2:    fact() {
       3:    local -i n=${1:0}
       4:    ((n==0)) && echo 1 && return
       5:    ((nm1=n-1))
       6:    ((result=n*`fact $nm1`))
       7:    echo $result
       8:    }
       9:
      10:==> echo fact 0 is: `fact 0`
     bashdb<1> s 3
     (/tmp/fact.sh:3):
     3:	local -i n=${1:0}
     bashdb<(2)> step
     (/tmp/fact.sh:4):
     4:	((n==0)) && echo 1 && return
     bashdb<(3)> print $n
     print $n
     0

This time we use the list debugger command to list the lines in the file. From before we know it takes three step commands before we get into the fact() function, so we add a count onto the step command. Notice we abbreviate step with s; we could have done likewise and abbreviated list with l.

     bashdb<(4)> RET
     (/tmp/fact.sh:4):
     4:	((n==0)) && echo 1 && return
     echo 1
     bashdb<(5)> RET
     (/tmp/fact.sh:4):
     4:	((n==0)) && echo 1 && return
     return

Again we just use RET to repeat the last step commands. And again the fact that we are staying on the same line 4 means that the next condition in the line is about to be executed. Notice that we see the command (echo 1 or return) listed when we stay on the same line which has multiple stopping points in it. Given the information above, we know that the value echo'ed on return will be 1.

     bashdb<(6)> RET
     fact 0 is: 1
     (/tmp/fact.sh:12):
     12:	echo fact 3 is: $(fact 3)
     bashdb<(7)> break 5
     Breakpoint 1 set in file fact.sh, line 5.
     bashdb<(8)> continue

We saw that we could step with a count into the function fact(). However above took another approach: we set a stopping point or ``breakpoint'' at line 5 to get us a little ways into the fact() subroutine. Just before line 5 is to executed, we will get back into the debugger. The continue command just resumes execution until the next stopping point which has been set up in some way.

     (/tmp/fact.sh:5):
     5:      ((nm1=n-1))
     Breakpoint 1 hit(1 times).
     bashdb<(8)> x n-1
     2
     bashdb<(9)> s
     (/tmp/fact.sh:5):
     6:     ((result=n*`fact $nm1`))
     bashdb<(10)> c
     fact.sh: line 6: ((: result=n*: syntax error: operand expected (error token is "*")
     bashdb<(7)> R
     Restarting with: bash --debugger fact.sh
     11:	echo fact 0 is: `fact 0`
     bashdb<0> l fact
      2:    fact ()
      3:    {
      4:       local -i n=${1:0};
      5:       (( "n==0" )) && echo 1 && return;
      6:       (( nm1=n-1 ));
      7:       ((fact_nm1=`fact $nm1`))
      8:       (( "result=n*fact_nm1" ));
      9:       echo $result
     10:    }

In addition to listing by line numbers, we can also list giving a function name. Below, instead of setting a breakpoint at line 5 and running ``continue'' as we did above, we try something slightly shorter and slightly different. We give the line number on the ``continue'' statement. This is a little different in that a one-time break is made on line 5. Once that statement is reached the breakpoint is removed.

     bashdb<1> continue 5
     One-time breakpoint 1 set in file fact.sh, line 5.
     fact 0 is: 1
     (/tmp/fact.sh:5):
     5:	((nm1=n-1))
     bashdb<(2)> s
     6:	((fact_nm1=`fact $nm1`))
     bashdb<(3)> s
     2:	fact() {
     bashdb<(4)> T
     ->0 in file `fact.sh' at line 2
     ##1 fact("3") called from file `fact.sh' at line 12
     ##2 source("fact.sh") called from file `/usr/local/bin/bashdb' at line 154
     ##3 main("fact.sh") called from file `/usr/local/bin/bashdb' at line 0
     bashdb<(5)> c
     fact 3 is: 6
     Debugged program terminated normally. Use q to quit or R to restart.

When we stop at line 5 above, we have already run fact(0) and output the correct results. The output from the program ``fact 0 is: 1'' is intermixed with the debugger output. The T command above requests call stack output and this confirms that we are not in the fact(0) call but in the fact(3) call. There are 4 lines listed in the stack trace even though there is just one call from the main program. The top line of the trace doesn't really represent a call, it's just where we currently are in the program. That last line is an artifact of invoking bash from the bashdb script rather than running bash --debugger.

The last message in the output above Debugged program exited
normally. is from the BASH debugger; it indicates script has finished executing.  We can end our bashdb session with the bashdb quit command.

Above we did our debugging session on the command line. If you are a GNU Emacs user, you can do your debugging inside that. Also there is a(nother) GUI interface called DDD that supports the BASH debugger.

Interactive Line Tracing Session
================================

One of the things I had found disappointing about the default set -x tracing behavior is that no position information is given in the trace output, in particular the line number and the file name.  However with the introduction in Bash 3.0 of the introspection variables, also needed to support the debugger, one can set $PS4 to rectify this. (I became of this in a defunct blog http://raz.cx/blog/2005/08/handy-bash-debugging-trick.html.)

Here's what I use:

       PS4='(${BASH_SOURCE}:${LINENO}): ${FUNCNAME[0]} - [${SHLVL},${BASH_SUBSHELL}, $?]
     '

Note that the string is in single quotes, not double quotes and there is a newline in the string. By using single quotes, variables which have a dollar in front of them in the string are expanded in the current environment of the line that is about to be run rather than at the time the variable PS4 is set.

You might want to add this in your shell's start-up script, e.g., .bashrc, or .profile.

There is also facility inside the bash debugger showing position information when tracing a script. Here's a simple session.

     /usr/local/bin/bashdb /tmp/fact.sh
     Bourne-Again Shell Debugger, release bash-VERSION
     Copyright 2002, 2003, 2004, 2006, 2007, 2008 Rocky Bernstein
     This is free software, covered by the GNU General Public License, and you are
     welcome to change it and/or distribute copies of it under certain conditions.

     (/tmp/fact.sh:11):
     11:	echo fact 0 is: `fact 0`
     bashdb<0> set linetrace on
     bashdb<1> cont
     (/tmp/fact.sh:11):
     level 1, subshell 1, depth 0:	echo fact 0 is: `fact 0`
     fact 0
     (/tmp/fact.sh:2):
     level 1, subshell 1, depth 1:	fact() {
     (/tmp/fact.sh:3):
     level 1, subshell 1, depth 1:	    local -i n=${1:0}
     (/tmp/fact.sh:4):
     level 1, subshell 1, depth 1:	    ((n==0)) && echo 1 && return
     (/tmp/fact.sh:4):
     level 1, subshell 1, depth 1:	    ((n==0)) && echo 1 && return
     echo 1
     (/tmp/fact.sh:4):
     level 1, subshell 1, depth 1:	    ((n==0)) && echo 1 && return
     return
     fact 0 is: 1
     (/tmp/fact.sh:13):
     level 1, subshell 0, depth 0:	echo fact 3 is: $(fact 3)
     (/tmp/fact.sh:13):
     level 1, subshell 1, depth 0:	echo fact 3 is: $(fact 3)
     fact 3
     (/tmp/fact.sh:2):
     level 1, subshell 1, depth 1:	fact() {
     (/tmp/fact.sh:3):
     level 1, subshell 1, depth 1:	    local -i n=${1:0}
     (/tmp/fact.sh:4):
     level 1, subshell 1, depth 1:	    ((n==0)) && echo 1 && return
     (/tmp/fact.sh:5):
     level 1, subshell 1, depth 1:	    ((nm1=n-1))
     (/tmp/fact.sh:6):
     level 1, subshell 1, depth 1:	    ((fact_nm1=`fact $nm1`))
     (/tmp/fact.sh:6):
     level 1, subshell 2, depth 1:	    ((fact_nm1=`fact $nm1`))
     fact $nm1
     (/tmp/fact.sh:2):
     level 1, subshell 2, depth 2:	fact() {
     ...
     level 1, subshell 4, depth 4:	fact() {
     (/tmp/fact.sh:3):
     level 1, subshell 4, depth 4:	    local -i n=${1:}
     (/tmp/fact.sh:4):
     level 1, subshell 4, depth 4:	    ((n==0)) && echo 1 && return
     (/tmp/fact.sh:4):
     level 1, subshell 4, depth 4:	    ((n==0)) && echo 1 && return
     echo 1
     (/tmp/fact.sh:4):
     level 1, subshell 4, depth 4:	    ((n==0)) && echo 1 && return
     return
     (/tmp/fact.sh:7):
     level 1, subshell 3, depth 3:	    ((result=n*fact_nm1))
     (/tmp/fact.sh:8):
     level 1, subshell 3, depth 3:	    echo $result
     (/tmp/fact.sh:7):
     level 1, subshell 2, depth 2:	    ((result=n*fact_nm1))
     (/tmp/fact.sh:8):
     level 1, subshell 2, depth 2:	    echo $result
     (/tmp/fact.sh:7):
     level 1, subshell 1, depth 1:	    ((result=n*fact_nm1))
     (/tmp/fact.sh:8):
     level 1, subshell 1, depth 1:	    echo $result
     fact 3 is: 6
     (/usr/local/bin/bashdb:260):
     level 1, subshell 0, depth -1:
     Debugged program terminated normally. Use q to quit or R to restart.
     bashdb<2>

An explanation of the output. The level is how many invocations of BASH are in effect before the statement shown is executed. The subshell is how many subshells you are nested in. Subshells are used by command substitution---`..' and $(...)---as well as arithmetic expressions ((...)). The depth is the function depth or how many calls you are nested in. A ``source'' command also increases this depth.

Notice also that in contrast to set -x tracing, the line shown is exactly as you entered it in the source. So if you indented statements in a meaningful way, it will help you understand the statement nesting level. But as before, if a line contains multiple statements, you are not executing the first statement in the line and set showcommand is not turned off (by default it is on), that statement is shown in addition below the multi-statement line. Such an example can be seen right at the beginning where fact 0 is shown.

If what you want to do is trace the entire script as was done above (and not stop in the debugger when the script is over), you can get the same effect by using the -X or --trace option on the bashdb command:

     /usr/local/bin/bashdb -X /tmp/fact.sh
     Bourne-Again Shell Debugger, release bash-VERSION
     Copyright 2002, 2003, 2004, 2006, 2007, 2008, 2009 Rocky Bernstein
     This is free software, covered by the GNU General Public License, and you are
     welcome to change it and/or distribute copies of it under certain conditions.

     (/usr/local/bin/bashdb:272):
     level 1, subshell 0, depth -1:	  . $_source_file
     (/tmp/fact.sh:11):
     level 1, subshell 0, depth 0:	echo fact 0 is: `fact 0`
     (/tmp/fact.sh:11):
     level 1, subshell 1, depth 0:	echo fact 0 is: `fact 0`
     fact 0
     (/tmp/fact.sh:2):
     level 1, subshell 1, depth 1:	fact() {
     (/tmp/fact.sh:3):
     level 1, subshell 1, depth 1:	    local -i n=${1:0}
     ...
     level 1, subshell 2, depth 2:	    echo $result
     (/tmp/fact.sh:7):
     level 1, subshell 1, depth 1:	    ((result=n*fact_nm1))
     (/tmp/fact.sh:8):
     level 1, subshell 1, depth 1:	    echo $result
     fact 3 is: 6
     (/usr/local/bin/bashdb:285):
     level 1, subshell 0, depth -1:

If you issue a break (e.g. send a SIGINT signal) while the program is running you will go into the debugger (assuming your program doesn't trap SIGINT).

Getting in and out
******************

This chapter discusses how to start the BASH debugger, and how to get out of it. The essentials are:

  * type bash --debugger script-name or bashdb
     script-name to start the BASH debugger. Or...

  * type bashdb -c command string to give a string to run under the debugger. Or ..

  * modify your program to enter the debugger at a particular point: source ../bashdb-trace and _Dbg_debugger.

  * type quit or C-d inside the debugger to exit.

There are also two front-ends available as well. One can also enter the debugger inside emacs via the command M-x bashdb after loading Emacs' Grand Unified Debugger, gud. See Using the BASH debugger from GNU Emacs. And there is support in a DDD for bash.

Starting the BASH debugger
==========================

Note: it is important to use a debugger-enabled bash. You will get an error message if the debugger is run under a version of BASH that does not have debugging support.

As mentioned above, one can enter via Emacs or DDD. However you don't have to use either of these. And these still need a way on their own to get things started.

There are in fact two other ways to start the BASH debugger.  The first way is to pass the --debugger option to bash with the name of your script the scripts arguments following that, or with a command string (-c).

     bash --debugger SCRIPT SCRIPT-ARGUMENTS...
     bash --debugger -c COMMAND-STRING...

This calls a debugger initialization script. It works much like a BASH login profile which may set variables and define functions. But this shell profile is customized for debugging and as such arranges for itself to get called before each statement is executed. Although there are some problems at present in I/O redirection that the method described next doesn't have, it is expected that over time more features will be enabled in bash when the --debugger option is in effect. By default, both debugging in Emacs via GUD (Using the BASH debugger under Emacs) and debugging via DDD work via this method.

The form bash --debugger -c ... can be used to get into the debugger without having to give a script name to debug. Sometimes you may want to do this just to see how the debugger works: try some debugger commands or maybe get online help. If you run ddd --bash without giving a script name, it in fact uses this form.

In order for the --debugger option to work however, you must have the debugger scripts installed in a place where can find them. For this reason, in developing the BASH debugger, I use a second method more often; it doesn't require the bash debugger to be installed. This method uses another script called bashdb which allows for giving its own options, the final option is signaled by adding --). After this, the name of the script to debugged and any the arguments to pass to that script are given. Using this method, one would start the debugger like this:

     bash PATH-TO-BASHDB/bashdb BASHDB-OPTIONS -- SCRIPT SCRIPT-ARGUMENTS...

If you don't need to pass dash options to your program which might get confused with the debugger options, then you don't need to add the --. (And in the interest of full disclosure, although this was not shown in the example it is possible to add the -- after the script name to be debugged but before the first program option with a dash.)

As with the first method, bash should be a debugger-enabled bash. If bashdb has the path to bash in it at the top (e.g. via #!), and bashdb can be found in your program-search path, then this might be equivalent to the above:

     bashdb BASHDB-OPTIONS -- SCRIPT SCRIPT-ARGUMENTS...

There are two or three disadvantages however of running a debugger this way. First $0 will have the value bashdb rather than the script you are trying to run. For some scripts this may change the behavior of the debugged script. Second a traceback will contain additional lines showing the ``source''-ing of the debugged script from bashdb. And third, although this way works better than the first method, over time this way may come into disuse.

An option that you'll probably need to use if bashdb isn't installed but run out of the source code directory is -L which specifies the directory that contains the debugger script files.

You can further control how bashdb starts up by using command-line options. bashdb itself can remind you of the options available.

Type

     bashdb -h

to display all available options and briefly describe their use.

When the bash debugger is invoked either by the bashdb front-end script or bash --debugging, the first argument that does not have an associated option flag for bashdb or bash (as the case may be) is used as the name a the script file to be debugged, and any following options get passed the debugged script.

Options for the bashdb front-end are shown in the following list.

Command-line options for bashdb script
--------------------------------------

You can run in various alternative modes---for example, in batch mode or quiet mode.

-h | --help
     This option causes the BASH debugger to print some basic help and exit.

-V | --version
     This option causes to print its version number, no-warranty blurb, and exit.

-A | --annodate LEVEL
     Add additional output which allows front-ends to track what's going on without having to poll for such vital information. The default annotation level is 0 (none). If you are running inside GNU Emacs using the Emacs code from this package, an annotation level 3 when set will allow for automatic tracking of frames and breakpoints. See Annotate.

-c | --command CMD
     Run the string instead of running a script

-B | --basename
     This option causes to print its version number and no-warranty blurb, and exit.

-n | --nx | --no-init
     Do not execute commands found in any initialization files.  Normally, BASH executes the commands in these files after all the command options and arguments have been processed.  See Command files.

-q | --quiet
     ``Quiet''.  Do not print the introductory and copyright messages.  These messages are also suppressed in batch mode.

-t | --terminal | --tty TTY
     ``Terminal output''.  Set the file or terminal that you want debugger command output to go to. Note that the debugger output is independent of the debugged script output.

-x | --eval-command
     execute debugger commands from CMDFILE.

-L | --library DIRECTORY

     Set directory where debugger files reside to DIRECTORY. The default location is ../lib/bashdb relative to the place that the bashdb script is located. For example if bashdb is located in bindir/bashdb, the default library location will be libdir/bashdb which may or may not exist. If it doesn't you'll get an error when you run bashdb. Only if the default location is incorrect, should you need to use the -L option.

-T | --tempdir DIRECTORY
     Set directory to use for writing temporary files.

Quitting the BASH debugger
==========================

An interrupt (often C-c) does not exit from the BASH debugger, but rather terminates the action of any command that is in progress and returns to the BASH debugger command level.  Inside a debugger command interpreter, use quit command (see Quitting the BASH debugger).

There way to terminate the debugger is to use the kill command. This does more forceful kill -9. It can be used in cases where quit doesn't work.

Calling the BASH debugger from inside your program
==================================================

Running a program from the debugger adds a bit of overhead and slows down your program quite a bit. Addressing this better would mean some serious changes to BASH internals, and judging from experience in other languages there still the slowdown is still noticeable.  If you have a configure script generated by autoconf, and you want to stop in the middle of the script, it can take quite a while.

Furthermore, by necessity, debuggers change the operation of the program they are debugging. And this can lead to unexpected and unwanted differences. It has happened so often that the term ``Heisenbugs'' (see http://en.wikipedia.org/wiki/Heisenbug) was coined to describe the situation where the addition of the use of a debugger (among other possibilities) changes behavior of the program so that the bug doesn't manifest itself anymore.

There is another way to get into the debugger aside from calling bashdb from the outset, and this adds no overhead or slowdown until you reach the point at which you want to start debugging. However for this method you must change the script. Because the debugger isn't involved before the first call, there is no overhead; the script will run at the same speed as if there were no debugger up to the point where it is first invoked.

Debugging a Running Shell Script
--------------------------------

In this section we'll show how to modify your script so that it enters the debugger when you send it a signal, and then we will show how you can call the debugger directly.

In either case, you'll need to modify the script to load some the debugger code.  The name of file to load is bashdb-trace and it is located in the directory where the other bash debugger files live. For example on GNU/Linux if it is in directory /usr/local/share/bashdb, you would first add to a BASH script the line:

         source /usr/local/share/bashdb/bashdb-trace

Although I said that running under the debugger adds overhead which slows down you program, the above command in of itself will not cause any slowdown. If possible, it's best to put this somewhere in the main-line code rather than in a function or in a subshell. If it is put in a function of subshell and you step outside of that, some of the global variables set up in bashdb-trace may be lost. One the other hand if you know your debugging will be confined to just the scope of the source command there is no problem.

Here's a complete example. In file debugit.sh

     # This is my extra debug hook
       source /usr/share/bashdb/bashdb-trace # adjust location

       echo $$
       while : ; do
             date=$(date)
             echo "$date"
             sleep 2
       done

Now run:

       $ bash ./debugit.sh
       Bourne-Again Shell Debugger, release bash-3.1-0.08
       Copyright 2002, 2003, 2004, 2006 Rocky Bernstein
       This is free software, covered by the GNU General Public License, and you are
       welcome to change it and/or distribute copies of it under certain conditions.

       9435
       Thu Jun 19 02:43:06 EDT 2008
       Thu Jun 19 02:43:08 EDT 2008

Sent it an "interrupt" signal

       kill -INT 9435

And back to the running program:

       Program received signal SIGINT (2)...
       ->0 in file `./debugit.sh' at line 251  # not sure where 251 came from!
       ##1 main() called from file `./debugit.sh' at line 0
       bashdb<0> where
       ->0 in file `./debugit.sh' at line 9    # but this line number is now right
       ##1 main() called from file `./debugit.sh' at line 0
       bashdb<1> list 1
         1:   # Set up some interrupt handlers to go into the debugger
         2:   source /usr/share/bashdb/bashdb-trace
         3:
         4:   echo $$
         5:   while : ; do
         6:   date=$(date)
         7:   echo "$date"
         8:   sleep 2
         9:==>done
       bashdb<2> step
       (./debugit.sh:5):
       5:      while : ; do
       bashdb<3> step
       (./debugit.sh:6):
       6:      date=$(date)
       bashdb<4> continue -

The command continue - not only continues execution but it removes the debug trap allowing the program to run at full speed. It is suitable only if there are no breakpoints that you care to stop at.

By default, bashdb-trace sets up a handler for the INT exception. If you down't want this or you want enter the debugger on a different signal to be use, _Dbg_handler. With this function you can specify whether to show a call stack, stop (enter the debugger) and/or print an indication that the a signal was seen.

Here are some examples:

         _Dbg_handler INT print showstack nostop  # this is the default
         _Dbg_handler INT                         # same thing
         _Dbg_hander                              # same thing
         _Dbg_handler HUP print stop              # stop in debugger when getting

Explicit Debugging Calls.
.........................

As we saw in the last section bashdb-trace installs some signal handlers. However you can make an explicit call to the debugger

          _Dbg_debugger

Let's show an example of that. We'll even do it under a condition:

       for ((i=1; i<=10; i++)) ;
             (( 5 == i )) && { _Dbg_debugger }
             date=$(date)
             echo "$date"
             sleep 2
       done

The debugger will be called on the 5th iteration of this loop, when i has the value 5.

You can also supply the number of statements to skip and the options to _Dbg_debugger just as you would to the debugger itself. All of the options listed in Options for the bashdb script can be used with the exception of -c (run a command) and of course you don't supply the name of a BASH script.

For example to stop at the next line and suppress the banner you could use _Dbg_debugger 1 -q in the above example.

Program-Controlled Line Tracing
-------------------------------

You can also turn on and off line tracing. Here's an example

       source path-to-program/bashdb-trace # modify location
        ...
       _Dbg_linetrace_on
       for i in `seq 10` ; do
          echo $i
       done
       _Dbg_linetrace_off
        _Dbg_QUIT_ON_QUIT=1

The _Dbg_QUIT_ON_QUIT  variable make sure the program doesn't stay inside the debugger after it quits. It can also be set earlier in the program.

Again <path-to-program> is whatever path needed to located <bashdb-trace>. For example it might be </usr/local/share> on some GNU/Linux installations.

Script Setup inside the BASH Debugger
*************************************

Starting your script
====================

After invoking the debugger you should be on the first stoppable line of your program to be debugged. At this point you can issue debugger commands to set breakpoints (see Setting breakpoints), or watchpoints (see Setting watchpoints), or start continue the execution of the program (see Resuming Execution).

restart args
run args
R args
     Use the restart command to restart your script under the BASH debugger. Without any arguments, the script name and parameters from the last invocation are used. The BASH debugger tries to maintain the settings, watchpoints, breakpoints, actions and so on. Internally it uses line numbers and filenames to record he position of interesting places in your porgram; so if your program changes some or all of these numbers may be off. Environment variable DBG_RESTART_FILE is and a temporary file are used to signal a restart, so you shouldn't uset DBG_RESTART_FILE (or any environment variable starting with BASHDB_.

Command files
=============

A command file for is a file of lines that are commands.  Comments (lines starting with #) may also be included. An empty line in a command file does nothing; it does not mean to repeat the last command, as it would from the terminal.

When you start the BASH debugger, it automatically executes commands from its init files, normally called .bashdbinit (The DJGPP port of uses the name bashdb.ini instead, due to the limitations of file names imposed by DOS filesystems.). During startup, does the following:

 1. Reads the init file (if any) in your home directory (On DOS/Windows systems, the home directory is the one pointed to by the HOME environment variable.).

 2. Processes command line options and operands.

 3. Reads the init file (if any) in the current working directory.

 4. Reads command files specified by the -x option.

The init file in your home directory can set options (such as set complaints) that affect subsequent processing of command line options and operands.  Init files are not executed if you use the -x option (see bashdb script options).

On some configurations of the BASH debugger, the init file is known by a different name (these are typically environments where a specialized form of may need to coexist with other forms, hence a different name for the specialized version's init file).  These are the environments with special init file names:

You can also request the execution of a command file with the source command:

source FILENAME
     Execute the command file FILENAME.

The lines in a command file are executed sequentially.  They are not printed as they are executed.  If there is an error, execution proceeds to the next command in the file.

Your script's arguments
=======================

The arguments to your script can be specified by the arguments of the restart command. They are passed to a shell, which expands wildcard characters and performs redirection of I/O, and thence to your script.

restart with no arguments uses the same arguments used by the previous restart, or those set by the set args command..

set args
     Specify the arguments to be used if your program is rerun. If set args has no arguments, restart executes your program with no arguments.  Once you have run your program with arguments, using set args before the next restart is the only way to run it again without arguments.

show args
     Show the arguments to give your program when it is started.

Your script's input and output
==============================

By default, the script you run under the BASH debugger does input and output to the same terminal that BASH uses. Before running the script to be debugged, the debugger records the tty that was in effect. All of its output is then written to that. However you can change this when using the bashdb script using the -t option.

info terminal
     Displays information recorded by about the terminal modes your program is using.

Another way to specify where your script should do input and output is with the tty command.  This command accepts a file name as argument, and causes this file to be the default for future restart commands.  It also resets the controlling terminal for the child process, for future restart commands.  For example,

     tty /dev/ttyb

directs that processes started with subsequent restart commands default to do input and output on the terminal /dev/ttyb and have that as their controlling terminal.

An explicit redirection in restart overrides the tty command's effect on the input/output device, but not its effect on the controlling terminal.

When you use the tty command or redirect input in the restart command, only the input for your script is affected.  The input for still comes from your terminal.

Script/Debugger Interaction
===========================

The BASH debugger and your program live in the same variable space so to speak. BASH does not have a notion of module scoping or lexical hiding (yet) as is found in modern programming langauges and in modern versions of the Korn shell. This then imposes some additional care and awareness.

Most of the variables and functions used inside start _Dbg_, so please don't use variables or functions with these names in your program.

Note: there are some other variables that begin with just an underscore (_); over time these will be phased out. But until then, avoid those or consult what is used by the debugger. Run bashdb --debugger -c "declare -p" to list all the variables in use including those used by the debugger.

A number of environment variables are also reserved for use; these start with DBG_. For example: DBG_INPUT, DBG_LEVEL and, _Dbg_QUIT_ON_QUIT (see Debug), DBG_RESTART_FILE (see Starting), to name a few.  Finally, there are some BASH environment dynamic variables and these start with BASH_. For example BASH_SUBSHELL (see Debug), BASH_COMMAND (see Command Display), BASH_LINENO, and BASH_SOURCE to name a few.

Inside the debugger some variables may be redefined. In particular IFS and PS4, and various dollar variables $?, $1, $2, etc. The values before entering the debugger are saved and those variables have their old values restroed when leaving the debugger. However you may notice these difference in various debugger commands. For example examine PS4 might not return the same value as eval declare -p PS4. The former is picking the debugger value while the eval is careful to restore the value to what it was before entering the debugger.

In order to do its work The BASH debugger sets up a DEBUG trap. Consequently a script shouldn't reset this or the debugger will lose control. The BASH debugger also sets up an EXIT handler so that it can gain control after the script finishes. Another signal intercepted is the an interrupt or INT signal. For more information about signal handling, see Signals

BASH Debugger Command Reference
*******************************

You can abbreviate the long name of command to the first few letters of the command name, if that abbreviation is unambiguous; and you can repeat the next or step commands by typing just RET. Some commands which require a parameter, such as print remember the argument that was given to them.

Command syntax
==============

A BASH debugger command is a single line of input.  There is no limit on how long it can be.  It starts with a command name, which is followed by arguments whose meaning depends on the command name. For example, the command step accepts an argument which is the number of times to step, as in step 5.  You can also use the step command with no arguments.  Some commands do not allow any arguments.

A blank line as input to (typing just RET) means to repeat the previous next or step command.

Any text from a # to the end of the line is a comment; it does nothing.  This is useful mainly in command files (see Command files).

Getting help (help)
===================

Once inside the BASH debugger, you can always ask it for information on its commands, using the command help.

help
h
     You can use help (abbreviated h) with no arguments to display a short list of named classes of commands:

     bashdb<0> help
     Available commands:
       action     debug    eval     help     print    set     step-      untrace
       alias      delete   examine  history  pwd      shell   step+      up
       backtrace  disable  export   info     quit     show    tbreak     watch
       break      display  file     kill     restart  signal  trace      watche
       commands   down     finish   list     return   skip    tty
       condition  edit     frame    load     reverse  source  unalias
       continue   enable   handle   next     search   step    undisplay

     Readline command line editing (emacs/vi mode) is available.
     Type "help" followed by command name for full documentation.

help COMMAND
     With a command name as help argument, the BASH debugger displays short information on how to use that command.

          bashdb<0> help list
          list [START|.|FN] [COUNT] -- List lines of a script.

          START is the starting line or dot (.) for current line. Subsequent
          list commands continue from the last line listed. If a function name
          is given list the text of the function.

          If COUNT is omitted, use the setting LISTSIZE. Use "set listsize" to
          change this setting.

          Aliases for list: l

     In addition to help, you can use the debugger command info to inquire about the state of your script, or the state of
     itself.  The listings under info in the Index
     point to all the sub-commands.  See Command Index.

info
     This command (abbreviated i) is for describing the state of your program.  For example, you can list the arguments given to your script with info args, or list the breakpoints you have set with info breakpoints.  You can get a complete list of the info sub-commands with help info.

          bashdb<0> help info
          List of info subcommands:

          info args -- Argument variables (e.g. $1, $2, ...) of the current stack frame.
          info breakpoints -- Status of user-settable breakpoints
          info display -- Show all display expressions
          info files -- Source files in the program
          info functions -- All function names
          info line -- list current line number and and file name
          info program -- Execution status of the program.
          info signals -- What debugger does when program gets various signals
          info source -- Information about the current source file
          info stack -- Backtrace of the stack
          info terminal -- Print terminal device
          info variables -- All global and static variable names
          info warranty -- Various kinds of warranty you do not have

          Aliases for info: i
          bashdb<1> info source
          Current script file is parm.sh
          Located in /tmp/parm.sh
          Contains 34 lines.

Quitting the BASH debugger (quit, kill)
=======================================

quit expression

quit [EXPRESSION subshell-levels]
q

     To exit the BASH debugger, use the quit command (abbreviated q), or type an end-of-file character (usually C-d).  If you do not supply EXPRESSION, will try to terminate normally or with exit code 0. Otherwise it will terminate using the result of EXPRESSION as the exit code.

     A simple quit tries to terminate all nested subshells that may be in effect.  If you are nested a subshell, this is normally indicated in a debugger prompt by the number of parentheses that the history number is inside --- no parenthesis means there is no subshell in effect. The dynamic variable BASH_SUBSHELL also contains the number of subshells in effect.

     If you want only to terminate some number of subshells but not all of them, you can give a count of the number of subshells to leave after the return-code expression. To leave just one level of subshell return does almost the same thing. (See Returning) There is a subtle difference between the two though: return will leave you at the beginning of the next statement while quit may leave you at the place the subshell was invoked which may be in the middle of another command such as an assingment statement or condition test.

     If the environment variable _Dbg_QUIT_ON_QUIT is set, when the program terminates, the debugger will also terminate too. This may be useful if you are debugging a script which calls another script and you want this inner script just to return to the outer script.

kill
k
     In situations where quit doesn't work we provide an alternative and more forceful quit command: kill. This sends to the OS non-maskable KILL signal with the debugger process number. No cleanup of temporary files is done by the program.

Stopping and Resuming Execution
===============================

One important use of a debugger is to stop your program before it terminates so that if your script might run into trouble, you can investigate and find out why. However should your script accidently continue to termination, has arranged for it not to leave the debugger without your explicit instruction. That way, you can restart the program using the same command arguments.

Inside the BASH debugger, your script may stop for any of several reasons, such as a signal, a breakpoint, or reaching a new line after a debugger command such as step.  You may then examine and change variables, set new breakpoints or remove old ones, and then continue execution.

Breakpoints, watchpoints (break, tbreak, watch, watche...)
----------------------------------------------------------

A breakpoint makes your script stop whenever a certain point in the program is reached.  For each breakpoint, you can add conditions to control in finer detail whether your script stops.

You specify the place where your script should stop with the break command and its variants (see Setting breakpoints). These commands allow own to specify the location by line number and file name or function name.

A watchpoint is a special breakpoint that stops your script when the value of an expression changes.  There is a different command to set watchpoints (see Setting watchpoints).

But aside from that, you can manage a watchpoint like any other breakpoint: you delete enable, and disable both breakpoints and watchpoints using the same commands.

You can arrange to have values from your program displayed automatically whenever BASH stops at a breakpoint.  See Automatic display.

The BASH debugger assigns a number to each breakpoint when you create it; these numbers are successive integers starting with one.  In many of the commands for controlling various features of breakpoints you use the breakpoint number to say which breakpoint you want to change. Each breakpoint may be enabled or disabled; if disabled, it has no effect on your script until you enable it again.

Watchpoint numbers however are distinguished from breakpoint numbers by virtue of their being suffixed with the either an upper- or lower-case `W'.  For example, to enable breakpoint entry 0 along with watchpoint entry 1 you would write enable 1 2w, the ``2w'' refers to the watchpoint; ``2W'' would work just as well.

Setting breakpoints (break tbreak)
..................................

Breakpoints are set with the break command (abbreviated b).

break FUNCTION
     Set a breakpoint at entry to function FUNCTION.

break LINENUM
     Set a breakpoint at line LINENUM in the current source file. The current source file is the last file whose source text was printed. The breakpoint will stop your script just before it executes any of the code on that line.

break FILENAME:LINENUM
     Set a breakpoint at line LINENUM in source file FILENAME; FILENAME has to be one of the files previously read in and has to be specified exactly as the name used when read in. For a list of read-in files, use the info files command.

break ... if COND
     Set a breakpoint with condition COND; evaluate the expression COND each time the breakpoint is reached, and stop only if the value is nonzero---that is, if COND evaluates as true. The expression is evaluated via the let builtin funtion. ... stands for one of the possible arguments described above (or no argument) specifying where to break. The word ``if'' is often optional and is necessary only ... is omitted. See Break conditions, for more information on breakpoint conditions.

     Examples:

          bashdb<0> break fn1
          Breakpoint 1 set in file parm.sh, line 3.
          bashdb<1> break 28
          Breakpoint 2 set in file parm.sh, line 28.
          bashdb<2> break parm.sh:29
          Breakpoint 3 set in file parm.sh, line 29.
          bashdb<3> break 28 if x==5
          Breakpoint 4 set in file parm.sh, line 28.

tbreak ARGS
     Set a breakpoint enabled only for one stop.  ARGS are the same as for the break command, and the breakpoint is set in the same way, but the breakpoint is automatically deleted after the first time your program stops there.  See Disabling breakpoints.

info breakpoints n
info break n
info watchpoints n
     Print a table of all breakpoints, watchpoints set and not deleted, with the following columns for each breakpoint:

     Breakpoint Numbers (Num)

     Enabled or Disabled (Enb)
          Enabled breakpoints are marked with 1.  0 marks breakpoints that are disabled (not enabled).

     Count
          The number of times that breakpoint or watchpoint has been hit.

     File and Line (file:line)
          The filename and line number inside that file where of breakpoint in the script. The file and line are separated with a colon.

     Condition
          A condition (an arithmetic expression) which when true causes the breakpoint to take effect.

     If a breakpoint is conditional, info break shows the condition on the line following the affected breakpoint; breakpoint commands, if any, are listed after that.

     info break displays a count of the number of times the breakpoint has been hit.

     info break with a breakpoint number N as argument lists only that breakpoint.

     Examples:

          bashdb<4> info break
          Breakpoints at following places:
          Num Type       Disp Enb What
          1   breakpoint keep y   parm.sh:3
          2   breakpoint keep y   parm.sh:28
          3   breakpoint keep y   parm.sh:29
          4   breakpoint keep y   parm.sh:28
          No watch expressions have been set.
          bashdb<5> info break 4
          Num Type       Disp Enb What
          4   breakpoint keep y   parm.sh:28
          No watch expressions have been set.

allows you to set any number of breakpoints at the same place in
your script.  There is nothing silly or meaningless about this.  When the breakpoints are conditional, this is even useful (see Break conditions).

Setting watchpoints (watch, watche)
...................................

You can use a watchpoint to stop execution whenever the value of an expression changes, without having to predict a particular place where this may happen. As with the print (see Examining Data), the idiosyncracies of a BASH or any POSIX shell derivative suggest using two commands. The watch command is just for a single variables; the watche command uses the builtin ``let'' command to evaluate an expression. If the variable you are tracking can take a string value, issuing something like watch foo will not have the desired effect---any string assignment to foo will have a value 0 when it is assigned via ``let.''

watch VAR
     Set a watchpoint for a variable. will break when the value of VAR changes. In this command do not add a leading dollar symbol to VAR.

watche EXPR
     Set a watchpoint for an expression via the builtin ``let'' command.
     will break when EXPR is written into by the program
     and its value changes. Not that this may not work for tracking arbitrary string value changes. For that use watch described earlier.

Breakpoint command lists (commands)
...................................

commands [BNUM]
... COMMAND-LIST ...
end
     Specify a list of commands for breakpoint number BNUM.  The commands themselves appear on the following lines.  Type a line containing just end to terminate the commands.

     To remove all commands from a breakpoint, type commands and follow it immediately with end; that is, give no commands.

     With no BNUM argument, commands refers to the last breakpoint, watchpoint, or catchpoint set (not to the breakpoint most recently encountered).

Pressing RET as a means of repeating the last debugger command is disabled within a COMMAND-LIST.

You can use breakpoint commands to start your program up again.  Simply use the continue command, or step, or any other command that resumes execution.

Any other commands in the command list, after a command that resumes execution, are ignored.  This is because any time you resume execution (even with a simple next or step), you may encounter another breakpoint---which could have its own command list, leading to ambiguities about which list to execute.

If the first command you specify in a command list is silent, the usual message about stopping at a breakpoint is not printed.  This may be desirable for breakpoints that are to print a specific message and then continue.  If none of the remaining commands print anything, you see no sign that the breakpoint was reached.  silent is meaningful only at the beginning of a breakpoint command list.

The commands echo, output, and printf allow you to print precisely controlled output, and are often useful in silent breakpoints.

For example, here is how you could use breakpoint commands to print the value of x at entry to foo whenever x is positive.

     break foo if x>0
     commands
     silent
     printf "x is %d\n",x
     cont
     end

One application for breakpoint commands is to compensate for one bug so you can test for another.  Put a breakpoint just after the erroneous line of code, give it a condition to detect the case in which something erroneous has been done, and give it commands to assign correct values to any variables that need them.  End with the continue command so that your program does not stop, and start with the silent command so that no output is produced.  Here is an example:

     break 403
     commands
     silent
     set x = y + 4
     cont
     end

Deleting breakpoints (clear, delete)
....................................

It may desirable to eliminate a breakpoint or watchpoint once it has done its job and you no longer want your script to stop there. This is called deleting the breakpoint.  A breakpoint that has been deleted no longer exists; it is forgotten.

With the clear command you can delete breakpoints according to where they are in your script.  With the delete command you can delete individual breakpoints, or watchpoints by specifying their breakpoint numbers. Note: as described below under the ``clear'' command, ``d'' is an alias for ``clear'', not ``delete''.

It is not necessary to delete a breakpoint to proceed past it. automatically ignores breakpoints on the first instruction to be executed when you continue execution.

clear
     Delete any breakpoints at the next instruction to be executed in the selected stack frame (see Selecting a frame).  When the innermost frame is selected, this is a good way to delete a breakpoint where your script just stopped.

     It may seem odd that we have an alias ``d'' for ``clear.'' It so happens that Perl's debugger use ``d'' for its delete command and the delete concept in Perl's debugger corresponds to ``clear'' in GDB. (Perl doesn't have a notion of breakpoint entry numbers). So in order to be compatible with both debugger interfaces, ``d'' is used as an alias for ``clear.'' Clear?

clear FUNCTION
clear FILENAME:FUNCTION
     Delete any breakpoints set at entry to the function FUNCTION.

clear LINENUM
d LINENUM
     Delete any breakpoints set at or within the code of the specified line.

delete breakpoints
     Delete the breakpoints, watchpoints specified as arguments.

     If no argument is specified, delete all breakpoints (asks confirmation, unless you have set confirm off).  You can abbreviate this command as de.

     Note that for compatibility with Perl's debugger, d means something else: clear.

Disabling breakpoints (disable, enable)
.......................................

Rather than deleting a breakpoint or watchpoint, you might prefer to disable it.  This makes the breakpoint inoperative as if it had been deleted, but remembers the information on the breakpoint so that you can enable it again later.

You disable and enable breakpoints, watchpoints, and catchpoints with the enable and disable commands, optionally specifying one or more breakpoint numbers as arguments.  Use info break or info watch to print a list of breakpoints, watchpoints, and catchpoints if you do not know which numbers to use.

A breakpoint, watchpoint, or catchpoint can have any of four different states of enablement:

  * Enabled.  The breakpoint stops your program.  A breakpoint set with the break command starts out in this state.

  * Disabled.  The breakpoint has no effect on your program.

  * Enabled once.  The breakpoint stops your program, but then becomes disabled.

  * Enabled for deletion.  The breakpoint stops your program, but immediately after it does so it is deleted permanently.  A breakpoint set with the tbreak command starts out in this state.

You can use the following commands to enable or disable breakpoints, watchpoints, and catchpoints:

disable breakpoints
     Disable the specified breakpoints---or all breakpoints, if none are listed.  A disabled breakpoint has no effect but is not forgotten.  All options such as ignore-counts, conditions and commands are remembered in case the breakpoint is enabled again later.  You may abbreviate disable as dis.

enable breakpoints
     Enable the specified breakpoints (or all defined breakpoints).  They become effective once again in stopping your program.

Except for a breakpoint set with tbreak (see Setting breakpoints), breakpoints that you set are initially enabled; subsequently, they become disabled or enabled only when you use one of the commands above.  (The command until can set and delete a breakpoint of its own, but it does not change the state of your other breakpoints; see Resuming Execution.)

Break conditions (condition)
............................

The simplest sort of breakpoint breaks every time your script reaches a specified place.  You can also specify a condition for a breakpoint.  A condition is just a BASH expression.

Break conditions can be specified when a breakpoint is set, by using if in the arguments to the break command.  See Setting breakpoints.  A breakpoint with a condition evaluates the expression each time your script reaches it, and your script stops only if the condition is true. They can also be changed at any time with the condition command.

There is also a notion of a ``one-time'' breakpoint which gets deleted as soon as it is hit, so that that breakpoint is executed once only.

Conditions are also accepted for watchpoints; you may not need them, since a watchpoint is inspecting the value of an expression anyhow---but it might be simpler, say, to just set a watchpoint on a variable name, and specify a condition that tests whether the new value is an interesting one.

condition BNUM EXPRESSION
     Specify EXPRESSION as the break condition for breakpoint BNUM.  After you set a condition, breakpoint BNUM stops your program only if the value of EXPRESSION is true (nonzero).

condition BNUM
     Remove the condition from breakpoint number BNUM.  It becomes an ordinary unconditional breakpoint.

BASH does not actually evaluate EXPRESSION at the time the condition command (or a command that sets a breakpoint with a condition, like break if ...) is given, however.

Examples;

     condition 1 x>5   # Stop on breakpoint 0 only if x>5 is true.
     condition 1       # Change that! Unconditinally stop on breakpoint 1.

Resuming Execution (step, next, finish, skip, continue, debug, return)
----------------------------------------------------------------------

A typical technique for using stepping is to set a breakpoint (see Breakpoints; watchpoints) at the beginning of the function or the section of your script where a problem is believed to lie, run your script until it stops at that breakpoint, and then step through the suspect area, examining the variables that are interesting, until you see the problem happen.

Continuing means resuming program execution until your script completes normally.  In contrast, stepping means executing just one more ``step'' of your script, where ``step'' may mean either one line of source code.  Either when continuing or when stepping, your script may stop even sooner, due to a breakpoint or a signal.

Step (step)
...........

step+|- count
     Continue running your script until control reaches a different source line, then stop it and return control to the BASH debugger.  An default alias alias for this is s.

     The step command only stops at the first instruction of a source line.  This prevents the multiple stops that could otherwise occur in switch statements, for loops, etc.  step continues to stop if a function that has debugging information is called within the line.  In other words, step steps inside any functions called within the line.

     Sometimes you want to step ensure that the next line is different from the one you currently are on. To do this, add the + suffix. And if you find you want to do this all of the time there is a setting force that will have this be the default behavior. On the other hand if you want to be explicit about not having this behavior even when force is in effect add the - suffix.

     With a count, continue running as in step, but do so COUNT times.  If a breakpoint is reached, or a signal not related to stepping occurs before COUNT steps, stepping stops right away.

Next (next)
...........

next count
     Continue to the next source line in the current (innermost) stack frame. This is similar to step, but function calls that appear within the line of code are executed without stopping.  Execution stops when control reaches a different line of code at the original stack level that was executing when you gave the next command.  This command is abbreviated n.

     An argument COUNT is a repeat count, as for step.

Finish (finish)
...............

finish
     Continue running until just after function returns.  Currently, the line shown on a return is the function header, unless the return builtin function is executed in which case it is the line number of the return function.

     Contrast this with the return command (see Returning from a function) and the quit (see Quitting the BASH debugger).

Skip (skip)
...........

skip count
     Skip execution of the next source line. This may be useful if you have an action that ``fixes'' existing code in the script. The debug command internally uses the skip command to skip over existing non-debugged invocation that was presumably just run.

Continue (continue)
...................

continue - | line-specification
c line-specification
     Resume program execution, at the address where your script last stopped; any breakpoints set at that address are bypassed.

     The optional argument LINE-SPECIFICATION allows you to specify a location (a line number, function, or filename linenumber combination) to set a one-time breakpoint which is deleted when that breakpoint is reached. Should the program stop before that breakpoint is reached, in a listing of the breakpoints you will see this entry with the condition 9999 which indicates a one-time breakpoint.

     If instead of a line specification you enter -, debugging will be turned of after continuing causing the program to run at full speed.

To resume execution at a different place, you can use return (see Returning from a function) to go back to the calling function or sourced script. If you are nested inside a subshell, quit with a value for the number of subshells to exit also functions like a return.

Debug (debug)
.............

debug script-name
     Debug into SCRIPT-NAME. If no name is given the current source line is used. In either case the options are prepended to cause the debugger to run.

     The nesting level of the debugger is saved inside environment variable _Dbg_DEBUGGER_LEVEL. The debugger prompt indicates the level of nesting by enclosing the history in that many nestings of <> symbols.

Returning from a function, sourced file, or subshell (return)
.............................................................

return
     You can cancel execution of a function call or a subshell with the return command.

The return command does not resume execution; it leaves the program stopped in the state that would exist if the function had just returned.  See also the quit command (Quitting the BASH debugger). In some situations return is similar to quit: in particular when the script is not currenlty inside in a function and the number of subshells in effect is 0, or when a subshell count of 1 is given on the quit command.

In contrast, the finish command (see Finish) resumes execution until the selected stack frame returns naturally.

Signals (handle, info handle, signal)
-------------------------------------

A signal is an asynchronous event that can happen in a program.  The operating system defines the possible kinds of signals, and gives each kind a name and a number.  For example, in Unix SIGINT is the signal a program gets when you type an interrupt character (often C-c); SIGALRM occurs when the alarm clock timer goes off (which happens only if your program has requested an alarm).

Some signal handlers are installed and changed for the BASH debugger's normal use: SIGDEBUG and SIGEXIT. SIGDEBUG is used by the debugger to potentially stop your program before execution of each statement occurs, and SIGEXIT is used to catch your program just before it is set to leave so you have the option of restarting the program with the same options (and not leave the debugger) or let the program quit.

Signal handlers that the debugged script might have installed are saved and called before the corresponding debugger handler. Thus, the debugged program should work roughly in the same fashion as when it is not debugged. However there are some call-stack variables which inevitably will differ. To try to hedge this a little so the behaviour is the same, the BASH debugger will modify arguments to the traps if it finds one of the call-stack that change as a result of the debugger being in place. In particluar $LINENO will get replaced with ${BASH_LINENO[0]}; also ${BASH_LINENO[0]} and ${BASH_SOURCE[0]} get replaced with ${BASH_LINENO[1]} and ${BASH_SOURCE[1]} respectively.

The debugger also installs an interrupt handler SIGINT so that errant programs can be interrupted and you can find out where the program was when you interrupted it.

Some signals, including SIGALRM, are a normal part of the functioning of your program.  Others, such as SIGSEGV, indicate errors; these signals are fatal (they kill your program immediately) if the program has not specified in advance some other way to handle the signal. SIGINT does not indicate an error in your program, but it is normally fatal so it can carry out the purpose of the interrupt: to kill the program.

BASH has the ability to detect any occurrence of a signal in your program.  You can tell BASH in advance what to do for each kind of signal.

Normally, BASH is set up to let the non-erroneous signals like SIGALRM be silently passed to your program (so as not to interfere with their role in the program's functioning) but to stop your program immediately whenever an error signal happens. You can change these settings with the handle command.

Intercepting Signals (handle, info handle)
..........................................

handle SIGNAL KEYWORDS...
     Change the way BASH handles signal SIGNAL.  SIGNAL can be the number of a signal or its name (with or without the SIG at the beginning). The KEYWORDS say what change to make.

info signals
info handle
     Print a table of all the kinds of signals and how BASH has been told to handle each one.  You can use this to see the signal numbers of all the defined types of signals.

     info handle is an alias for info signals.

The keywords allowed by the handle command can be abbreviated. Their full names are:

stop
     BASH should stop your program when this signal happens.  This implies the print keyword as well.

nostop
     BASH should not stop your program when this signal happens.  It may still print a message telling you that the signal has come in.

print
     BASH should print a message when this signal happens.

noprint
     BASH should not mention the occurrence of the signal at all.

stack
     BASH should print a stack trace when this signal happens.

nostack
     BASH should not print a stack trace when this signal occurs.

Sending your program a signal (signal)
......................................

signal SIGNAL-NAME | SIGNAL-NUMBER
     You can use the signal command send a signal to your program. Supply either the signal name, e.g. SIGINT, or the signal number 15.

Examining the Stack Frame (where, frame, up, down)
==================================================

When your script has stopped, one thing you'll probably want to know is where it stopped and some idea of how it got there.

Each time your script performs a function call (either as part of a command substitution or not), or `source's a file, information about this action is saved.  The call stack then is this a history of the calls that got you to the point that you are currently stopped at.

One of the stack frames is selected by and many
commands refer implicitly to the selected frame.  In
particular, whenever you ask to list lines without giving a line number or location the value is found in the selected frame. There are special commands to select whichever frame you are interested in. See Selecting a frame.

When your program stops, BASH automatically selects the currently executing frame and describes it briefly, similar to the frame command.

Stack frames
------------

The call stack is divided up into contiguous pieces called stack frames, or frames for short; each frame is the data associated with one call to one function.  The frame contains the line number of the caller of the function, the source-file name that the line refers to a function name (which could be the built-in name ``source'')..

When your script is started, the stack has only one frame, that of the function main.  This is called the initial frame or the outermost frame.  Each time a function is called, a new frame is made.  Each time a function returns, the frame for that function invocation is eliminated.  If a function is recursive, there can be many frames for the same function.  The frame for the function in which execution is actually occurring is called the innermost frame.  This is the most recently created of all the stack frames that still exist.

the BASH debugger assigns numbers to all existing stack frames, starting with zero for the innermost frame, one for the frame that called it, and so on upward.  These numbers do not really exist in your script; they are assigned by the BASH debugger to give you a way of designating stack frames in the BASH debugger commands.

Backtraces (where)
------------------

A backtrace is essentially the same as the call stack: a summary of how your script got where it is.  It shows one line per frame, for many frames, starting with the place that you sare stopped at (frame zero), followed by its caller (frame one), and on up the stack.

backtrace
bt
where
T
     Print a backtrace of the entire stack: one line per frame for all frames in the stack.

backtrace N
bt N
where N
T N
     Similar, but print only the innermost N frames.

The names where and T are additional aliases for backtrace.

Each line in the backtrace shows the frame number and the function name, the source file name and line number, as well as the function name.

Here is an example of a backtrace taken a program in the regression-tests parm.sh.

     % ../bashdb -n -L .. parm.sh
     Bourne-Again Shell Debugger, release VERSION
     Copyright 2002, 2003, 2004, 2006, 2007, 2008, 2009 Rocky Bernstein
     This is free software, covered by the GNU General Public License, and you are
     welcome to change it and/or distribute copies of it under certain conditions.

     (./parm.sh:21):
     21:	fn1 5
     bashdb<0> continue fn3
     One-time breakpoint 1 set in file ./parm.sh, line 17.
     fn2: testing 1 2 3
     (./parm.sh:17):
     17:	fn3() {
     bashdb<1> where
     ->0 in file `./parm.sh' at line 14
     ##1 fn3() called from file `./parm.sh' at line 14
     ##2 fn2("testing 1", "2 3") called from file `parm.sh' at line 5
     ##3 fn1("0") called from file `parm.sh' at line 9
     ##4 fn1("1") called from file `parm.sh' at line 9
     ##5 fn1("2") called from file `parm.sh' at line 9
     ##6 fn1("3") called from file `parm.sh' at line 9
     ##7 fn1("4") called from file `parm.sh' at line 9
     ##8 fn1("5") called from file `parm.sh' at line 21
     ##9 source("parm.sh") called from file `bashdb' at line 143
     ##10 main("-n", "-L", "..", "parm.sh") called from file `bashdb' at line 0

The display for ``frame'' zero isn't a frame at all, although it has the same information minus a function name; it just indicates that your script has stopped at the code for line 14 of ./parm.sh.

Selecting a frame (up, down, frame)
-----------------------------------

Commands for listing source code in your script work on whichever stack frame is selected at the moment.  Here are the commands for selecting a stack frame; all of them finish by printing a brief description of the stack frame just selected.

up n
     Move N frames up the stack.  For positive numbers N, this advances toward the outermost frame, to higher frame numbers, to frames that have existed longer.  Using a negative N is the same as issuing a down command of the absolute value of the N. Using zero for N does no frame adjustment, but since the current position is redisplayed, it may trigger a resyncronization if there is a front end also watching over things.

     N defaults to one. You may appreviate up as u.

down n
     Move N frames down the stack.  For positive numbers N, this advances toward the innermost frame, to lower frame numbers, to frames that were created more recently.  Using a negative N is the same as issuing a up command of the absolute value of the N. Using zero for N does no frame adjustment, but since the current position is redisplayed, it may trigger a resyncronization if there is a front end also watching over things.

     N defaults to one.  You may abbreviate down as do.

All of these commands end by printing two lines of output describing the frame.  The first line shows the frame number, the function name, the arguments, and the source file and line number of execution in that frame.  The second line shows the text of that source line.

For example:

     bashdb<8> up
     19:	sourced_fn
     bashdb<8> T
     ##0 in file `./bashtest-sourced' at line 8
     ->1 sourced_fn() called from file `bashtest-sourced' at line 19
     ##2 source() called from file `bashdb-test1' at line 23
     ##3 fn2() called from file `bashdb-test1' at line 33
     ##4 fn1() called from file `bashdb-test1' at line 42
     ##5 main() called from file `bashdb-test1' at line 0

After such a printout, the list command with no arguments prints ten lines centered on the point of execution in the frame. See Printing source lines.

frame ARGS
     The frame command allows you to move from one stack frame to another, and to print the stack frame you select.  ARGS is the the stack frame number;  frame 0 then will always show the current and most recent stack frame.

     If a negative number is given, counting is from the other end of the stack frame, so frame -1 shows the least-recent, outermost or most ``main'' stack frame.

     Without an argument, frame prints the current stack frame. Since the current position is redisplayed, it may trigger a resyncronization if there is a front end also watching over things.

Examining Source Files (list)
=============================

the BASH debugger can print parts of your script's source.  When your script stops, the BASH debugger spontaneously prints the line where it stopped.  Likewise, when you select a stack frame (see Selecting a frame), the BASH debugger prints the line where execution in that frame has stopped.  You can print other portions of source files by explicit command.

If you use the BASH debugger through its GNU Emacs interface, you may prefer to use Emacs facilities to view source; see Using the BASH debugger under GNU Emacs.

To print lines from a source file, use the list command (abbreviated l).  By default, ten lines are printed. There are several ways to specify what part of the file you want to print.

Here are the forms of the list command most commonly used:

list LINENUM
l LINENUM
     Print lines centered around line number LINENUM in the current source file.

list FUNCTION
l FUNCTION
     Print the text of FUNCTION.

list
l
     Print more lines.  If the last lines printed were printed with a list command, this prints lines following the last lines printed; however, if the last line printed was a solitary line printed as part of displaying a stack frame (see Examining the Stack), this prints lines centered around that line.

list -
l -
     Print lines just before the lines last printed.

By default, the BASH debugger prints ten source lines with any of these forms of the list command. You can change this using set listsize:

set listsize COUNT
     Make the list command display COUNT source lines (unless the list argument explicitly specifies some other number).

show listsize
     Display the number of lines that list prints.

Repeating a list command with RET discards the argument, so it is equivalent to typing just list.  This is more useful than listing the same lines again.  An exception is made for an argument of -; that argument is preserved in repetition so that each repetition moves up in the source file.

In general, the list command expects you to supply a linespecs.  Linespecs specify source lines; there are several ways of writing them, but the effect is always to specify some source line.

Here is a complete description of the possible arguments for list:

list LINESPEC
     Print lines centered around the line specified by LINESPEC.

list FIRST INCREMENT
     Print INCREMENT lines starting from FIRST

list FIRST
     Print lines starting with FIRST.

list -
     Print lines just before the lines last printed.

list .
     Print lines after where the script is stopped.

list
     As described in the preceding table.

Here are the ways of specifying a single source line---all the kinds of linespec.

NUMBER
     Specifies line NUMBER of the current source file. When a list command has two linespecs, this refers to the same source file as the first linespec.

FILENAME:NUMBER
     Specifies line NUMBER in the source file FILENAME.

FUNCTION
     Specifies the line that function FUNCTION is listed on.

Editing Source files (edit)
===========================

To edit the lines in a source file, use the edit command.  The editing program of your choice is invoked with the current line set to the active line in the program.  Alternatively, you can give a line specification to specify what part of the file you want to print if you want to see other parts of the program.

You can customize to use any editor you want by using the EDITOR environment variable. The only restriction is that your editor (say ex), recognizes the following command-line syntax:

     ex +NUMBER file

The optional numeric value +NUMBER specifies the number of the line in the file where to start editing.  For example, to configure the BASH debugger to use the vi editor, you could use these commands with the sh shell:

     EDITOR=/usr/bin/vi
     export EDITOR
     gdb ...

or in the csh shell,

     setenv EDITOR /usr/bin/vi
     gdb ...

edit line specification
     Edit line specification using the editor specified by the EDITOR environment variable.

Searching source files (search, reverse, /.../, ?..?)
=====================================================

There are two commands for searching through the current source file for a BASH extended pattern-matching expression.

forward BASH-PATTERN
search BASH-PATTERN
     The command forward BASH-PATTERN checks each line, starting with the one following the current line, for a match for BASH-PATTERN which is an extended bash pattern-matching expression.  It lists the line that is found.  You can use the synonym search BASH-PATTERN or abbreviate the command name as fo or /PAT/.

reverse BASH-PATTERN
     The command reverse BASH-PATTERN checks each line, starting with the one before the last line listed and going backward, for a match for BASH-PATTERN.  It lists the line that is found.  You can abbreviate this command as rev or ?BASH-PATTERN?.

Examining Data (print, examine, info variables)
===============================================

One way to examine string data in your script is with the print command (abbreviated p). However a more versatile print command is x; it can print variable and function definitions and can do arithmetic computations. Finally, the most general method would be via eval echo.

print EXPR

     Use print to display strings as you would from echo. And as such, variable names to be substituted have to be preceded with a dollar sign. As with echo, filename expansion, e.g. tilde expansion, is performed on unquoted strings. So for example if you want to print a *, you would write print "*", not print *. If you want to have the special characters dollars sign appear, use a backslash.

          bashdb<0> print the value of x is $x
          the value of x is 22
          bashdb<1> p The home directory for root is ~root
          The home directory for root is /root
          bashdb<2> p '*** You may have won $$$ ***'
          *** You may have won $$$ ***
          bashdb<3> # Note the use of the single quotes.
          bashdb<3> # Compare what happens with double quotes or no quotes

print
p
     If you omit EXPR, the BASH debugger displays the last expression again.

x VARIABLE1 variable2...

x EXPR

     This is a smarter, more versatile ``print'' command, and although sometimes it might not be what you want, and you may want to resort to either print or eval echo....

     As with print, if you omit EXPR, the BASH debugger displays the last expression again.

     The x command first checks if EXPR is variable or a list of variables delimited by spaces. If it is, the definition(s) and value(s) of each printed via BASH's declare -p command. This will show the variable's attributes such as if it is read only or if it is an integer. If the variable is an array, that is show and the array values are printed.

     If instead EXPR is a function, the function definition is printed via BASH's declare -f command. If EXPR was neither a variable nor an expression, then we try to get a value via let. And if this returns an error, as a last resort we call print and give what it outputs.

     Since let may be used internally and since (to my thinking) let does funny things, the results may seem odd unless you understand the sequence tried above and how let works. For ``example if the variable foo has value 5, then x foo shows the definition of foo with value 5, and x foo+5 prints 10 as expected. So far so good. However if foo is has the value alpha, x foo+5 prints 5 because let has converted the string alpha into the numeric value 0. So p foo+5 will simply print ``foo+5''; if you want the value of ``foo'' substituted inside a string, for example you expect ``the value of foo is $foo'' to come out ``the value of foo is 5'', then the right command to use is print rather than x, making sure you add the dollar onto the beginning of the variable.

          bashdb<0> examine x y
          declare -- x="22"
          declare -- y="23"
          bashdb<1> examine x+y
          45
          bashdb<2> x fn1
          fn1 ()
          {
              echo "fn1 here";
              x=5;
              fn3
          }
          bashdb<2> x FUNCNAME
          declare -a FUNCNAME='([0]="_Dbg_cmd_x" [1]="_Dbg_cmdloop" [2]="_Dbg_debug_trap_handler" [3]="main")'

V !pattern

     If you want to all list variables and values or a set of variables by pattern, use this command.

          bashdb<0> V dq*
          dq_args="dq_*"
          dq_cmd="V"
          bashdb<1> V FUNCNAME
          FUNCNAME='([0]="_Dbg_cmd_list_variables" [1]="_Dbg_cmdloop" [2]="_Dbg_debug_trap_handler" [3]="main")'

Automatic display (display, undisplay)
======================================

If you find that you want to print the value of an expression frequently (to see how it changes), you might want to add it to the automatic display list so that the BASH debugger evaluates a statement each time your program stops.  Each expression added to the list is given a number to identify it; to remove an expression from the list, you specify that number.  The automatic display looks like this:

     2 (echo $x): 38

This display shows item numbers, expressions and their current values.

display EXPR
     Add the expression EXPR to the list of expressions to display each time your program stops.

display
     Display the current values of the expressions on the list, just as is done when your program stops.

undisplay DNUMS...
delete display DNUMS...
     Remove item numbers DNUMS from the list of expressions to display.

     undisplay does not repeat if you press RET after using it. (Otherwise you would just get the error No display number ....)

disable display DNUMS...
     Disable the display of item numbers DNUMS.  A disabled display item is not printed automatically, but is not forgotten.  It may be enabled again later.

enable display DNUMS...
     Enable display of item numbers DNUMS.  It becomes effective once again in auto display of its expression, until you specify otherwise.

info display
     Print the list of expressions previously set up to display automatically, each one with its item number, but without showing the values.  This includes disabled expressions, which are marked as such. It also includes expressions which would not be displayed right now because they refer to automatic variables not currently available.

Running Arbitrary BASH and Shell commands (eval, shell)
=======================================================

The two most general commands and most ``low-level'' are eval and shell.

eval [ bash-code ]
e

     In contrast to the commands of the last section the most general way to examine data is through eval. But you do much more with this; you can change the values of variables, since, you are just evaluating BASH code.

     If you expect output, you should arrange that in the command, such as via echo or printf. For example, to print the value of FOO, you would type e echo $foo. This is bit longer than p $foo or (when possible) x foo. However suppose you wanted to find out how the builtin test operator [ works with the -z test condition. You could use eval to do this such as e [ -z "$foo"] && echo "yes".

eval

     I find I sometimes want to run the line that's about to be executed to see if I want to step into methods that are called.

     For example:

          (/etc/apparmor/functions:24):
          PROFILES="/etc/apparmor.d"
          bashdb<2>

     I had been cutting and pasting the command as shown, but realized I could do better if I made a command for this. So that's what I've done.

     If you run the eval command without any arguments, it will run the command that is about to be run.

          (/etc/apparmor/functions:24):
          PROFILES="/etc/apparmor.d"
          bashdb<2> eval
          eval: PROFILES="/etc/apparmor.d"
          $? is 0
          bashdb<3>

     This was working fine, until I started coming across tests inside if, elsif,  case, return or while blocks. For example:

          (/etc/init.d/apparmor:70):
          if [ "$1" = "recache" ]

     Suppose I want to know which branch I'm going to take before taking the branch. That way I might even be able to change which way to go by changing the test before it runs in the debugged program. (In the above example, I could print $1

          bashdb<2> pr $1
          status

     But I'm lazy. I'd rather let the debugger do the work for me:

          bashdb<1> eval?
          eval: [ "$1" = "recache" ]
          $? is 1

     If you alias eval with a name that ends in ? it will strip off any leading if, case, while, elsif, or return.

!! COMMAND STRING

     If you need to execute occasional shell commands during your debugging session, there is no need to leave or suspend the BASH debugger; you can just use the shell command or its alias !!.

     Invoke a shell to execute COMMAND STRING.

shell

     Although the debugger allows one to evaluate arbitrary BASH code using eval, or via the set autoeval mode, sometimes you might prefer to work inside a BASH shell to see variables, experiment, issue commands (using the currently-set up environment), and even change variables and functions.

     For this we, the debugger shell command, enters a nested shell session. But before it does this, it saves out variable and function definitions in the current context of the running program. That way, you have access to those.

     This however creates a new problem: getting changes you make reflected back into the running program. Right now any variable you change can be flagged to have its value re-read when the shell exits. This is done using the save_var function inside the nested shell. save_var takes a list of variable names.

     Here is an example session

          bashdb /etc/init.d/apparmor status
          bashdb debugger, release 4.2-0.6

          Copyright 2002, 2003, 2004, 2006, 2007, 2008, 2009, 2010 Rocky Bernstein
          This is free software, covered by the GNU General Public License, and you are
          welcome to change it and/or distribute copies of it under certain conditions.
          ...
          (/etc/init.d/apparmor:35):
          . /etc/apparmor/functions
          bashdb<1> s
          (/etc/apparmor/functions:24):
          PROFILES="/etc/apparmor.d"
          bashdb<2> s
          (/etc/apparmor/functions:25):
          PARSER="/sbin/apparmor_parser"
          bashdb<3> shell
          bashdb $ typeset -p PROFILES
          typeset -p PROFILES
          typeset PROFILES=/etc/apparmor.d
          bashdb $ PROFILES='Hi, Mom!'
          bashdb $ save_vars PROFILES
          bashdb $  <EOF>
          (/etc/apparmor/functions:25):
          PARSER="/sbin/apparmor_parser"
          bashdb<4> x PROFILES
          typeset PROFILES='Hi, Mom!'

     Note that inside the nested shell the we have set the prompt has been set to bashdb $ .

Interfacing to the OS (cd, pwd)
===============================

cd

     Set working directory to DIRECTORY for debugger and program being debugged.  Tilde expansion, variable and filename expansion is performed on DIRECTORY. If no directory is given, we print out the current directory which is really the same things as running pwd.

     Note that gdb is a little different in that it peforms tilde expansion but not filename or variable expansion and the directory argument is not optional as it is here.

pwd

     Prints the working directory as the program sees things.

Status and Debugger Settings (info, show)
=========================================

In addition to help, you can use the BASH commands info and show to inquire about the state of your program, or the state of BASH itself.  Each command supports many topics of inquiry; here we introduce each of them in the appropriate context.  The listings under info and under show in the Index point to all the sub-commands.  See Command Index.

Showing information about the program being debugged (info)
-----------------------------------------------------------

This info command (abbreviated i) is for describing the state of your program.  For example, you can list the current $1, $2 parameters with info args, or list the breakpoints you have set with info breakpoints or info watchpoints.  You can get a complete list of the info sub-commands with help info.

info args
     Argument variables (e.g. $1, $2, ...) of the current stack frame.

info breakpoints
     Status of user-settable breakpoints

info display
     Show all display expressions

info files
     Source files in the program

info functions
     All function names

info line
     list current line number and and file name

info program
     Execution status of the program.

info signals
     What debugger does when program gets various signals

info source
     Information about the current source file

info stack
     Backtrace of the stack

info terminal
     Print terminal device

info variables
     All global and static variable names

Show information about the debugger (show)
------------------------------------------

In contrast to info, show is for describing the state of BASH itself.  You can change most of the things you can show, by using the related command set;

The distinction between info and show however is a bit fuzzy and is kept here to try to follow the GDB interface. For example, to list the arguments given to your script use show args; info args does something different.

Here are three miscellaneous show subcommands, all of which are exceptional in lacking corresponding set commands:

show version
     Show what version of BASH is running.  You should include this information in BASH bug-reports.  If multiple versions of BASH are in use at your site, you may need to determine which version of BASH you are running; as BASH evolves, new commands are introduced, and old ones may wither away.  Also, many system vendors ship variant versions of BASH, and there are variant versions of BASH in GNU/Linux distributions as well. The version number is the same as the one announced when you start BASH.

show copying
     Display information about permission for copying BASH.

show linetrace

     Show if line tracing is enabled. See also Line Tracing.

show logging

     Show summary information of logging variables which can be set via set logging. See also Logging.

show logging file

     Show the current logging file.

show logging overwrite

     Show whether logging overwrites or appends to the log file.

show warranty
     Display the GNU ``NO WARRANTY'' statement, or a warranty, if your version of comes with one.

Controlling bashdb (set, file, prompt, history...)
==================================================

You can alter the way BASH interacts with you in various ways given below.

Debugger Command Aliases (alias)
--------------------------------

alias NAME COMMAND
     Add NAME as an alias for COMMAND

     Remove NAME as an alias for COMMAND

unalias NAME COMMAND

Annotation Level (set annotate)
-------------------------------

set annotate INTEGER
     The annotation level controls how much information the BASH debugger prints in its prompt; right new it just controls whether we show full filenames in output or the base part of the filename without path information.  Level 0 is the normal, level 1 is for use when the BASH debugger is run as a subprocess of GNU Emacs of DDD, level 2 is the maximum annotation suitable for programs that control the BASH debugger.

Set/Show auto-eval (set autoeval)
---------------------------------

set autoeval [ on | 1 | off | 0 ]
     Specify that debugger input that isn't recognized as a command should be passed to Ruby for evaluation (using the current debugged program namespace). Note however that we first check input to see if it is a debugger command and only if it is not do we consider it as Ruby code. This means for example that if you have variable called n and you want to see its value, you could use p n, because just entering n will be interpreted as the debugger ``next'' command.

     When autoeval is set on, you'll get a different error message when you invalid commands are encountered. Here's a session fragment to show the difference

          bashdb<1> stepp
          Unknown command
          bashdb<2> set autoeval on
          autoeval is on.
          bashdb<3> stepp
          NameError Exception: undefined local variable or method `stepp' for ...

show args
     Shows whether Ruby evaluation of debugger input should occur or not.

Set/Show listing on stop (set autolist)
---------------------------------------

set autolist [ on | 1 | off | 0 ]
     When set runs a ``list'' command on each stop in the debugger.

File basename (set basename)
----------------------------

set basename [ on | 1 ]
     When set on, source filenames are shown as the shorter ``basename'' only. (Directory paths are omitted). This is useful in running the regression tests and may useful in showing debugger examples as in this text. You may also just want less verbose filename display.

set basename [ off | 0 ]
     Source filenames are shown as with their full path. This is the default.

Allow Debugging the debugger (set debugger)
-------------------------------------------

set debugger [ on | 1 ]
     Allow the possibility of debugging this debugger. Somewhat of an arcane thing to do. For gurus, and even he doesn't use it all that much.

set debugger [ off | 0 ]
     Don't allow debugging into the debugger. This is the default.

Specifying a Script-File Association (file)
-------------------------------------------

Sometimes the BASH debugger gets confused about where to find the script source file for the name reported to it by bash. To resolve relative file names that bash supplies via BASH_SOURCE, the BASH debugger uses the current working directory when the debugged script was started as well as the current working directory now (which might be different if a ``cd'' command was issued to change the working directory).

However somethimes this doesn't work and there is a way to override this.

file SCRIPT-FILE
     Directs the BASH debugger to use SCRIPT-FILE whenever bash would have it refers to the filename given in BASH_SOURCE. The filename specified in BASH_SOURCE that gets overriden is shown when is this command is issued.

Show position information as statements are executed (set linetrace)
--------------------------------------------------------------------

BASH has ``set -x'' tracing to show commands as they are run. However missing from this is file and line position information. So the debugger compensates here for what I think is deficiency of BASH by providing this information. The downside is that this tracing is slower than the built-in tracing of BASH.

The status of whether line tracing is enabled can be show via show linetrace.

set linetrace [ on | 1 ]
     Turn on line tracing.

set linetrace [ off | 0 ]
     Turn off line tracing.

Logging output (set logging, set logging file...)
-------------------------------------------------

You may want to save the output of the debugger commands to a file. There are several commands to control the debuggers's logging.

set logging
     Prints set logging usage.

set logging [ on | 1 ]
     Enable or Disable logging.

set logging file FILENAME
     Change the name of the current logfile.  The default logfile is bashdb.txt.

set logging overwrite [ on | 1 ]
     By default, the debugger will append to the logfile.  Set overwrite if you want set logging on to overwrite the logfile instead.

set logging redirect [ on | 1 ]
     By default, the debugger output will go to both the terminal and the logfile.  Set redirect if you want output to go only to the log file.

show logging
     Show the current values of the logging settings.

Prompt (set prompt, show prompt)
--------------------------------

The BASH debugger indicates its readiness to read a command by printing a string called the prompt.  This string is normally:

     bashdb${_Dbg_less}${#_Dbg_history[@]}${_Dbg_greater}$_Dbg_space

When variables inside the the prompt string are evaluated, the above becomes something like bashdb<5> if this is the fifth command executed or perhaps bashdb<<2>> if you have called the debugger from inside a debugger session and this is the second command inside the debugger session or perhaps bashdb<(6)> if you entered a subshell after the fifth command.

You can change the prompt string with the set prompt command, although it is not normally advisable to do so without understanding the implications. If you are using the DDD GUI, it changes the changes the prompt and should not do so.  In certain other circumstances (such as writing a GUI like DDD), it may be is useful to change the prompt.

Note: set prompt does not add a space for you after the prompt you set.  This allows you to set a prompt which ends in a space or a prompt that does not. Furthermore due to a implementation limitation (resulting from a limitation of the bash built-in function ``read''), to put a space at the end of the prompt use the $_Dbg_space variable.

set prompt NEWPROMPT
     Directs the BASH debugger to use NEWPROMPT as its prompt string henceforth.

     Warning: changing the prompt can DDD's ability to
     understand when the debugger is waiting for input.

show prompt
     Prints a line of the form: bashdb's prompt is: YOUR-PROMPT

Command editing (set editing, show editing)
-------------------------------------------

the BASH debugger reads its input commands through bash which uses via the readline interface.  This GNU library provides consistent behavior for programs which provide a command line interface to the user.  Advantages are GNU Emacs-style or vi-style inline editing of commands, csh-like history substitution, and a storage and recall of command history across debugging sessions.

You may control the behavior of command line editing in BASH with the command set.

set editing
set editing [ on | 1 ]
     Enable command line editing (enabled by default).

set editing [ off | 0 ]
     Disable command line editing.

show editing
     Show whether command line editing is enabled.

Debugger Commands Tracing (set trace-commands, show trace-commands)
-------------------------------------------------------------------

If you need to debug user-defined commands or sourced files you may find it useful to enable command tracing.  In this mode each command will be printed as it is executed, prefixed with one or more + symbols, the quantity denoting the call depth of each command.

set trace-commands on
     Enable command tracing.

set trace-commands off
     Disable command tracing.

show trace-commands
     Display the current state of command tracing.

Command Display (set showcommand)
---------------------------------

The debugger normally lists the line number and source line of the for the statement to be next executed. Often this line contains one expression or one statement and it is clear from this line what's going to happen. However BASH allows many expressions or statements to be put on a single source line; some lines contain several units of execution. Some examples of this behavior are listed below:

     x=1; y=2; x=3
     (( x > 5 )) && x=5
     y=`echo *`

In the first line of the example above, we have three assignment statements on a single line. In the second line of the example above we have a statement which gets run only if a condition tests true. And in the third line of the example above, we have a command that gets run and then the output of that is substituted in an assignemnt statement.  If you were single stepping inside the debugger, each line might get listed more than once before each of the actions that might get performed. (In the case of the conditional statement, the line gets listed only once when the condition is false.)

In order to assist understanding where you are, the enhanced version of BASH maintains a dynamic variable BASH_COMMAND that contains piece of code next to be run (or is currently being run). The debugger has arranged to save this and can display this information or not. This is controlled by set showcommand.

set showcommand [auto | on | 1 | off | 0 ]
     controls whether or not to show the saved BASH_COMMAND for the command next to be executed.

When the value is auto the following heuristic is used to determine whether or not to display the saved BASH_COMMAND. If the last time you stopped you were at the same place and the command string has changed, then show the command. When the value on is used, the debugger always shows BASH_COMMAND and when off is used, the debugger nevers shows BASH_COMMAND. Note that listing the text of the source line is independent of whether or not the command is also listed.

Some examples:

     set showcommand auto      This is the default
     set showcommand on        Always show the next command to be executed
     set showcommand off       Never show the next command to be executed

Command history (H, history, !)
-------------------------------

The BASH debugger can keep track of the commands you type during your debugging sessions, so that you can be certain of precisely what happened.  If the prompt has not been changed (see Prompt), the history number that will be in use next is by default listed in the debugger prompt. Invalid commands and history commands are not saved on the history stack.

H [START-NUMBER end-number]

H -count
![-]N:p

     You can list what is in the history stack with H. Debugger commands in ths history stack are listed from most recent to least recent. If no START-NUMBER is given we start with the most recently executed command and end with the first entry in the history stack. If START-NUMBER is given, that history number is listed first. If END-NUMBER is given, that history number is listed last. If a single negative number is given list that many history commands.

     An alternate form is !n:p or !-n:p where n is an integer. If a minus sign is used, n is taken as the count to go back from the end rather than as a absolute history number. In contrast H, this form only prints a single history item.

     Some examples:

          H      List entire history
          H -2   List the last two history items
          !-2:p  List a single history item starting at the same place as above
          H 5    List history from history number 5 to the begining (number 0)
          H 5 0  Same as above
          H 5 3  List history from history number 5 down to history number 3
          !5:p   List a single history item 5

history [[-]N]
![-]N

     Use this command to reexecute a given history number. If no number is given, the last debugger command in the history is executed.

     An alternate form is !n or !-n where n is an integer.

     If a minus sign is used in in either form, n is taken as the count to go back from the end rather than as a absolute history number.

Use these commands to manage the the BASH debugger command history facility.

set history save
set history save [ on | 1 ]
     Record command history in a file, whose name may be specified with the set history filename command.  By default, this option is enabled.

set history save [ off | 0 ]
     Stop recording command history in a file.

set history size SIZE
     Set the number of commands which BASH keeps in its history list. This defaults to the value of the environment variable HISTSIZE, or to 256 if this variable is not set.

show history
show history save
show history size
     These commands display the state of the BASH history parameters. show history by itself displays all states.

show commands
     Display the last ten commands in the command history.

show commands N
     Print ten commands centered on command number N.

show commands +
     Print ten commands just after the commands last printed.

Command Completion (complete)
-----------------------------

The complete ARGS command lists all the possible completions for the beginning of a command.  We can also show completions for set, show and info subcommands. Use ARGS to specify the beginning of the command you want completed.  For example:

     complete d

results in:

     d
     debug
     delete
     disable
     display
     deleteall
     down

And

     complete set a

results in:

     set args
     set annotate

This is intended for use by front-ends such as GNU Emacs and DDD.

Using the BASH debugger from a front-end user interface
*******************************************************

There are some front-ends that can use the BASH debugger as a back-end debugger.

Using the BASH debugger from GNU Emacs
======================================

A special interface allows you to use GNU Emacs to view (and edit) the source files for the program you are debugging with the BASH debugger. However you must be using GNU Emacs version 23 or greater. (M-x show-emacs-version inside GNU Emacs will tell you what version you are running.)

The project emacs-dbgr at https://github.com/rocky/emacs-dbgr has the code. This project handles other debuggers, not just bashdb. Alas, steps need to be taken to make it easier to install.

The load the code M-x load-libarary dbgr.  To use this interface, use the command M-x dbgr-bashdb in GNU Emacs.  There is also am Emacs lisp command alias called bashdb. However it is possible ther will be a conflict with older code that we used to provide in this package.

When you run dbgr-bashdb you are prompted for the executable file you want to debug as an argument.

The dbgr-bashdb command starts the BASH debugger as a subprocess of Emacs, with input and output through a newly created Emacs buffer.

Using the BASH debugger under Emacs is just like using the BASH debugger normally except for two things:

  * All ``terminal'' input and output goes through the GNU Emacs buffer.

This applies both to the BASH debugger commands and their output, and to the input and output done by the program you are debugging.

This is useful because it means that you can copy the text of previous commands and input them again; you can even use parts of the output in this way.

All the facilities of GNU Emacs' Shell mode are available for interacting with your script.  In particular, you can send signals the usual way---for example, C-c C-c for an interrupt, C-c C-z for a stop.

Commands from the GUD buffer
----------------------------

  * the BASH debugger displays source code through Emacs.

Each time the BASH debugger displays a stack frame, Emacs automatically finds the source file for that frame and puts an arrow (=>) at the left margin of the current line.  Emacs uses a separate buffer for source display, and splits the screen to show both your the BASH debugger session and the source.

Explicit the BASH debugger list or search commands still produce output as usual, but you probably have no reason to use them from GNU Emacs.

     Warning: If the directory where your script resides is not your current directory, it can be easy to confuse Emacs about the location of the source files, in which case the auxiliary display buffer does not appear to show your source.  the BASH debugger can find programs by searching your environment's PATH variable, so the the BASH debugger input and output session proceeds normally; but Emacs does not get enough information back from the BASH debugger to locate the source files in this situation.  To avoid this problem, either start the BASH debugger mode from the directory where your script resides, or specify an absolute file name when prompted for the M-x gdb argument.

     A similar confusion can result if you use the the BASH debugger file command to switch to debugging a program in some other location, from an existing the BASH debugger buffer in Emacs.

By default, M-x bashdb calls the bash --debugger.  If you need to call the BASH debugger by a different name (for example, if you keep several configurations around, with different names) you can set the Emacs variable gud-bashdb-command-name; for example,

     (setq gud-bashdb-command-name "bash --debugger")

(preceded by M-: or ESC :, or typed in the *scratch* buffer, or in your .emacs file) makes Emacs call the program named ``bash-debugger'' instead.

In the the BASH debugger I/O buffer, you can use the Emacs commands listed below in addition to the standard Shell mode commands. The I/O buffer name name is usually *gud-script-name*, where script-name is the name of the script you are debugging.

Many of the commands listed below are also bound to a second key sequence which also can be used in the also be used in the source script. These are listed in Emacs Source.

C-h m
     Describe the features of Emacs' the BASH debugger Mode.

C-c C-f
     Execute until exit from the selected stack frame. The Same as the BASH debugger finish command. The GNU Emacs command name is gud-finish and C-x C-a f C-f is an alternate binding which also can be used in the source script. See Finish.

C-c C-l
     Resynchronize the current position with the source window. The GNU Emacs command name is gud-refresh and C-x C-a
     C-l is an alternate binding which also can be used in the source script.

C-c C-n
     Execute to next source line in this function, skipping all function calls. Same as the BASH debugger next command.  The GNU Emacs command name is gud-next and C-x C-a n is an alternate binding which also can be used in the source script. See Next.

     With a numeric argument, run that many times. See Numeric Arguments (The GNU Emacs Manual).

C-c C-r
     Continue execution of your script Same as the BASH debugger continue command. The GNU Emacs command name is gud-cont and C-x C-a C-r is an alternate binding which also can be used in the source script. See Continue.

C-c C-s
     Step one source line. Same as the BASH debugger step command. The GNU Emacs command name is gud-step and C-x C-a C-s is an alternate binding which can be used in the source script. See Step.

     With a numeric argument, run that many times. See Numeric Arguments (The GNU Emacs Manual).

C-c >
     Go down a stack frame.  Same as the BASH debugger down. With a numeric argument, go down that many stack frames. See Numeric Arguments (The GNU Emacs Manual).

     The GNU Emacs command name is gud-down and C-x C-a > is an alternate binding which can be used in the source script.

C-c <
     Go up a stack frame. With a numeric argument, go up that many stack frames. Same the BASH debugger up command. See Numeric Arguments (The GNU Emacs Manual).

     The GNU Emacs command name is gud-up and C-x C-a < is an alternate binding which can be used in the source script.

C-c a
     Shows argument variables (e.g. $1, $2) of the current stack frame. Same as the BASH debugger info args command. The GNU Emacs command name is gud-args and C-x C-a a is an alternate binding which also can be used in the source script.

C-c R
     Restart or run the script. Same as the BASH debugger run command. The GNU Emacs command name is gud-finish and C-x C-a R is an alternate binding which also can be used in the source script.

C-c T
     Show stack trace. Same as the BASH debugger where command. The GNU Emacs command name is gud-where and C-x C-a T is an alternate binding which can be used in the source script. See Backtrace.

In any source file, the Emacs command C-x SPC (gud-break) tells the BASH debugger to set a breakpoint on the source line point is on.

If you accidentally delete the source-display buffer, an easy way to get it back is to type the command frame in the the BASH debugger buffer, to request a frame display; when you run under Emacs, this recreates the source buffer if necessary to show you the context of the current frame.

The source files displayed in Emacs are in ordinary Emacs buffers which are visiting the source files in the usual way.  You can edit the files with these buffers if you wish; but keep in mind that the BASH debugger communicates with Emacs in terms of line numbers.  If you add or delete lines from the text, the line numbers that the BASH debugger knows cease to correspond properly with the code.

See Debugger Operation (The GNU Emacs Manual).

Commands from the source script
-------------------------------

C-x SPC

     tells the BASH debugger to set a breakpoint on the source line point is on. (gud-break)

C-x C-a t

     gud-linetrace

C-x C-a C-f
     Restart or run the script. Same as the BASH debugger run command. The GNU Emacs command name is gud-finish. In the corresponding I/O buffer, C-c R is an alternate binding.

C-x C-a T
     Show stack trace. Same as the BASH debugger where command. In the corresponding I/O buffer, C-c T is an alternate binding. See Backtrace.

C-x C-a <

     Go up a stack frame. With a numeric argument, go up that many stack frames. Same the BASH debugger up command. See Numeric Arguments (The GNU Emacs Manual).

     The GNU Emacs command name is gud-up. In the corresponding I/O buffer, C-c < is an alternate binding.

C-x C-a >

     Go down a stack frame.  Same as the BASH debugger down. With a numeric argument, go down that many stack frames. See Numeric Arguments (The GNU Emacs Manual).

     The GNU Emacs command name is gud-down. In the corresponding I/O buffer, C-c > is an alternate binding.

C-x C-a C-t

     gud-tbreak

C-x C-a C-s

     Step one source line. Same as the BASH debugger step command. See Step.

     With a numeric argument, run that many times. See Numeric Arguments (The GNU Emacs Manual).

     The GNU Emacs command name is gud-step. In the corresponding I/O buffer, C-c C-s is an alternate binding.

C-x C-a C-e

     gud-statement

C-x C-a R
     Restart or run the script. Same as the BASH debugger run command. The GNU Emacs command name is gud-run. In the corresponding I/O buffer, C-c R is an alternate binding.

C-x C-a C-d
     Delete breakpoint. gud-remove

C-x C-a C-p

     gud-print

C-x C-a C-n

     Execute to next source line in this function, skipping all function calls. Same as the BASH debugger next command.  With a numeric argument, run that many times.  See Numeric Arguments (The GNU Emacs Manual).

     The GNU Emacs command name is gud-next. In the corresponding I/O buffer, C-c C-n is an alternate binding.

C-x C-a f	C-f

     gud-finish

C-x C-a C-r
     Continue execution of your script Same as the BASH debugger continue command. The GNU Emacs command name is gud-cont. In the corresponding I/O buffer, C-c C-r is an alternate binding. See Continue.

C-x C-a C-b

     gud-break

C-x C-a a

     gud-args Shows argument variables (e.g. $1, $2) of the current stack frame. Same as the BASH debugger info args command.  The GNU Emacs command name is gud-args. In the corresponding I/O buffer, C-c a is an alternate binding which also can be used in the source script.

C-x C-a C-l
     Move to current position in this source window. The GNU Emacs command name is gud-refresh. In the corresponding I/O buffer, C-c C-l is an alternate binding.

the BASH debugger from a GNU Emacs Shell
----------------------------------------

It is also possible in GNU emacs to use a regular (``comint'') shell and set a mode to watch for the BASH debugger prompts. See Shell (The GNU Emacs Manual).

To run bash in a shell in Emacs but track source lines this, issue the the command (from M-x) turn-on-bashdbtrack. There is some overhead involved in scanning output, so if you are not debugging bash programs you probably want to turn this off which can be done via the M-x turn-off-bashdbtrack command.

Using the BASH debugger from DDD
================================

the BASH debugger support is rather new in DDD. As a programming language, the BASH debugger is not feature rich: there are no record structures or hash tables (yet), no pointers, package variable scoping or methods. So much of the data display and visualization features of DDD are disabled.

As with any scripting or interpreted language (e.g. Perl), one can't step by a single machine-language instruction. So the ddd Stepi/Nexti commands are disabled.

Some BASH settings are essential for DDD to work correctly.  These settings with their correct values are:

     set annotate 1
     set prompt set prompt bashdb$_Dbg_less$_Dbg_greater$_Dbg_space

DDD sets these values automatically when invoking BASH; if these values are changed, there may be some malfunctions.

Pay special attention when the prompt has extra angle brackets (a nested shell) or has any parenthesis (is in a subshell). Quitting may merely exit out of one of these nested (sub)shells rather than leave the program.

Reporting Bugs
**************

Your bug reports play an essential role in making the BASH debugger reliable.

Reporting a bug may help you by bringing a solution to your problem, or it may not.  But in any case the principal function of a bug report is to help the entire community by making the next version of the BASH debugger work better.  Bug reports are your contribution to the maintenance of the BASH debugger.

In order for a bug report to serve its purpose, you must include the information that enables us to fix the bug.

Have you found a bug?
=====================

If you are not sure whether you have found a bug, here are some guidelines:

  * If the debugger gets a fatal signal, for any input whatever, that is a the BASH debugger bug.  Reliable debuggers never crash.

  * If the BASH debugger produces an error message for valid input, that is a bug.  (Note that if you're cross debugging, the problem may also be somewhere in the connection to the target.)

  * If the BASH debugger does not produce an error message for invalid input, that is a bug.  However, you should note that your idea of ``invalid input'' might be our idea of ``an extension'' or ``support for traditional practice''.

  * If you are an experienced user of debugging tools, your suggestions for improvement of the BASH debugger are welcome in any case.

How to report bugs
==================

Bug reports can sent via the sourceforge bug tracking mechansim at http://sourceforge.net/tracker/?group_id=61395&atid=497159. Of course patches are very much welcome too. Those can also be sent via the same mechanism.

The fundamental principle of reporting bugs usefully is this: report all the facts.  If you are not sure whether to state a fact or leave it out, state it!

Often people omit facts because they think they know what causes the problem and assume that some details do not matter.  Thus, you might assume that the name of the variable you use in an example does not matter. Well, probably it does not, but one cannot be sure.  Perhaps the bug is a stray memory reference which happens to fetch from the location where that name is stored in memory; perhaps, if the name were different, the contents of that location would fool the debugger into doing the right thing despite the bug.  Play it safe and give a specific, complete example.  That is the easiest thing for you to do, and the most helpful.

Keep in mind that the purpose of a bug report is to enable us to fix the bug.  It may be that the bug has been reported previously, but neither you nor we can know that unless your bug report is complete and self-contained.

Sometimes people give a few sketchy facts and ask, ``Does this ring a bell?''  Those bug reports are useless, and we urge everyone to refuse to respond to them except to chide the sender to report bugs properly.

To enable us to fix the bug, you should include all these things:

  * The version of the BASH debugger.  the BASH debugger announces it if you start with no arguments; you can also print it at any time using version command.

     Without this, we will not know whether there is any point in looking for the bug in the current version of the BASH debugger.

  * The type of machine you are using, and the operating system name and version number.

  * What compiler (and its version) was used to compile BASH---e.g. ``gcc 3.4''.

  * The command arguments you gave the compiler to compile your example and observe the bug.  For example, did you use -O?  To guarantee you will not omit something important, list them all.  A copy of the Makefile (or the output from make) is sufficient.

     If we were to try to guess the arguments, we would probably guess wrong and then we might not encounter the bug.

  * A complete input script, and all necessary source files, that will reproduce the bug.

  * A description of what behavior you observe that you believe is incorrect.  For example, ``It gets a fatal signal.''

     Of course, if the bug is that the BASH debugger gets a fatal signal, then we will certainly notice it.  But if the bug is incorrect output, we might not notice unless it is glaringly wrong.  You might as well not give us a chance to make a mistake.

     Even if the problem you experience is a fatal signal, you should still say so explicitly.  Suppose something strange is going on, such as, your copy of the BASH debugger is out of synch, or you have encountered a bug in the C library on your system.  (This has happened!)  Your copy might crash and ours would not.  If you told us to expect a crash, then when ours fails to crash, we would know that the bug was not happening for us.  If you had not told us to expect a crash, then we would not be able to draw any conclusion from our observations.

  * If you wish to suggest changes to the the BASH debugger source, send us context diffs.  If you even discuss something in the the BASH debugger source, refer to it by context, not by line number.

     The line numbers in our development sources will not match those in your sources.  Your line numbers would convey no useful information to us.

Here are some things that are not necessary:

  * A description of the envelope of the bug.

     Often people who encounter a bug spend a lot of time investigating which changes to the input file will make the bug go away and which changes will not affect it.

     This is often time consuming and not very useful, because the way we will find the bug is by running a single example under the debugger with breakpoints, not by pure deduction from a series of examples. We recommend that you save your time for something else.

     Of course, if you can find a simpler example to report instead of the original one, that is a convenience for us.  Errors in the output will be easier to spot, running under the debugger will take less time, and so on.

     However, simplification is not vital; if you do not want to do this, report the bug anyway and send us the entire test case you used.

  * A patch for the bug.

     A patch for the bug does help us if it is a good one.  But do not omit the necessary information, such as the test case, on the assumption that a patch is all we need.  We might see problems with your patch and decide to fix the problem another way, or we might not understand it at all.

     Sometimes with a program as complicated as the BASH debugger it is very hard to construct an example that will make the program follow a certain path through the code.  If you do not send us the example, we will not be able to construct one, so we will not be able to verify that the bug is fixed.

     And if we cannot understand what bug you are trying to fix, or why your patch should be an improvement, we will not install it.  A test case will help us to understand.

  * A guess about what the bug is or what it depends on.

     Such guesses are usually wrong.  Even we cannot guess right about such things without first using the debugger to find the facts.

History and Acknowledgments
***************************

The suggestion for a debugger for a Bourne-like shell came from the book ``Learning the Korn Shell'', by Bill Rosenblatt Copyright (C) 1993 by O'Reilly and Associates, Inc. Others such as Cigy Cyriac, Chet Ramey, Rocky Bernstein, and Gary V. Vaughan expanded and improved on that.

However Bourne-Shell debuggers rely on a signal mechanism (SIGDEBUG) to call a debugger routine. In the Korn shell as well as BASH in versions prior to 2.05, there was a fundamental flaw: the routine that you registered in the trap, got called after the statement was executed. It takes little imagination to realize that this is a bit too late to find and correct errors, especially if the offending command happens to do serious damage like remove filesystems or reboot a server. As a horrible hack, these debuggers added one to the line number that was just executed on the wishful thinking that this would then be the line of next statement to execute. Sometimes this was correct, but it was too often wrong, such as in loops and conditionals, comments, or commands that are continued on the next line.

Another failing of these debuggers was the inability to debug into functions or into sourced files, provide a stack trace, dynamically skip a statement to be run, unconditionally trace into a function or subshell, or stop when a subroutine, sourced file, or subshell completed. In truth, the crux of the problem lay in debugging support in BASH. Given that there was limited bash debugging support, it is not surprising that these debuggers could not do any of the things listed above and could debug only a single shell in a single source file: lines could be listed only from a single text, breakpoints were set into the text which was in fact a copy of the script name prepended with debugger routines.

In version 2.04 of BASH, Rocky Bernstein started hacking on BASH to add call-stack information, source file information, allow for debugging into functions and for reporting line numbers in functions as relative to the file rather than the beginning of a function whose origin line number was not accessible from BASH. He started changing the user commands in bashdb to be like other more-advanced debuggers, in particular perl5db and gdb. However he gave up on this project when realizing that stopping before a line was crucial. A patch for this was nontrivial and wildly changed semantics. Furthermore the chance of getting his other patches into BASH was was not going to happen in version 2.04.

In version 2.05, the fundamental necessary change to the semantics of SIGDEBUG trap handling (suggested at least two years earlier) was made. Also, version 2.05 changed the line-number reporting in a function to be relative to the beginning of the file rather than the beginning of a function---sometimes. Rocky then picked up where he left off and this then became this debugger. A complete rewrite of the debugger, some of which started in 2.04 was undertaken. Debugger internals were changed to support multiple file names, save and restore the calling environment (such as variables $1 and $?) and install debugger signal handlers. Work was also done on the BASH in conjunction with the debugger to save stack trace information, provide a means for stopping after a routine finished, debugging into a subshell and so on. And a number of changes were made to BASH just to improve the accuracy of the line number reporting which is crucial in a debugger.

This documentation was modified from the GNU Debugger (GDB) Reference manual.

     Additions to this section are particularly welcome.  If you or your friends (or enemies, to be evenhanded) have been unfairly omitted from this list, we would like to add your names!

The following have contributed directly or indrectly to bashdb:

Rocky Bernstein (initial full-featured bashdb with stack tracing and multi-file support)

Masatake YAMATO (help to merge Rocky's hack to the official bash source tree)

Bill Rosenblatt (kshdb), Michael Loukides (kshdb), Cigy Cyriac (proto bashdb), Chet Ramey (proto bashdb), and Gary V. Vaughan (proto bashdb).

Authors of per5ldb:

Ray Lischner, Johan Vromans, and Ilya Zakharevich.

Authors of GDB:

Richard Stallman, Andrew Cagney, Jim Blandy, Jason Molenda, Stan Shebs, Fred Fish, Stu Grossman, John Gilmore, Jim Kingdon, and Randy Smith (to name just a few).

Authors of GUD:

Eric S. Raymond.

     [file gpl.texi not included]

     [file fdl.texi not included]