我有一个bash
调用expect
脚本的脚本。
Expect 脚本有几个条件。它通过 ssh 进入一个盒子并执行命令,并且可能会发生不同的错误,我给出了退出代码,如下所示:
expect {
"passwd: password updated successfully" {
exit 0
}
"Password unchanged" {
exit 1
}
"Bad: new and old password are too similar" {
exit 2
}
"You must choose a longer password" {
exit 3
}
}
我计划获取这些退出代码并在调用 Expect 脚本的 bash 脚本中使用它们,如下所示:
if [ $? -eq 0 ]; then
echo -e "\n"
echo "Password successfully changed on $host by $user"
elif [ $? -eq 1 ]; then
echo "Failure, password unchanged"
elif [ $? -eq 2 ]; then
echo "Failure, new and old passwords are too similar"
elif [ $? -eq 3 ]; then
echo "Failure, password must be longer"
else
echo "Password failed to change on $host"
fi
但这是行不通的。看起来expect脚本只在成功时返回0,在失败时返回1,无论在哪里失败。是否可以检索我分配的退出代码并在 bash 脚本中使用它们?
或者在期望脚本中使用“send_user”来描述错误会更好吗?如果是这样,我怎样才能让bash脚本使用expect中“send_user”命令的输出?
答案1
更简单的方法是使用case
语句而不是$?
重复检查:
case "$?" in
0) echo "Password successfully changed on $host by $user" ;;
1) echo "Failure, password unchanged" ;;
2) echo "Failure, new and old passwords are too similar" ;;
3) echo "Failure, password must be longer" ;;
*) echo "Password failed to change on $host" ;;
esac
答案2
您需要将返回值初始化为临时变量。像这样:
./my_expect_script.expect
a=$?
if [ $a -eq 0 ]; then
echo -e "\n"
echo "Password successfully changed on $host by $user"
elif [ $a -eq 1 ]; then
echo "Failure, password unchanged"
elif [ $a -eq 2 ]; then
echo "Failure, new and old passwords are too similar"
elif [ $a -eq 3 ]; then
echo "Failure, password must be longer"
else
echo "Password failed to change on $host"
fi