Search code examples
gdbgdbinit

how to have conditional part in gdbinit based on the environnment


In the gdb manual there is this part:

if else

This command allows to include in your script conditionally executed commands. The if command takes a single argument, which is an expression to evaluate...

I can perform tests in my gdbinit when I use a numeric expression, like

if (42 == 42)
    print "42"
end

But when I want to perform a test on a String, like this:

if ("a" == "a")
    print "yes"
end

then I got an error when I start gdb:

.gdbinit:45: Error in sourced command file:
You can't do that without a process to debug.

I tried, unsuccessfully, to find documentation or examples for the expression syntax in order to write my conditional block.

What I want to achieve is to add a bunch of command based on an environment variable. So I need to have this kind of section in my gdbinit:

if ("${myEnvVar}" == "someSpecialValue")
    #my set of special values
end

How to achieve that ?

edit: looks like the easiest way is to use python to perform this kind of operation: How to access environment variables inside .gdbinit and inside gdb itself?

If there's no way to achieve this with 'pure' gdb commands, I guess that this question should be closed as a duplicate.


Solution

  • How to achieve that ?

    If you have GDB with embedded Python (most recent GDB builds do), you have full power of Python at your disposal.

    For example:

    # ~/.gdbinit
    source ~/.gdbinit.py
    
    # ~/.gdbinit.py
    import os
    
    h = os.getenv("MY_ENV_VAR")
    if h:
      print "MY_ENV_VAR =", h
      gdb.execute("set history size 100")
      # Put other settings here ...
    else:
      print "MY_ENV_VAR is unset"
    

    Let's see if it works:

    $ gdb -q 
    MY_ENV_VAR is unset
    (gdb) q
    
    $ MY_ENV_VAR=abc gdb -q 
    MY_ENV_VAR = abc
    (gdb)