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

file ./program
run arg1 arg2

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

3 Answers 3


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
  • 2
    Why echo abc , what is break main, what is -c, what is od, which is the tested executable?
    – Viesturs
    Commented Jul 14, 2018 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
    Commented Jul 14, 2018 at 20:33
  • 4
    Simply replace the -ex quit by -batch to avoid any interaction.
    – meuh
    Commented Jul 14, 2018 at 21:34
  • 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
    Commented Jul 31, 2018 at 15:40
  • 3
    -ex quit will not be necessary if you use -batch option. Commented Sep 12, 2018 at 19:37

The commands could be fed in on standard input:

exec gdb -q <<EOF
file ./program
run arg1 arg2

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'...
  • why not give afile an .sh extension once it is a shell script?
    – Viesturs
    Commented Jul 14, 2018 at 21:12
  • Using exec will prevent executing after gdb exit. Commented Jul 15, 2018 at 12:38
  • @Viesturs I never put *.sh on my shell scripts
    – thrig
    Commented Jul 15, 2018 at 14:17

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

gdb --args ./program arg1 arg2

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .