Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use expect with optional prompts?

Tags:

linux

bash

expect

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.

like image 910
joshualan Avatar asked Jul 12 '13 17:07

joshualan


People also ask

How do you run a command in Expect script?

The first line defines the expect command path which is #!/usr/bin/expect . On the second line of code, we disable the timeout. Then start our script using spawn command. We can use spawn to run any program we want or any other interactive script.

What does expect do in Linux?

The Linux expect command takes script writing to an entirely new level. Instead of automating processes, it automates running and responding to other scripts. In other words, you can write a script that asks how you are and then create an expect script that both runs it and tells it that you're ok.


1 Answers

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"
    }
}
like image 134
jbtule Avatar answered Sep 28 '22 01:09

jbtule