git - 使用 shell 脚本更改 *n* 次提交的 git 历史记录(提交日期)

标签 git shell git-rebase git-rewrite-history

我的问题的总体情况:

我想写一个脚本到change the history最后 n 次提交到今天,例如:./myscript.sh 5 将更改最后一次的提交日期 今天有 5 项 promise 。

来自this link ,我可以:

  1. 上次提交的日期设置为当前日期
  2. 最后提交的日期设置为任意日期
  3. 任意提交的日期设置为任意日期或当前日期

因为我想要的是更改最后n次提交的历史记录,而不仅仅是1次,所以我必须采用第三种技术,它需要调用git rebase -i 并打开一个编辑器。我想编写一个脚本来自动执行此任务。


以下是手动完成任务的方式(将最近 5 次提交的提交日期更改为今天):

git rebase -i HEAD~5

然后打开编辑器

pick 81888d1 committed 9 months ago
pick 7363124 committed a month ago
pick eea43f7 committed yesterday
pick 48c3e85 committed yesterday
pick a62cbec commit recently
# change all the `pick` to `edit`

关闭编辑器,重复以下操作5次

GIT_COMMITTER_DATE="$(date)" git commit --amend --no-edit --date "$(date)"
git rebase --continue

完成。


约束:因为我提前知道我在编辑器中所做的部分是将所有 pick 关键字替换为 edit,所以我希望它默默地完成。只需输入 ./myscript.sh 5 即可完成工作,无需打开任何编辑器。我该如何做到这一点(在脚本中)


在答案的帮助下,这是我的最终脚本:

#!/bin/bash

# wish design:
#./myscript.sh [number of days]
#./myscript.sh 5 # make the last 5 commits's commit dates to today

declare -r integer_pattern="^[0-9]+$"

if [[ $1 =~ $integer_pattern ]]; then
  count=$1

  GIT_SEQUENCE_EDITOR="sed -i -re 's/^pick /e /'" git rebase -i "HEAD~$count"

  for ((i=0; i<count; i++)); do
    GIT_COMMITTER_DATE="$(date)" git commit --amend --no-edit --date "$(date)"
    git rebase --continue
  done

else
  echo "invalid argument [number of days] $1"

fi

最佳答案

将 n 次提交压缩为一次可以在没有 rebase 交互的情况下完成......甚至根本不需要 rebase。要压缩最后 5 次提交,您可以这样做:

git reset --soft HEAD~5
git commit -m "some comment"

你就完成了

关于git - 使用 shell 脚本更改 *n* 次提交的 git 历史记录(提交日期),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59523376/

相关文章:

git:如何在通过文件删除进行 rebase 提交时不删除文件

git - 从我在本地没有的远程 git 历史记录中删除一个提交

Git rebase interactive 最后 n 次提交

linux - 如何在shell脚本中跳转解压目录?

windows - 从 Windows 转到 centOS 时 Composer 无法正常工作

git - 在 IntelliJ IDEA、WebStorm、RubyMine 等中更改 GIT 登录名/用户名

git - 如何恢复删除的文件

git - 如何在保留特定目录的同时将其他分支与我的同步?

linux - SED 解析时间戳之间的 apache 日志

linux - 如何将 sed 与模式文件和 sed 一起使用