gpt4 book ai didi

linux - 如何返回 bash 脚本中的特定命令?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:36:55 24 4
gpt4 key购买 nike

我需要一种方法来跟踪 bash 脚本中最后一次成功执行的命令。例如我有这个脚本:

#!/bin/bash
command1
command2

command1command2 都将返回一些退出代码。我需要的是保存最后一次成功执行的命令,当我重新运行这个脚本时,我希望它从那一点开始。因此,如果 command1 正确执行而 command2 失败,下次我运行脚本时它将从 command2 开始。

最简单的方法是将执行信息存储在附加文件中,脚本将在执行前读取这些信息。在执行命令之前,脚本会检查该命令是否已成功执行。

有更好的方法吗?有没有这个实现的例子?我想我在配置脚本中看到了类似的东西。

最佳答案

#!/bin/bash -e
#
# run those commands that did not yet run
# breaks upon failed command due to -e
#
# keeps the line number of the last successful command in lastline
#
# first, some preparation:
#

lastfile=$(readlink -f lastline) # inspired by ton1c: Get absolute path
test -f $lastfile && lastline=`cat $lastfile` >/dev/null
test -z "$lastline" && lastline=0

e()
{
thisline="$BASH_LINENO"
test $lastline -lt $thisline || return 0
"$@"
echo $thisline > $lastfile
}

#
# and now prepend every command by e
# for example run this, interrupt the sleep 5 and run again
# to restart ALL commands, remove the file "lastline"
#

echo running sleep 3
e sleep 3
echo running sleep 5
e sleep 5
echo running sleep 7
e sleep 7

关于linux - 如何返回 bash 脚本中的特定命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27731071/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com