[Git] How To Undo Merge

Macus.y
2 min readAug 26, 2022

--

สถานการณ์ Pull Request ผิด Branch เกิดขึ้นได้เสมอแม้เราจะ Protected Branch แล้ว ด้วยเหตุผลต่างๆ เราสามารถ Undo Merge ได้ แต่ต้องตรวจสอบผลกระทบหลังการ Reset Merge ก่อนการ Reset Merge ด้วยนะครับ

จากรูปด้านบนจำลองสถานการณ์ การ Merge Branch [origin]features/sample2 เข้า [origin]main โดยไม่ตั้งใจหรือตั้งใจก็ตามแต่ แต่ต้องการเอา [origin] features/sample2 ออกจาก [origin]main โดยต้องการให้ [origin]main กลับไปอยู่ที่ Commit ก่อนหน้าคือ Merge pull request #1 from pichayean/features/sample1 [ec9d1e7]

ตัวอย่าง Content หลังการ Merge ที่ไม่ต้องการ เราไม่ต้องการ บรรทัดที่เป็น [sample2] เพราะว่ามาจาก branch [origin]features/sample2

Content หลังการ Merge [origin]features/sample2 -> [origin]main

Let’s do it

  1. [ทำที่ Local repository] ไปที่ branch main and git fetchนี้ถ้า main ไม่เท่ากับ origin ให้ pull ลงมา
  2. USEgit log OR git reflog (เพื่อหา commit ID โดยในตัวอย่างนี้คือ[a69d480])
  3. Revert to Selected Commit (ในกรณีที่เรารู้ commit ID ที่ต้องการกลับไป)
git reset --merge a69d480
content กลับมาเป็น ที่เราต้องการ

3. Or The HEAD Shorthand

The Git HEAD keyword refers to the latest commit in your repository. You can use the Git HEAD shorthand to undo a merge:

git reset --merge HEAD~1

4. -f Push Notes ****ระมัดระวังนะ****

If you need to push the branch to the remote, and you have already pushed the merge, you need to use:

git push -f origin main
กลับไปที่ Commit ที่ต้องการแล้ว

เสร็จเรียบร้อย ✨✨

ถ้ามีส่วนไหนที่ ไม่ถูกต้องหรือ มีวิธีที่ดีกว่า สามารถแนะนำเพิ่มเติมได้เลยนะครับ
ขอบคุณมากครับ

--

--

Macus.y
Macus.y

Written by Macus.y

“Many of life’s failures are people who did not realize how close they were to success when they gave up.”– Thomas A. Edison 😇😇😇

No responses yet