【问题标题】:bash script to execute from where it was failed last timebash 脚本从上次失败的地方执行
【发布时间】:2015-10-07 12:08:17
【问题描述】:

谁能告诉我如何编写一个脚本以从上次停止的地方执行。我的 bash 脚本包含 24 个按顺序执行的脚本文件。但是,如果任何一个脚本失败,下次当我执行脚本文件时,我不希望脚本从 script1 开始,而是应该从上次失败的地方开始。请指教。

【问题讨论】:

  • 听起来你需要一个依赖于一些状态文件的makefile,这些文件会随着make过程的进行而写入

标签: linux bash scripting


【解决方案1】:

一种粗略的方式:

#!/bin/bash
# Needs bash 4 or later, for `;&` to work
[ "$1" = "--frest_start" ] && rm statusfile

touch statusfile
read status < statusfile
[ "$status" = "" ] && status=0

case $status in
0) ./script1; echo 1 > statusfile ;&
1) ./script2; echo 2 > statusfile ;&
2) ./script3; echo 3 > statusfile ;&

# ....... & so on till

23) ./script24; echo 24 > statusfile ;;

esac

但是通过Makefile 进行操作似乎也是一个不错的解决方案...

.NOTPARALLEL
.PHONY: all frest_start

all:
    make step1
    make step2
    make step3
    ....
    make step24

step%: script%
    "./$<"
    touch "$@"

frest_start:
    rm step*
    make all

【讨论】:

  • 请注意;&amp; 需要bash 4 或更高版本。
  • 如果这对您有用,请不要忘记将其标记为已接受的答案...另外,为了我的信息,请告诉我,您使用了 2 个选项中的哪一个 - bash/makefile?
  • 嗨,Anish,我使用了第一种方法..但是我根据我的要求对该脚本进行了一些更改..
【解决方案2】:
#mail.sh

function errortest {
    "$@"
    local status=$?
    if [ $status -ne 0 ]; then
        echo "error with $1" >&2
    fi
    return $status
}
errortest sh /home/user1/test1.sh
errortest sh /home/user1/test2.sh

每当脚本发生任何错误时,都会在终端上给出错误。我在我的机器上测试过。

【讨论】:

  • 不要将你的函数名称为testtest 是一个 bash 内置。
  • 这只是报错。它不允许脚本在上一个错误后从中断处继续。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-01-19
  • 2017-12-28
  • 2020-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-21
相关资源
最近更新 更多