ข้ามไปเนื้อหาหลัก

git rebase --onto — ย้าย commits ไปอยู่บน branch อื่น

git rebase --onto ตัด commits ออกจาก branch หนึ่งแล้วปลูกลงบนอีก branch — ใช้เมื่อ branch แตกมาจากจุดผิดหรือต้องการ cherry-pick ช่วง commits

สถานการณ์: feature แตกมาจาก topic แต่ต้องการ rebase ตรง main แทน

main  ─── A ─── B
                 \
topic             C ─── D
                          \
feature                    E ─── F
# ย้าย E–F ออกจาก topic ไปต่อที่ main
git rebase --onto main topic feature
main  ─── A ─── B ─── E' ─── F'
                 \
topic             C ─── D

ลบ commits บางส่วน: ตัด commits C–D ออก เก็บแค่ E–F

# syntax: --onto <newbase> <upstream> <branch>
git rebase --onto main D feature
# D = commit ก่อน E (exclusive) → เริ่ม replay จาก E

ใช้บ่อยสำหรับ:

  • Branch ที่สร้างมาจาก feature branch ที่ยังไม่ merge — ต้องการ rebase ตรง main
  • ตัด hotfix commit ออกจาก chain ยาว
  • แก้ไขเมื่อ git checkout -b จากจุดที่ผิด