20

Let's say I am trying to write an expect script for a test.sh that has three prompts: prompt1, prompt2, prompt3.

My code is like this:

spawn test.sh
expect "prompt1"
send "pass1"
expect "prompt2"
send "pass2"
expect "prompt3"
send "pass3"

However, prompt2 only occurs half the time. If prompt2 doesn't show up, the expect script breaks. How would I write expect code that skips over prompt2 if it doesn't show up?

EDIT:

Fixed my code:

/usr/bin/expect -c '
spawn ./test.sh
expect {
      "prompt1" {
          send "pass1\r"
          exp_continue
      }
      "prompt2" {
          send "pass2\r"
          exp_continue
      }
      "prompt3" {
          send "pass3\r"
          exp_continue
      }
}
interact return
'

This way, the rest of the script executes and provides output.

Eliran Malka
  • 15,821
  • 6
  • 77
  • 100
joshualan
  • 2,030
  • 8
  • 23
  • 32
  • 2
    You will need to `expect` another pattern to be able to break out of the loop. Otherwise you'll never get to the `interact` line. – glenn jackman Jul 13 '13 at 11:47

2 Answers2

24

As long as you have a case that will be always be expected to hit and don't include an exp_continue in that case, you can can remove duplication and handle optional prompts easily:

expect "prompt1"
send "pass1"
expect { 
    "prompt2" { 
        send "pass2"
        exp_continue
    }
    "prompt3" {
        send "pass3"
    }
}
Anthony Geoghegan
  • 11,533
  • 5
  • 49
  • 56
jbtule
  • 31,383
  • 12
  • 95
  • 128
18

You can expect multiple things:

expect { 
    "prompt2" { 
        send "pass2"
        expect "prompt3"
        send "pass3"
    }
    "prompt3" {
        send "pass3"
    }
}
that other guy
  • 116,971
  • 11
  • 170
  • 194