TheOneTrueMorty
TheOneTrueMorty

Reputation: 159

Expect not working as expected

EDIT: So ultimately what I ended up doing here is running it straight in a mysql.expect script. Any variables that need to be updated would be replaced via sed in standard bash script used to launch mysql.expect.

I have a bash script that runs expect, and automates the MySQL installation process, as you can see here. The reason expect needs to be called in this script is to source local bash variables, so I can't just run it via expect, but rather it needs to be called it as follows:

if [ catch "spawn /bin/bash ./mysql.sh" error ] {

   puts "Could not spawn mysql.sh $error"

}

I know this works, because there's another script I have called "test.sh" that does the following:

#!/bin/bash
source ./myvars.rc

echo "CONNECTED" >> "./out.html"

echo "$MYVARIABLE" >> "./out.html"

This works fine, the variable is correctly added to out.html. The mysql.sh script works when called directly, but not through expect, and there are no errors. Any ideas? Thanks.

Upvotes: 1

Views: 750

Answers (1)

zerodiff
zerodiff

Reputation: 1700

I'm not an expect expert, but you may have a syntax error in the spawn command. This seems to work:

#!/usr/bin/expect

if { [ catch {spawn /bin/bash ./mysql.sh} error ] } {  
   puts "Could not spawn mysql.sh $error"
}
# This is the important part
interact

catch returns 0 (OK) if your command succeeds. You were seeing "success" because it really errored out, but you were testing the other condition.

So, I did some more testing and updated that a bit. You don't want the ! there, but you do want the interact. Once you spawn something with expect, you want to either use expect to process the output, or if there is none to process, just let the script run with interact.

The interesting thing is that if you use /bin/bash ./mysql.sh without interact, this will just do nothing but not actually run the script. If you use just ./mysql.sh, it will hang. I assume there is something with standard in/out that happens differently between the two.

Anyway, I hope this helps and actually solve your problem. Extra added stuff because I'm geeking out here -- you probably want exec instead of spawn if you don't want to interact with your script:

#!/usr/bin/expect

if { [ catch {puts [exec /bin/bash ./mysql.sh]} error ] } {
   puts "Could not spawn mysql.sh $error"
}

The puts is there because otherwise you will lose the output of the script. If you don't care about the output, you can use:

#!/usr/bin/expect

if { [ catch {exec /bin/bash ./mysql.sh} error ] } {
   puts "Could not spawn mysql.sh $error"
}

Upvotes: 1

Related Questions