Jenson Jose
Jenson Jose

Reputation: 532

Command sent twice via Expect

I have written an Expect script that logs into to a remote system, executes some commands in a sequence and captures the output in a log file.

Everything is happening fine except the fact that when I check the log file, some commands appear to be sent twice such that, the next command to be sent, appears in the middle of the output of the previous one. It is also sent again on detecting the prompt (which is the correct execution). Also, this issue does NOT occur in all cases, which is even more baffling.

I would like to add that I have customized the prompt to include this " ---> ". This is for easier output parsing by another script.

Here's the expect code,

set prompt "(]|%|#|>|\\$)"

# go to bash shell
expect -re $prompt
send "/bin/bash\r"

# customize the prompt
expect -re $prompt
send "PS1=\"\\u@\\H ---> \"\r"

# set new prompt into variable
expect -re $prompt
set newPrompt " ---> "

# opens file containing command list
set commFile [open commands.txt]

# reads each line containing commands from file, stores it in "$theLine" variable and sends it.
while {[gets $commFile theLine] >= 0} { 
    expect "$newPrompt"
    send "$theLine\r"
}

close $commFile

This is how my output appears.

"prompt --->" command1
----output----
----output----
command2
----output----
----output----

"prompt --->" command2
----output----
----output----

Hope you get the idea.

I don't understand this behaviour nor was I able to find any solutions to this elsewhere. Any ideas?

Upvotes: 0

Views: 968

Answers (1)

glenn jackman
glenn jackman

Reputation: 247062

There's a bit of a logic problem: after you send PS1=... you expect the old prompt. Then inside the loop you expect the new prompt before sending another command. Does this help?

send "PS1=\"\\u@\\H ---> \"\r"
set newPrompt { ---> $}
expect -re $newprompt
set commFile [open commands.txt]
while {[gets $commFile theLine] >= 0} { 
    send "$theLine\r"
    expect -re "$newPrompt"
}

Upvotes: 1

Related Questions