Search code examples
timeoutwaitexpect

How can I wait till the send command completes its execution in expect script


My code look like this.

#!/usr/bin/expect -f

set $somelocation "cd /somelocation"
set perlScriptCommand "perl runScript.pl abc xyz\r"

spawn ssh uid@IP
expect "Password: "
send "$pwd\r"
sleep 2

#change directory in the remote
send "$somelocation"

#run a perl script in the remote
send $perlScriptCommand

# **I want to make the script wait till the perl command is completed in remote

#once the previous step is completed I want to exit the remote session
send "exit\r"
expect eof

I want to wait till the send command (perl script execution in remote) completes. Then I want to exit the remote session.

I have tried by passing the commands along with ssh. Still it doesn't wait for the perl script to complete.

set somelocation "cd /somelocation"

spawn ssh uid@IP "$somelocation; $perlScriptCommand"

Solution

  • After you send something, you need to expect something. When you find yourself putting sleep into an expect script, then your expect patterns may not be matching and need to be adjusted.

    I'll assume your prompt ends with "dollar+space"

    set prompt {\$ $}
    set somelocation "cd /somelocation"
    set perlScriptCommand "perl runScript.pl abc xyz"
    
    spawn ssh uid@IP
    expect "Password: "
    send -- "$pwd\r"
    expect -re $prompt
    
    send -- "$somelocation\r"
    expect -re $prompt
    
    # disable the timeout so the perl script can take as long as it needs
    set timeout -1
    send -- "$perlScriptCommand\r"
    expect -re $prompt
    
    send "exit\r"
    expect eof
    

    While developing an expect script, run it with expect -d so you can verify that your expect patterns are matching correctly.