Breakpoint command lists

You can give any breakpoint (or watchpoint) a series of commands to execute when your program stops due to that breakpoint. For example, you might want to print the values of certain expressions, or enable other breakpoints.

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 or watchpoint set (not to the breakpoint most recently encountered).

Pressing Enter as a means of repeating the last GDB command is disabled within a command-list.

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

Commands in command-list that follow 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 isn't 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. The silent command 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's 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 doesn't stop, and start with the silent command so that no output is produced. Here's an example:

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