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
echo abc , what is break main, what is -c, what is od, which is the tested executable?
-ex can be useful. I've added the answer to your problem to the end of the post.
-ex quit by -batch to avoid any interaction.
-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.
-ex quit will not be necessary if you use -batch option.
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'...
afile an .sh extension once it is a shell script?
*.sh on my shell scripts
To pass arguments to your program on the GDB command line, use gdb --args.
gdb --args ./program arg1 arg2
bt