You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Bash脚本从迭代中断点处继续执行SQL脚本

实现断点续执行的Bash SQL脚本方案

核心思路

通过一个状态记录文件追踪已成功执行的SQL脚本,脚本启动时读取该文件,跳过已完成的部分,直接从上次出错的文件开始执行。

具体实现代码

#!/bin/bash

# 配置项
files_list="1.sql 2.sql 3.sql 4.sql 5.sql"  # 按执行顺序排列的SQL文件列表
state_file="./sql_exec_state.txt"  # 记录执行进度的状态文件

# 初始化状态文件:不存在则创建空文件
[ ! -f "$state_file" ] && touch "$state_file"
last_executed=$(cat "$state_file")

for sql_file in $files_list; do
    # 跳过已成功执行的文件
    if [ -n "$last_executed" ] && [ "$sql_file" != "$last_executed" ]; then
        echo "跳过已完成文件: $sql_file"
        continue
    fi

    # 重置标记,开始执行当前及后续文件
    last_executed=""

    echo "开始执行: $sql_file"
    # 替换为你的实际SQL执行命令,比如mysql、psql等
    if ! mysql -u your_user -p'your_password' -D your_database < "$sql_file"; then
        echo "执行失败: $sql_file"
        # 记录当前失败的文件,下次从这里启动
        echo "$sql_file" > "$state_file"
        exit 1
    fi

    echo "执行成功: $sql_file"
    # 更新状态为当前成功的文件
    echo "$sql_file" > "$state_file"
done

# 全部执行完成后清空状态文件
echo "" > "$state_file"
echo "所有SQL脚本执行完毕"

优化建议

  • 有序文件列表:如果文件名是数字编号,用files_list=$(ls *.sql | sort -n)自动生成有序列表,避免手动排序出错。
  • 错误日志:给每个失败的文件单独记录错误日志,方便排查:
    mysql -u your_user -p'your_password' -D your_database < "$sql_file" 2>> "${sql_file}.err"
    
  • 原子性执行:如果command1和command2是一组关联操作,封装成函数,确保要么全成功要么全失败,避免部分执行的混乱:
    execute_sql() {
        # 执行command1
        if ! command1; then
            return 1
        fi
        # 执行command2
        if ! command2; then
            return 1
        fi
        return 0
    }
    
    # 调用函数
    if ! execute_sql; then
        echo "执行失败: $sql_file"
        echo "$sql_file" > "$state_file"
        exit 1
    fi
    

内容的提问来源于stack exchange,提问作者Sai Ram Metla

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 17:20:36