How do I run a program with commandline arguments using GDB within a Bash script?

586,944

Solution 1

You can run gdb with --args parameter,

gdb --args executablename arg1 arg2 arg3

If you want it to run automatically, place some commands in a file (e.g. 'run') and give it as argument: -x /tmp/cmds. Optionally you can run with -batch mode.

gdb -batch -x /tmp/cmds --args executablename arg1 arg2 arg3

Solution 2

gdb -ex=r --args myprogram arg1 arg2

-ex=r is short for -ex=run and tells gdb to run your program immediately, rather than wait for you to type "run" at the prompt. Then --args says that everything that follows is the command and arguments, just as you'd normally type them at the commandline prompt.

Solution 3

Another way to do this, which I personally find slightly more convenient and intuitive (without having to remember the --args parameter), is to compile normally, and use r arg1 arg2 arg3 directly from within gdb, like so:

$ gcc -g *.c *.h
$ gdb ./a.out
(gdb) r arg1 arg2 arg3

Solution 4

You could create a file with context:

run arg1 arg2 arg3 etc

program input

And call gdb like

gdb prog < file

Solution 5

Much too late, but here is a method that works during gdb session.

gdb <executable>

then

(gdb) apropos argument

This will return lots of matches, the useful one is set args.

set args -- Set argument list to give program being debugged when it is started.

set args arg1 arg2 ...

then

r

This will run the program, passing to main(argc, argv) the arguments and the argument count.

Share:
586,944
drox
Author by

drox

A JAVA application developer

Updated on August 12, 2022

Comments

  • drox
    drox almost 2 years

    When running a program on GDB, usually, the arguments for the program are given at the run command. Is there a way to run the program using GDB and as well as give arguments within a shell script?

    I saw an answer in a related question, mentioning that we can attach GDB to the program after the script starts executing. But then I will have to 'wait' the program.

    Is there another way to do this?