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

如何在Bash中将git log输出拆分为提交信息数组?

问题:从Git Log输出按提交拆分生成Bash数组

我不擅长Bash,想要从git log --name-status branch_one...branch_two命令的输出中提取信息,将输出按提交拆分,生成一个字符串数组,每个元素对应一条提交的完整信息。

示例输入

git_command_output="
commit one
Author: Johny
Date: 01/01/1999

feat: add something

M src/some_file.txt

commit two
Author: Alex
Date: 02/01/1999

fix: bug

M src/some_file.txt"

期望输出

数组每个元素对应一条提交信息,示例如下:

echo "${array[0]}" 

# Author: Johny
# Date: 01/01/1999

# feat: add something

# M src/my_file.txt

echo "${array[1]}" 

# Author: Alex
# Date: 02/01/1999

# fix: bug

# M src/foreign_file.txt

尝试过的无效方法

array[0]=$(echo "$git_command_output" | awk '{split($0, array, "commit"); print array[0]}')
IFS='commit' read -r -a array <<< "$git_command_output"

请问有没有简洁的实现方式,最好使用awk?


解决方案

可以用awk先将每个提交的内容处理成空字符\0分隔的字符串(避免和内容中的字符冲突),再通过Bash的readarray命令读取到数组中,具体命令如下:

readarray -d '' array < <(echo "$git_command_output" | awk '
    /^commit/ {
        if (commit_content != "") {
            printf "%s\0", commit_content
        }
        commit_content = ""
        next
    }
    {
        commit_content = commit_content (commit_content != "" ? "\n" : "") $0
    }
    END {
        if (commit_content != "") {
            printf "%s\0", commit_content
        }
    }
')

逻辑说明

  1. awk处理部分:
    • 匹配到以commit开头的行时,若已累积上一个提交的内容,就用\0分隔输出,然后重置累积变量,跳过当前行(不需要保留commit xxx这行)。
    • 其他行全部累积到commit_content变量中,保留原有的换行格式。
    • 处理到末尾时,输出最后一个提交的内容。
  2. Bash读取部分:
    • readarray -d ''以空字符作为分隔符读取内容,确保每个提交的完整内容被存入数组的单个元素中,不会因内容中的空格、换行导致拆分错误。

验证输出

执行命令后,打印数组元素即可得到期望结果:

echo "${array[0]}"

输出:

Author: Johny
Date: 01/01/1999

feat: add something

M src/some_file.txt
echo "${array[1]}"

输出:

Author: Alex
Date: 02/01/1999

fix: bug

M src/some_file.txt

内容的提问来源于stack exchange,提问作者Slava.In

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 01:50:25