Reputation: 141
I have a bash script that is calling an expect script in a for loop. This loop creates users in the bash script.
EXPECT SCRIPT:
# Define variables for arguments passed into the script
set user [lindex $argv 0]
set role [lindex $argv 1]
set email [lindex $argv 2]
set passwd [lindex $argv 3]
# Run the CLI command for users and expect the required output
spawn cli users add -username $user -role $role -email $email
expect "*assword:"
send "$passwd\r"
expect "*assword:"
send "$passwd\r"
expect {
default { send_user "\nERROR: $user was NOT created successfully.
Exiting script.\n"; exit 1 }
"*added to the system successfully*"
}
interact
BASH SCRIPT FOR LOOP:
for role in $user_roles
do
expect_scripts/users.exp $role"1" $role $user_email $password
done
Now, what I want to happen is if the user is not created in the expect script, exit the expect script with an error and fail in the FOR loop. I want the FOR loop to exit completely.
I cannot figure out how to do this, as it seems that my expect script is failing with the desired error but the FOR loop continues. Any help would be greatly appreciated.
Upvotes: 1
Views: 385
Reputation: 6387
A bash for loop will not fail if part of its body returns non-zero. You have to explicitly test for it, and handle it. For example:
for role in $user_roles
do
expect_scripts/users.exp $role"1" $role $user_email $password
if [ $? -ne 0 ]; then
exit 1;
fi
done
You can of course shorten this in a single line as so:
for role in $user_roles
do
expect_scripts/users.exp $role"1" $role $user_email $password || exit 1
done
Also, if you don't want to exit the script you can replace exit 1
with break
, which will cause the for loop to terminate, but will not exit the script.
Upvotes: 2