linux - 如何让用户在通过 bash 脚本执行一堆任务时更正错误?
问题描述
我想自动化一堆任务 Task_1、Task_2、Task_3、Task_4、Task_5 -
status = Task_1
if (status == FALSE)
*give option for user to rectify the problem, once done, proceed to Task_2*
status = Task_2
if (status == FALSE)
*give option for user to rectify the problem, once done, proceed to Task_3*
status = Task_3
if (status == FALSE)
*give option for user to rectify the problem, once done, proceed to Task_4*
status = Task_4
if (status == FALSE)
*give option for user to rectify the problem, once done, proceed to Task_5*
status = Task_5
如何实现 -“为用户提供解决问题的选项,完成后,继续执行 Task_X ”的目标?
编辑:
我正在寻找类似于的功能 -
- 你执行 git pull --rebase,
- 如果存在合并问题,它会通知用户并让他们采取行动。
- 用户更正后,他们可以执行 git rebase --continue 以继续执行原来的 rebase 进程。
解决方案
通常,命令具有退出状态。如果你的任务写得很好,如果任务失败,退出状态应该是非零,如果任务成功,退出状态应该是零。因此,在 bash 中,您将编写如下内容:
#!/bin/bash
if Task_1 ; then
echo 'Task_1 succeeded'
else
#give option to rectify the problem
fi
以此类推剩余的任务。
您还可以使用最后一个任务的退出代码$?
,如
Task_1
if [ $? != 0 ] ; then
echo "Despair! Task_1 has failed"
# allow the user to do some reparations
fi
为用户提供修复选项在很大程度上取决于修复方式和您的环境。
例如,您可以显示具有固定操作的菜单,例如:
echo "a for abandon hope, b for be despaired"
read line
case "$line" in
("a")
# actions for abandoning hope
;;
("b")
# actions for being despaired
;;
("*")
echo "Unknown action; continuing without doing anything."
;;
esac
或者,有时你可以启动一个 xterm:
echo "Close terminal when the repair is finished"
xterm
(对不起那些令人沮丧的例子)