TIL/TIL

[TIL] HEAD 가 아닌 과거 Commit 수정하기 (git rebase + amend)

아람2 2026. 2. 9. 23:17
반응형

Commit 을 여러 개 쌓았는데 중간에 있는 Commit 에 빠뜨린 게 있었다

6c381c2 Feat: 기능 추가
8b8dba7 Refactor: 리팩토링
a775b72 Feat: 다른 기능
9b31d5a Chore: echo 메시지 정리  👈 여기에 추가하고 싶음
c01b112 Feat: 이전 기능

git commit --amend 는 HEAD 만 수정 가능하다

이럴 때 rebase -i 를 쓴다

💡 해결: interactive rebase + amend

과거 Commit 을 수정하려면 rebase -i 로 해당 Commit 에 멈춰야 한다

📋 전체 흐름

1. 작업 중인 변경사항 stash
2. rebase -i 로 해당 Commit 에서 멈춤 (edit 모드)
3. stash pop 으로 변경사항 복구
4. amend 로 Commit 에 추가
5. rebase --continue 로 나머지 Commit 적용

🛠️ 실제 명령어

# 1. 현재 변경사항 stash
git stash push -m "추가할 변경사항" path/to/file.sh

# 2. interactive rebase 시작 (해당 Commit 을 edit 으로 변경)
GIT_SEQUENCE_EDITOR="sed -i '' 's/^pick 9b31d5a/edit 9b31d5a/'" git rebase -i 9b31d5a~1

# 3. stash 에서 변경사항 가져오기
git stash pop

# 4. 변경사항 추가하고 amend
git add path/to/file.sh
git commit --amend --no-edit

# 5. 나머지 Commit 적용
git rebase --continue

🧠 핵심 포인트

  1. GIT_SEQUENCE_EDITOR 👈 -i 플래그의 에디터 열림 방지
  2. Commit~1 👈 해당 Commit 의 부모부터 rebase 시작
  3. --no-edit 👈 Commit 메시지 유지

⚠️ 주의사항

# ❌ unstaged 변경사항 있으면 rebase 안 됨
error: cannot rebase: You have unstaged changes.

# ✅ 다른 파일 변경사항도 전부 stash
git stash push -m "other" -- file1.py file2.py

여러 파일 작업 중이면 다 stash 해야 한다

📊 stash 관리

# stash 목록 확인
git stash list
# stash@{0}: On main: other changes
# stash@{1}: On main: 추가할 변경사항  👈 이거 먼저 넣었음

# 특정 stash 만 pop
git stash pop stash@{1}

stash 는 Stack 구조라서 나중에 넣은 게 0번이다

Stack: LIFO (Last In, First Out) 구조. 접시 쌓기처럼 마지막에 올린 게 먼저 나온다

📈 결과

6c381c2 Feat: 기능 추가
8b8dba7 Refactor: 리팩토링
a775b72 Feat: 다른 기능
9b31d5a Chore: echo 메시지 정리  👈 변경사항 추가됨!
c01b112 Feat: 이전 기능

히스토리는 깔끔하게 유지하면서 과거 Commit 수정 완료

🎯 결론

HEAD 가 아닌 Commit 수정이 필요하면:

  1. 변경사항 stash
  2. rebase -i 로 edit 모드 진입
  3. stash popaddamend
  4. rebase --continue

새 Commit 으로 쌓는 것보다 히스토리 관리에 좋다

단, push 전에만 해야 한다 🐣 이미 push 했으면 force push 필요 🐣 

반응형