I am trying to automate gdb with expect. My script will start gdb, do some initialisation, and then pass the control to the user. Expect's interact command seems like the perfect tool for the job.

Now consider:

$ echo "spawn gdb
    expect \"(gdb) \"
    send \"help\r\"
    expect \"(gdb) \"
    interact" | expect -

On my machines, this scriptlet spawns gdb, issues the help command, as expected. But then it immediately exits the script and returns me to the bash prompt. I would expect the user to stay within gdb and be able to issue commands.

Any idea what I am missing here?

  • Are you running on Windows? Oct 24, 2013 at 13:43

1 Answer 1


interact will get its input from expects standard input, which is the pipe to echo now closed.

You can write it instead (ksh/zsh/bash syntax):

expect <(echo "spawn gdb
  expect \"(gdb) \"
  send \"help\r\"
  expect \"(gdb) \"
  interact" )

That's still fed via a pipe, but this time, the pipe is given as a path argument to expect so expect's stdin is not affected.

In this case though, the obvious may to write it would be:

expect -c '
  spawn gdb
  expect "(gdb)"
  send "help\r"
  expect "(gdb) "

expect like sh and most shells allow passing inline scripts with -c.

If you still need to pass the output of a command (like echo in your case), you can do it with -c as well with:

expect -c "$(echo...)"

That means however that contrary to the pipe approaches expect won't start until that command has finished.

BTW, here, you could use a .gdbinit file instead or -ix option to gdb, you don't really need expect.

  • Thanks, it does make complete sense indeed. Could you please elaborate (or point to documentation) on the <() construction? I don't know it, and it's hard to google! Oct 24, 2013 at 18:02
  • Also, yes I know about -ix but my real script is much more complex and in this case, I need the flexibility of expect. Good suggestion though. Oct 24, 2013 at 18:03
  • 1
    @NicolasBonnefon. That's called process substitution, a ksh feature. Plenty of questions and answers on it on U&L Oct 24, 2013 at 18:57
  • @NicolasBonnefon @StéphaneChazelas I have been able to avoid escaping the quotation marks by using the construct expect <(cat <<- 'EOF' ... EOF )
    – Andreas
    Jun 10, 2015 at 4:48
  • why so convoluted? why not just write a `#!/usr/bin/expect -f`` script?
    – cas
    Nov 4, 2015 at 9:49

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .