Abdul Latheef
Abdul Latheef

Reputation: 23

How to exit from expect and bash script

I have written an expect script inside a for loop bash script. When a condition is met during expect script, script will exit with 'exit' command. But it will come to bash script and again goes for next iteration. If I provide break statement in bash script, it will affect all conditions. Please suggest how can I implement this.

for i in `cat /tmp/downtimehosts.txt`
do
{
y=$( expr $y + 1 )
j=$(echo $i | awk -F. '{print $1}')
host=$(cat /tmp/ipmon_host_db.txt | grep $j | awk '{print $4}')
ipmon=$(cat /tmp/ipmon_host_db.txt | grep $j | awk '{print $2}')

if [ $? -eq 0 ]
then
{
/usr/bin/expect -c "
spawn ssh $username@$ipmon
expect {
-re ".*Are.*.*yes.*no.*" {
send \"yes\r\"
exp_continue
}
"*?ssword:*" {
send \"$password\r\"
expect "password" {
send "quit\r"
exit
}
}}
expect "denied" {
send "quit\r"
exit
}
expect "~]$"
send \"sudo su -\r\"
expect "password"
send \"$password\r\"
expect "~]"
send \"/apps/bin/schedule-downtime.pl -v -h "$host" -d 
"$his"\r\"
expect "~]"
send \"logout\r\"
expect "~]"
send \"logout\r\"
expect eof"
}
else
:
fi
}
done

In the above if password is wrong, it must exit the expect script as well as bash script.

Upvotes: 1

Views: 4863

Answers (1)

Jack
Jack

Reputation: 6158

If there is an error in your expect script, return a non-zero value, e.g., exit 23.

Then in your bash code, check the result with $?. If it is not zero, break out of the loop:

ret_val=$?
if [ $ret_val -ne 0 ]; then
   break
fi

Upvotes: 3

Related Questions