본문 바로가기
개발

[Git] Git Add/Commit 되돌리기, 수정하기

by seaweed_one 2024. 2. 6.
728x90

Add / Commit 되돌리기 

1. commit 하지 않은 파일 되돌리기 

git commit을 하지 않은 파일을 되돌리고 싶은 경우 사용이 가능합니다.

// 변경 파일 확인 
git status 

// 전체 되돌리기
git checkout .

//특정 파일 혹은 디렉토리 되돌리기 
git checkout [target_file / dir ]

 

2. git add 취소하기 

파일 상태를 Unstage로 변경합니다.

// 전체 되돌리기 
git reset HEAD

// 특정 파일 되돌리기 
git reset HEAD [file]

 

3. push 하지 않은 commit 되돌리기 

push 하지 않은 commit 을 확인

git log --branches --not --remotes

git status 로도 확인이 가능하지만 위 명령어로 원격에 존재하지 않는 모든 커밋을 확인할 수 있습니다. 

 

commit 되돌리기

기본 사용 형식은 아래와 같습니다. 

git reset [Option] [target]

reset 옵션은 아래와 같습니다. 

  • --mixed(default) : commit 취소, 변경 사항 unstaged (git add 필요)
  • --soft : commit 취소, 변경사항  staged (git add 완료 상태)
  • --hard : commit 취소, 변경 사항 삭제 

mixed 옵션이 기본으로 미지정시 mixed로 실행됩니다.

//기본 옵션(가장 최근 commit 취소)
git reset --mixed HEAD^ 

//바로 이전 커밋으로 되돌리기 
git reset HEAD~1

//마지막 2개의 커밋 되돌리고 변경 내용을 워킹 디렉토리에서 삭제  
git reset --hard HEAD~2

//커밋 아이디로 취소 
git reset [Commit ID]

 

원격 저장소의 마지막 commit 으로 되돌리기 

작업 디렉터리를 원격 저장소의 마지막 commit 상태로 되돌리고 싶은 경우 사용가능합니다.

마지막 commit 이후 변경사항은 모두 사라지므로 주의가 필요합니다.

git reset --hard HEAD

 

4. push 완료 상태의 commit 되돌리기 

추천하지 않는 방법입니다. 

특히나 협업중인 git에서 사용 시에는 특별히 주의를 요합니다. 

local의 내용을 원격 저장소에 강제로 덮어쓰는 방법으로 되돌아간 commit 이후 모든 commit 정보가 사라집니다.

// 가장 최근 commit 취소 
git reset HEAD^

// 커밋 목록 확인 
git reflog 
git log

// 원하는 시점으로 워킹 dir 되돌리기 
git reset [commitId or HEAD]

// 되돌린 상태에서 commit
git commit -m "Revert a pushed commit"

// remote 로 강제 push 
git push -f origin [branch name]

 


Commit 수정하기 

1. commit 메세지 변경 

git commit --amend

// -m 옵션으로 명령줄에서 메세지 수정 
git commit --amend -m "new commit message"

 

2. commit 에 파일 추가 

file1, file2 를 수정하고 file1 만 커밋하는 실수를 저지르는 경우가 있습니다.

해당 경우에 file2 를 추가로 커밋하면 커밋이 지저분해지게 됩니다.

이때 사용 가능한 방법입니다.

 

아래 방법을 사용해 커밋 메시지 변경 없이 파일을 추가할 수 있습니다. 

// commit file list : file1 , file2 
git add file1
git commit -m "[Test] add test files"

// forgot to add file2 
git add file2
git commit --amend --no-edit

 

728x90