linux - 执行 mysql 文件,并按列高亮显示

前置条件

  • 服务器要安装 mysql 客户端

创建连接配置文件

.mysql_client

[client]
host = 127.0.0.1
port = 3306
user = root
password = ↑↑↓↓←→←→BA

执行 sql 文件,并按列高亮的脚本

_mysql.sh

#!/bin/bash

######## 前置检查 ########

db="hun-dou-luo"

client_file=".mysql_client"
if [ ! -f "$client_file" ]; then
    echo "配置文件 $client_file 不存在"
    exit 1
fi

action=$1
if [ -z "$action" ]; then
    echo "第一个参数指定 action"
    echo "run <sql_file> <filter>| 运行 sql 脚本,并过滤文件【filter 非必选】"
    exit 1
fi

######## 定义函数 ########

# 彩色显示文本的函数
display_rainbow() {
    local result="$1"

    echo "$result" | awk -F'|' '  # 修改分隔符为竖线
    BEGIN {
        # 定义彩虹色(红、黄、绿、青、蓝、紫)
        colors[0]="\033[1;31m";  # 红
        colors[1]="\033[1;33m";  # 黄
        colors[2]="\033[1;32m";  # 绿
        colors[3]="\033[1;36m";  # 青
        colors[4]="\033[1;34m";  # 蓝
        colors[5]="\033[1;35m";  # 紫
        reset="\033[0m";
    }
    {
        # 计算列数
        num_cols = NF;
        
        # 分割每一行并为每列应用不同颜色
        for (i = 1; i <= num_cols; i++) {
            col = $i;
            color_idx = (i - 1) % 6;  # 循环使用颜色
            
            # 打印带颜色的列
            printf "%s%s%s", colors[color_idx], col, reset;
            
            # 如果不是最后一列,添加分隔符
            if (i < num_cols) printf " | ";
        }
        printf "\n";
    }'
}

# 定义执行SQL文件的函数
execute_sql_file() {
    local sql_file=$1
    local filter=$2

    local mysql_result=$(mysql --defaults-extra-file=$client_file $db <$sql_file | sed 's/\t/|/g')

    if [ -z "$filter" ]; then
        display_rainbow "$mysql_result"
    else
        export GREP_COLORS="ms=7" # grep 反色显示【不会影响到脚本外部】
        display_rainbow "$mysql_result" | (
            head -1
            grep --color=always "$filter"
        )
    fi

}

######## 执行命令 ########

# 运行 sql 脚本
if [ "$action" == "run" ]; then

    sql_file=$2
    if [ -z "$sql_file" ] || [ ! -f "$sql_file" ]; then
        echo "sql 文件 $sql_file 不存在"
        exit 1
    fi

    filter=$3
    execute_sql_file "$sql_file" "$filter"

# 其他情况
else
    echo "不支持 $action 命令"
    exit 1

fi

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值