Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

need to return exit code of spawned procees from expect script

Tags:

shell

expect

tcl

I have below expect script

expect -c "
spawn tdwallet add $StringName
expect \"^Enter\"
send \"Krishna123\r\"
"

if [ $? != 0 ]; then
   echo "Failed to Add a String $StringName."
else
   echo "\"add <string>\" ==> [OK]"
fi

I tried modifying the expect script i.e. added some lines after "send"

expect -c "
spawn tdwallet add $StringName
expect \"^Enter\"
send \"Krishna123\r\"
expect eof
catch wait reason
exit [lindex $reason 3]
"

But it is returning always a non-zero value irrespective of process's failure/success.

Could you give me some pointers in identifying the correct exit code whenever process fails/success.

Thanks in advance

regards,
Srikrishna Erra.

like image 526
Srikrishna Erra Avatar asked Apr 19 '26 21:04

Srikrishna Erra


1 Answers

The problem is the $reason is getting substituted by your shell (and not expect). Moreover, it's probably being substituted with the empty string, which leads to a syntax error. The quickest way to fix this is to put a backslash in front of the $, like this:

expect -c "
spawn tdwallet add $StringName
expect \"^Enter\"
send \"Krishna123\r\"
expect eof
catch wait reason
exit [lindex \$reason 3]
"

OTOH, it would probably be better now that you're getting up to this level of complexity to put that script in a separate file so you can reduce the number of backslashes. At that point, you then switch to passing the thing to add as a command line argument.

Thus, in addWallet.exp you have this:

spawn tdwallet add [lindex $argv 0]
expect "^Enter"
send "Krishna123\r"
expect eof
catch wait reason
exit [lindex $reason 3]

And then your main script is this:

expect addWallet.exp $StringName

That's much easier to work with!

like image 179
Donal Fellows Avatar answered Apr 21 '26 22:04

Donal Fellows