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?
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
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'...
To pass arguments to your program on the GDB command line, use gdb --args
.
gdb --args ./program arg1 arg2
bt
echo abc
, what isbreak main
, what is-c
, what isod
, which is the tested executable? – Viesturs Jul 14 '18 at 20:24-ex
can be useful. I've added the answer to your problem to the end of the post. – meuh Jul 14 '18 at 20:33Inferior 1 [process 13597] will be killed.
Quit anyway? (y or n)` in your example?
– Viesturs Jul 14 '18 at 21:15-ex quit
by-batch
to avoid any interaction. – meuh Jul 14 '18 at 21:34'run arg1 arg2'
and don't in-ex bt
? – Viesturs Jul 31 '18 at 15:35-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-ex quit
will not be necessary if you use-batch
option. – FractalSpace Sep 12 '18 at 19:37