How to Run GDB in Bash Script
This tutorial demonstrates running gdb
in a bash script with a binary file that takes command line arguments.
We will create a C program that takes a single command-line argument and convert it into a binary file. We will use this binary file for demonstration purposes in this tutorial.
Create a Binary File
Here is a C program that takes a command-line argument and prints it to the screen.
#include <stdio.h>
void main(int argc, char *argv[]) {
printf("This is a C program!\n");
if (argc < 2) {
printf("No argument passed.\n");
} else {
printf("Argument 1: %s\n", argv[1]);
}
}
Compile the C program and convert it to a binary file using the following command.
gcc args.c -o args
Run the binary file without any arguments.
./args
The output of the binary file without arguments:
This is a C program!
No argument passed.
Run the binary file with a single argument.
./args hello
The output of the binary file with a single argument.
This is a C program!
Argument 1: hello
Run gdb
in Bash Script
The bash script runs gdb
with the -q
option, which stands for quite. It tells gdb
not to print the version number on startup. The --args
option is used to pass command-line arguments to the binary that gdb
loads for debugging. However, the first argument is the binary.
In our case, args
is the name of the binary, and arg1
is the argument being passed to the binary.
#!/bin/bash
gdb -q --args args arg1
Run the bash script.
bash gdb_script.sh
Once you run the script, it opens up gdb
as shown below, but it does not run the binary file. You need to type run
to execute the binary file in gdb
.
Reading symbols from args...
(no debugging symbols found)...done.
gdb$
To automatically run the binary file once we run the bash script, we can add the -ex=r
as shown below.
!/bin/bash
gdb -q -ex=r --args args arg1
Run the bash script.
bash gdb_script.sh
From the output, we can see that the binary file was run automatically without us having to type run
in gdb
.
Reading symbols from args...
(no debugging symbols found)...done.
Starting program: /root/args arg1
This is a C program!
Argument 1: arg1
[Inferior 1 (process 3372) exited with code 021]
Warning: not running
gdb-peda$