我想在启动后运行多个脚本。机器启动时,一个脚本将运行并强制重启。然后,重启后,另一个脚本将运行,然后重启。这需要发生大约四次。这可能吗?
答案1
是的,这是可能的。您可以将系统的当前状态保存到日志文件中。然后主脚本可以读取最后写入的状态并有条件地运行某个脚本或函数。以下是此类脚本的示例:
$ cat ~/status-reboot.sh
#!/bin/bash
STATUS_LOG="$HOME/our.status.log"
# Determinate whether the log file exists ? get the status : set status0
if [[ -f $STATUS_LOG ]]
then
CURRENT_STATUS="$(cat "$STATUS_LOG")"
else
CURRENT_STATUS="stage0"
echo "$CURRENT_STATUS : $(date)"
echo "$CURRENT_STATUS" > "$STATUS_LOG"
# You could reboot at this point,
# but probably you want to do action_1 first
fi
# Define your actions as functions
action_1()
{
# do the 1st action
CURRENT_STATUS="stage1"
echo "$CURRENT_STATUS : $(date)"
echo "$CURRENT_STATUS" > "$STATUS_LOG"
exit # You could reboot at this point
}
action_2()
{
# do the 2nd action
CURRENT_STATUS="stage2"
echo "$CURRENT_STATUS : $(date)"
echo "$CURRENT_STATUS" > "$STATUS_LOG"
exit # You could reboot at this point
}
case "$CURRENT_STATUS" in
stage0)
action_1
;;
stage1)
action_2
;;
stage2)
echo "The script '$0' is finished."
;;
*)
echo "Something went wrong!"
;;
esac
以下是它在命令行中的工作方式:
$ ./status-reboot.sh
stage0 : Thu Aug 6 22:45:29 EEST 2020
stage1 : Thu Aug 6 22:45:29 EEST 2020
$ ./status-reboot.sh
stage2 : Thu Aug 6 22:45:33 EEST 2020
$ ./status-reboot.sh
The script './status-reboot.sh' is finished.
$ ./status-reboot.sh
The script './status-reboot.sh' is finished.
我认为它应该可以毫无问题地与 crontab 条目一起工作,如下所示:
@reboot sleep 15 && "$HOME/status-reboot.sh" >> "$HOME/our.progress.log"
- 请在 crontab 使用的脚本中使用命令的完整路径。