我有一个bash脚本,它在一个sql脚本文件夹上迭代。当脚本遇到错误时,我希望它能智能地运行。我不想跑两步。
for a in $files_list; do
command 1
command 2
.
.
done
如果1、2、3、4、5是要执行的文件,则脚本在步骤3退出并出现一些错误。在下一次执行中,我只想从步骤3开始运行。我有一个变量,用于检测脚本在哪个步骤退出。我一直坚持从那个变量开始迭代。这是可以做的事情吗?任何建议都可以接受。我也愿意改变我的逻辑。
确实没有花太多时间,但假设您想要执行的所有命令都存储在test.txt
文件中
test.txt
ls
cal
du
d
date
ls
下面的bash脚本采用两个参数filename
(存储命令的位置(和checkpoint
(需要启动的位置(。
测试.sh
## Function to read a file line by line
checkpoint=$2
filename=$1
checkpointReached=false
read_file_line_by_line() {
local file="$1"
while IFS= read -r line
do
if [ $checkpointReached == "false" ] && [ "$line" != "$checkpoint" ] ; then
echo "...... Finding checkpoint....... current line is $line"
fi
if [ "$line" == "$checkpoint" ]; then
echo " *************************************************
Checkpoint reached. Commands after checkpoint
*****************************************************"
checkpointReached=true
continue
fi
if $checkpointReached; then
echo " $line"
execute_command $line
fi
done < "$file"
}
function execute_command() {
local command="$1"
echo " Executing .......... $command"
if eval $command; then
echo " Command executed successfully"
else
echo " Command failed. Exiting........"
echo " Please note the new checkpoint.... $command"
exit 1
fi
}
read_file_line_by_line "$filename"
让我们第一次运行它,检查点是第一个命令,即ls,它预计在d
失败,这是无效命令
╰─ bash test.sh text.txt "ls"
*************************************************
Checkpoint reached. Commands after checkpoint
*****************************************************
Executing .......... ls
test.sh test.yaml text.txt
Command executed successfully
du
Executing .......... du
24 .
Command executed successfully
d
Executing .......... d
test.sh: line 33: d: command not found
Command failed. Exiting........
Please note the new checkpoint.... d
现在我们知道了检查站。所以我们把它传下去。假设d
现在是固定的,为了脚本起见,我们将其更改为echo
。在您的情况下,脚本d
将被修复。
╰─ bash test.sh text.txt "echo"
...... Finding checkpoint....... current line is ls
...... Finding checkpoint....... current line is du
*************************************************
Checkpoint reached. Commands after checkpoint
*****************************************************
Executing .......... echo
Command executed successfully
date
Executing .......... date
Mon Sep 12 14:50:44 +04 2022
Command executed successfully
如果这有帮助,请告诉我。