返回

Git回退到指定版本

不怕出错的方法

   
摘要GPT
摘要小助理暂时失联跑路啦……😜

git回退到上个版本

git reset --hard HEAD^

回退到前3次提交之前,以此类推,回退到n次提交之前

git reset --hard HEAD~3

回退到指定版本

查看 commit 哈希值

 git reflog

红色框框的就是哈希值


例如我要回退到commit信息为: 版本005 的时候,对应哈希值: adacc9e

git reset --hard adacc9e

更多版本

要回退到更久之前的版本,使用脚本:

q 退出 再按序号选择版本

#!/bin/bash

# 显示git的reflog
git reflog

# 提取reflog输出的序号和对应的提交哈希值,并将其存储在数组中
mapfile -t commit_array < <(git reflog | grep -E '^[a-f0-9]+' | cat -n)

# 显示序号和对应的提交哈希值供用户选择
for ((i=0; i<${#commit_array[@]}; i++)); do
  echo "${commit_array[i]}"
done

# 提示用户输入要恢复的版本号前面对应的数字
read -p "请输入要恢复的版本号前面对应的数字: " version_number

# 提取用户选择的提交哈希值
selected_commit_hash=$(echo "${commit_array[version_number-1]}" | awk '{print $2}')

# 使用git reset --hard命令将本地代码回退到指定版本
git reset --hard "$selected_commit_hash"

知识共享许可证 CC BY-NC-SA 4.0
最后更新于 2024-07-17 18:28
使用 Hugo 构建
主题 hugo-magic小洋葱 魔改 由 Jimmy 设计
Written by Human, Not by AI