How do I run a program with commandline arguments using GDB within a Bash script?
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?
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