Redirection of a gdb's command output to a file can be made by using Python (my version of gdb is 8.1.1):
(gdb) python
>with open("/path/to/file/bt.txt", "w") as outfile:
> outfile.write(gdb.execute("bt", to_string=True))
>end
For convenience this functionality can be added as a command to gdb by adding into .gdbinit:
python
import argparse
class RedirOutput(gdb.Command):
def __init__(self):
super().__init__("rdr", gdb.COMMAND_USER, gdb.COMPLETE_COMMAND)
def invoke(self, argstr, from_tty):
parser = argparse.ArgumentParser()
parser.add_argument('command', nargs='+')
parser.add_argument('-o', "--outfile", required=True, help="output file")
nm = parser.parse_args(argstr.split())
with open(nm.outfile, "w") as output_file:
try:
output_file.write(gdb.execute(' '.join(nm.command), to_string=True))
except Exception as e:
print(str(e))
RedirOutput()
end
Variants of usage:
### Inside gdb
(gdb) rdr info -o /absolute/path/info.txt
(gdb) rdr info registers eax -o ./eax.txt
(gdb) rdr bt -o ./bt.txt
Note: if saving in a file is needed for subsequent opening in vim or less for more convenient viewing and paging, then the "file step" is redundant, because gdb's output can be redirected right to these programs, see redirection to less.