萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 作業系統 >  >> Linux 教學

Linux 下將 Shell 腳本轉換為 SQL 檔案的實作範例

應用場景

在自動化部署或資料庫初始化流程中,常需透過 Shell 腳本動態產生 SQL 腳本檔案。本文以建立 tb_employeeinfo 資料表為例,示範完整轉換流程。

原始 Shell 腳本(example.sh)

#!/bin/bash

function Init() {
    if [ -f "example.sql" ]; then
        echo "example.sql is exits and is deleting it,then recreate it"
        rm -f example.sql
    else
        echo "example.sql no exits and is creating it"
    fi
    echo " use zxdbp_166 " >> example.sql
    echo " go" >> example.sql
}

function CreateTable() {
    cat >> example.sql << EOF
create table tb_employeeinfo
(
    employeeno varchar(20) not null, -- 員工工號
    employeename varchar(20) not null, -- 員工姓名
    employeeage int null -- 員工年齡
);
create unique index idx1_tb_employeeinfo on tb_employeeinfo(employeeno);
create index idx2_tb_employeeinfo on tb_employeeinfo(employeename);
print 'create table tb_employeeinfo ok'
go
EOF
}

## 執行函數
Init
CreateTable

關鍵語法解析

  • Here Document(<< EOF):將多行文字直接導入檔案,保留縮排與換行,適合產生結構化 SQL。
  • 函數模組化:將初始化、建表邏輯拆分為函數,腳本尾部按序呼叫,易於維護擴充。
  • 檔案存在性檢查:-f 判斷檔案是否存在,避免重複執行產生殘留資料。

生成 SQL 檔案的完整步驟

1. 上傳腳本至 Linux 伺服器

使用 FileZilla 等 FTP 工具將 example.sh 上傳至目標目錄(如 ~/sql)。

2. 轉換換行符格式(關鍵步驟)

Windows 編輯的檔案含 CRLF(\r\n),Linux 僅識別 LF(\n),直接執行會報 Permission denied 或語法錯誤。

dos2unix example.sh

批次轉換:dos2unix file1 file2 file3

3. 賦予執行權限並執行

chmod +x example.sh
./example.sh

4. 驗證產出的 SQL 檔案

cat example.sql

預期輸出包含 use zxdbp_166、建表語句、索引建立與 go 終止符。

進階應用建議

  • 搭配 mysql -u root -p < example.sql 直接導入資料庫
  • 加入錯誤碼檢查($?)與日誌記錄,納入 CI/CD 流程
  • 使用變數參數化資料庫名、表名,提升腳本複用性

掌握 Shell 腳本動態生成 SQL 技巧,能大幅提升資料庫變更與部署的自動化程度。

copyright © 萬盛學電腦網 all rights reserved