How to have a Shell script continue after reboot?

2019-05-30 15:15发布

I have a Shell script that needs to run in a loop, and perform a series of commands, and when it's finished repeat, hence the loop. Between each command there is a sleep command for a few minutes. The "job" should never terminate. I can have the script start a boot time, but it needs to continue where it left off in the sequence for the commands when the system is rebooted.

How can I best accomplished this? Should I create a MySQL table of the queue of commands, and have it delete each row after each time it successfully executes it? Then when it completes the loops it would re-populate the queue table and start from the top.

It seems like I'm missing something to make this more simple. Thanks in advance for your helpful insight!

标签: mysql shell
3条回答
Deceive 欺骗
2楼-- · 2019-05-30 15:54

MySQL sounds like a pretty complex solution for this case. In general I would think about some sort of filesystem based markers. You could keep the current state of execution in one or more files e. g. in /var/run and make your script check for these files when it starts up.

When you complete one step, you rename the file to reflect the next step that needs to be done and so on.

At the end, rename it or remove it so that the next time the script runs, it will start a new cycle.

查看更多
We Are One
3楼-- · 2019-05-30 16:08

You may want to rewrite your code so that it looks like this:

while: ; do
    case $step in
        0) command_1 && ((step++)) ;;
        1) command_2 && ((step++)) ;;
        ...
        9) command_9 && step=0 ;;
        *) echo "ERROR" >&2 ; exit 1 ;;
    esac
done

So you would be aware of what has been done by testing the value of step.

Then, you may want to set a trap before the while loop is executed, so that, on exit, the value of step is written to a log file:

trap "echo step=$step > log_file" EXIT

Then, all you need to do is to source the log file at the beginning of the script, and the last one will continue its job where it has been stopped.

查看更多
干净又极端
4楼-- · 2019-05-30 16:08

I think you can use a cron job for this. A cron job can run each minute and with a "lock file" strategy you can run the script only if the lock file is not present hence when the previous running script was ended.

查看更多
登录 后发表回答