退出 bash 脚本 for expect 脚本 expect 错误循环
Exiting bash script for loop on expect script expect error
我有一个 bash 脚本,它在 for 循环中调用 expect 脚本。此循环在 bash 脚本中创建用户。
期待脚本:
# 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 循环脚本:
for role in $user_roles
do
expect_scripts/users.exp $role"1" $role $user_email $password
done
现在,我想要发生的是,如果用户不是在 expect 脚本中创建的,则退出 expect 脚本并出现错误并在 FOR 循环中失败。我希望 FOR 循环完全退出。
我不知道该怎么做,因为我的 expect 脚本似乎因预期的错误而失败,但 FOR 循环仍在继续。任何帮助将不胜感激。
如果循环体 returns 的一部分非零,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循环终止,但不会退出脚本。
在顶部使用 set -e
在 expect 脚本中
我有一个 bash 脚本,它在 for 循环中调用 expect 脚本。此循环在 bash 脚本中创建用户。
期待脚本:
# 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 循环脚本:
for role in $user_roles
do
expect_scripts/users.exp $role"1" $role $user_email $password
done
现在,我想要发生的是,如果用户不是在 expect 脚本中创建的,则退出 expect 脚本并出现错误并在 FOR 循环中失败。我希望 FOR 循环完全退出。
我不知道该怎么做,因为我的 expect 脚本似乎因预期的错误而失败,但 FOR 循环仍在继续。任何帮助将不胜感激。
如果循环体 returns 的一部分非零,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循环终止,但不会退出脚本。
在顶部使用 set -e
在 expect 脚本中