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?


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
  • 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
  • 3
    Simply replace the -ex quit by -batch to avoid any interaction. – meuh Jul 14 '18 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 Jul 31 '18 at 15:40
  • 1
    -ex quit will not be necessary if you use -batch option. – FractalSpace Sep 12 '18 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 Jul 14 '18 at 21:12
  • Using exec will prevent executing after gdb exit. – val Jul 15 '18 at 12:38
  • @Viesturs I never put *.sh on my shell scripts – thrig Jul 15 '18 at 14:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.