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

请求优化Shell脚本:将my.cnf中[mysqld]段移至#SAFE#类段上方

问题需求

需要将MySQL配置文件my.cnf中的[mysqld]段及其所有内容移动到#SAFE#类段的上方,且两段之间保留空白行。这里的#SAFE#类段包含三种格式:##SAFE##、#SAFE#、# SAFE #。

以下是当前使用的Shell脚本、实际my.cnf内容及预期输出,请求技术支持:

现有脚本

#!/bin/bash
for server in `cat /home/servers.txt'`
username=$1
password=$2
do
sshpass-p $PWD ssh -o stricthostchecking=no $USERNAME@$server "ed -s /home/my.cnf <<'EOF'
/^\[mysqld\]$/;/^\[.*/ -1m$
?\[mysqld\]?i

.
w
EOF"
done

实际my.cnf内容

[client]
   a=2
   b=7
   
   [mysql]
    d=6
    e=7
 
   [mysqld]
    
    disable-log-bin = 1
    
    skip-name-resolve = 1
    performance-schema = 0
    local-infile = 0
    mysqlx = 0
    open_files_limit = 200000
    max_allowed_packet = 256M
    sql_mode="NO_ENGINE_SUBSTITUTION"

    #the below are password related of [mysqld]
     validate password=1
    
    innodb_dedicated_server = 1
    innodb_buffer_pool_instances = 48
    
    [myisamck]
    a=3
    b=4
    
    [sst]
    d=3
    c=4
    
    # SAFE #
    d=0
    f=0

预期输出

[client]
   a=2
   b=7
   
   [mysql]
    d=6
    e=7
    
    [myisamck]
    a=3
    b=4
    
    [sst]
    d=3
    c=4
    
   [mysqld]
    
    disable-log-bin = 1
    
    skip-name-resolve = 1
    performance-schema = 0
    local-infile = 0
    mysqlx = 0
    open_files_limit = 200000
    max_allowed_packet = 256M
    sql_mode="NO_ENGINE_SUBSTITUTION"
    
    #the below are password related of [mysqld]
     validate password=1

    innodb_dedicated_server = 1
    innodb_buffer_pool_instances = 48
    
    # SAFE #
    d=0
    f=0

解决方案

修正后的脚本

原脚本存在语法错误、匹配逻辑不全等问题,以下是修复后的版本:

#!/bin/bash
# 校验参数是否完整
if [ $# -ne 2 ]; then
    echo "用法: $0 <用户名> <密码>"
    exit 1
fi

USERNAME="$1"
PASSWORD="$2"

# 遍历服务器列表,兼容文件名含空格的情况
while IFS= read -r server; do
    # 跳过空行和注释行
    [[ -z "$server" || "$server" =~ ^# ]] && continue

    sshpass -p "$PASSWORD" ssh -o StrictHostKeyChecking=no "$USERNAME@$server" "ed -s /home/my.cnf <<'EOF'
# 定位[mysqld]完整段落:从[mysqld]行到下一个[开头行的前一行
/^\[mysqld\]$/,/^\[.*\]$/-1m/#^#+\s*SAFE\s*#+$/-1
# 在#SAFE#段前插入空行,保证段间空白
/#^#+\s*SAFE\s*#+$/-1i

.
w
EOF"
done < /home/servers.txt

关键修正点说明

  1. 语法修复:
    • 修正sshpass-p为正确的sshpass -p格式
    • 替换错误的$PWD为传入的密码变量$PASSWORD
    • 改用while read循环读取服务器列表,避免文件名含空格时的遍历错误
  2. 匹配逻辑优化:
    • /^\[mysqld\]$/,/^\[.*\]$/-1:精准匹配[mysqld]的完整段落,包含所有子配置项
    • #^#+\s*SAFE\s*#+$:正则匹配所有#SAFE#类格式,包括#SAFE#、# SAFE #、##SAFE##
    • m/#^#+\s*SAFE\s*#+$/-1:将[mysqld]段移动到#SAFE#类段的前一行
  3. 格式保证:通过/#^#+\s*SAFE\s*#+$/-1i插入空行,确保[mysqld]和#SAFE#段之间保留空白间隔

验证方式

执行脚本后,登录目标服务器查看/home/my.cnf,确认[mysqld]段已移动到#SAFE#类段上方,且两段之间存在空白行即可。


内容的提问来源于stack exchange,提问作者Raj

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 00:01:36