8

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?

1 Answers1

13

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) "
  interact'

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.

Stéphane Chazelas
  • 522,931
  • 91
  • 1,010
  • 1,501
  • 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! – Nicolas Bonnefon Oct 24 '13 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. – Nicolas Bonnefon Oct 24 '13 at 18:03
  • 1
    @NicolasBonnefon. That's called _process substitution_, a ksh feature. Plenty of questions and answers on it on U&L – Stéphane Chazelas Oct 24 '13 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 '15 at 04:48
  • why so convoluted? why not just write a `#!/usr/bin/expect -f`` script? – cas Nov 04 '15 at 09:49
  • @cas, the OP is invoking expect as part of a _shell_ script, having to manage a separate _expect_ script would probably not be simpler. – Stéphane Chazelas Nov 04 '15 at 10:27