10

When I debug an executable program with arguments arg1 arg2 with gdb I perform the following sequence

gdb
file ./program
run arg1 arg2
bt
quit

How can I do the same from one command line in shell script?

Viesturs
  • 943
  • 3
  • 12
  • 16

3 Answers3

17

You can pass commands to gdb on the command line with option -ex. You need to repeat this for each command. This can be useful when your program needs to read stdin so you don't want to redirect it. Eg, for od -c

echo abc |
gdb -ex 'break main' -ex 'run -c' -ex bt -ex cont -ex quit  od

So in particular for your question, you can use:

gdb -ex 'run arg1 arg2' -ex bt -ex quit ./program
meuh
  • 51,383
  • 2
    Why echo abc , what is break main, what is -c, what is od, which is the tested executable? – Viesturs Jul 14 '18 at 20:24
  • The example is just to show how -ex can be useful. I've added the answer to your problem to the end of the post. – meuh Jul 14 '18 at 20:33
  • How can I get rid of `A debugging session is active.

    Inferior 1 [process 13597] will be killed.

    Quit anyway? (y or n)` in your example?

    – Viesturs Jul 14 '18 at 21:15
  • 4
    Simply replace the -ex quit by -batch to avoid any interaction. – meuh Jul 14 '18 at 21:34
  • Why do you use apostrophes in 'run arg1 arg2' and don't in -ex bt? – Viesturs Jul 31 '18 at 15:35
  • 1
    The -ex option wants a single string value, so when you want to pass it a string with a space in it you need to use single or double quotes to stop the shell from splitting the string into 2 strings. You can use -ex 'bt' if you like for consistency, but the shell removes all these quotes before they get to gdb as parameters. – meuh Jul 31 '18 at 15:40
  • 3
    -ex quit will not be necessary if you use -batch option. – FractalSpace Sep 12 '18 at 19:37
6

The commands could be fed in on standard input:

#!/bin/sh
exec gdb -q <<EOF
file ./program
run arg1 arg2
bt
quit
EOF

Or the commands can be placed in afile and gdb run with gdb -batch -x afile, or if you hate newlines (and the maintenance coder) with a fancy shell you can do it all on a single line (a different way to express the heredoc version):

gdb -q <<< "file ./program"$'\n'run$'\n'...
thrig
  • 34,938
2

To pass arguments to your program on the GDB command line, use gdb --args.

gdb --args ./program arg1 arg2
bt
tbodt
  • 495