Search code examples
shellgdbcommandsh

run gdb batch command with `` incorrect


>cmd="/usr/bin/gdb -q --batch -ex 'thread apply all bt full' /proc/8969/exe /tmp/core.xxx"
>ret=`$cmd`
Excess command line arguments ignored. (bt ...)
apply: No such file or directory.
/etc/all: No such file or directory.
Undefined command: "".  Try "help".
>echo $ret

>

But -ex 'thread apply all bt full' change to -ex 'bt', the result is correct. I don't know why,and how to fix it.

type /usr/bin/gdb -q --batch -ex 'thread apply all bt full' /proc/8969/exe /tmp/core.xxx" in command line and execute success


Solution

  • cmd="/usr/bin/gdb -q --batch -ex 'thread apply all bt full' /proc/8969/exe /tmp/core.xxx
    ret=`$cmd`
    

    After parameter expansion of $cmd, the shell will do field splitting, which splits using the delimiters in $IFS (typically white space). This results in the following fields:

    • /usr/bin/gdb
    • -q
    • --batch
    • -ex
    • 'thread
    • apply
    • all
    • bt
    • full'
    • /proc/8969/exe
    • /tmp/core.xxx

    This tells GDB to execute a command named 'thread, and to debug an executable named apply and core file all.

    One way to get the results you want is to run

    ret=`eval "$cmd"`
    echo "$ret" # use quotes here to preserve newlines
    

    If you use bash or other modern shells that support arrays, this might be better:

    gdbargs=(-q --batch -ex 'thread apply all bt full' /proc/8969/exe /tmp/core.xxx)
    ret=`/usr/bin/gdb "${gdbargs[@]"}`
    echo "$ret"