我有一个bash脚本,它在for循环中调用expect脚本。此循环在bash脚本中创建用户。
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
现在,我想要发生的是,如果未在expect脚本中创建用户,则退出expect脚本时出现错误并在FOR循环中失败。我希望FOR循环完全退出。
我无法弄清楚如何做到这一点,因为看起来我的期望脚本失败了所需的错误,但FOR循环继续。任何帮助将不胜感激。
答案 0 :(得分:1)
如果bash for循环的一部分返回非零,则它不会失败。你必须明确地测试它,并处理它。例如:
for role in $user_roles
do
expect_scripts/users.exp $role"1" $role $user_email $password
if [ $? -ne 0 ]; then
exit 1;
fi
done
您当然可以将其缩短为一行:
for role in $user_roles
do
expect_scripts/users.exp $role"1" $role $user_email $password || exit 1
done
此外,如果您不想退出脚本,可以将exit 1
替换为break
,这将导致for循环终止,但不会退出脚本。
答案 1 :(得分:-1)
set -e